suran91 发表于 2022-2-3 12:24:16

pyrthon多变可嵌套循环打印换行问题

========================代码如下:
numLines=int(input("How many lines of stars do you want?"))
numStars=int(input("How many stars per line"))
for line in range(0,numLines):   
    for star in range(0,numStars):
             print('*'),
    print

========================运行结果如下:
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
========================= RESTART: D:python/打印星星.py ========================
How many lines of stars do you want?3
How many stars per line2
*
*
*
*
*
*
========================
没有按照实际的情况进行换行,请教如何处理

ckblt 发表于 2022-2-3 12:31:04

numLines = int(input("How many lines of stars do you want?"))
numStars = int(input("How many stars per line"))
for line in range(numLines):
    for star in range(numStars):
      print("*", end="")
    print()

ckblt 发表于 2022-2-3 12:34:39

或者
numLines = int(input("How many lines of stars do you want?"))
numStars = int(input("How many stars per line"))
for line in range(numLines):
    print("*" * numStars)

suran91 发表于 2022-2-3 15:59:03

感谢,已经解决

suran91 发表于 2022-2-3 16:07:48

可以详细讲下原因不~~~~因为另外一个代码又遇到了这个问题

suran91 发表于 2022-2-3 16:10:30

ckblt 发表于 2022-2-3 12:31


numBlocks=int(input("how many bloocks of stars do you want?"))
numLines=int(input("how many lines in each block?"))
代码如下~~~~~~~
numStars=int(input("how many stars per line?"))
for block in range(0,numBlocks):
    for line in range(0,numStars):
      print("*", end=""),
    print
print
运行结果如下~~~~~~~~
how many bloocks of stars do you want?4
how many lines in each block?3
how many stars per line?8
********************************

ckblt 发表于 2022-2-3 16:22:58

print改成print()

suran91 发表于 2022-2-3 18:58:23

ckblt 发表于 2022-2-3 16:22
print改成print()

感谢

suran91 发表于 2022-2-3 19:12:44

python中的print()默认以换行符"\n"结尾 即执行一次print()自动换行。

在算法与数据结构的时候,对于输出有特殊的格式要求,此时可以通过end参数来调整输出的格式
页: [1]
查看完整版本: pyrthon多变可嵌套循环打印换行问题