在python中,如何在一行上放置特定数量的整数?
在我的GCSE Comp学习课程中,我遇到了一个问题,要求我输入一个数字,然后在输入之前显示平方数,每行有5个值。我设法达到了显示平方数的程度,但它不允许我在每行上输入5个值。这是我的密码:在python中,如何在一行上放置特定数量的整数?,python,Python,在我的GCSE Comp学习课程中,我遇到了一个问题,要求我输入一个数字,然后在输入之前显示平方数,每行有5个值。我设法达到了显示平方数的程度,但它不允许我在每行上输入5个值。这是我的密码: counter = 0 number = int(input('Enter a number')) for i in range (1, number + 1): print (i * i.) counter = counter + 1 if counter % 5 == 0:
counter = 0
number = int(input('Enter a number'))
for i in range (1, number + 1):
print (i * i.)
counter = counter + 1
if counter % 5 == 0:
print \
对此问题的任何帮助都将不胜感激。Python将自动将
\n
设置为print()
函数中的end
参数的值,因此您可以手动将其设置为空格,并在计数器达到5的倍数时仅打印新行
下面是一个Python 3解决方案:
counter = 0
number = int(input('Enter a number: '))
for i in range (1, number + 1):
print (i * i, end=' ')
counter += 1
if counter % 5 == 0:
print ("\n")
如果您使用的是Python 2,只需使用以下命令修改第一条打印语句:
print i * i,
对于Python2,结尾逗号将自动用空格替换默认的结尾newlinw
因此,如果您输入20
,输出将为:
1 4 9 16 25
36 49 64 81 100
121 144 169 196 225
256 289 324 361 400
上面的答案可能适用于Python3,但由于您似乎正在使用Python2,它可能不适用于您,因此我为您提供了Python2的解决方案 您可以用方号创建一个列表,当
计数器%5==0
时,打印带空格的数字并将列表重置为空:
计数器=0
number=int(输入(‘输入一个数字’)
sqlist=[]#平方数列表
对于范围(1,数字+1)内的i:
#将平方数追加到列表中
append(str(i**2))#**是Python中的效价运算符
计数器+=1
如果计数器%5==0:
打印“.join(sqlist)
del sqlist[:]#重置列表
“输入前的平方数”建议您打印平方值,请使用完整的错误回溯更新您的问题。想法可能是以空格作为分隔符输入所有平方值,然后拆分输入。。。并处理生成的数字列表。您是否也可以提供示例输入和预期输出,以使这一点更清楚、更容易理解?您的回答可能对OP不起作用,因为他似乎在使用Python2(因为他最后一行代码“print”没有括号)。谢谢您的反馈,我同意。增加了Python2指令。
N = 123 # int(input("enter a number: "))
n = 1
while n*n<=N:
print(n*n,end=" " if n%5 else "\n") # next line on multiples of 5
n += 1
if (n-1)%5: print() # additional end of line if not multiple of 5 printed
1 4 9 16 25
36 49 64 81 100
121