簡體   English   中英

如何在 python 的一行中放置特定數量的整數?

[英]How can I put a specific amount of integers on one line in 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:
    print \

任何有關此問題的幫助將不勝感激。

Python 將自動將\n設置為print() function 中的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,

在 Python 2 的情況下,結尾逗號將自動用空格替換默認結尾newlinw

因此,如果您輸入20 ,則 output 將是:

1 4 9 16 25 

36 49 64 81 100 

121 144 169 196 225 

256 289 324 361 400 

上面的答案可能適用於 Python 3,但是由於您似乎使用的是 Python 2,它可能對您不起作用,所以我為您提供了 ZA7F5F35426B9237411FCZ232173 62317B 的解決方案。

您可以使用平方數制作一個列表,當counter % 5 == 0時,您打印帶有空格的數字並將列表重置為空:

counter = 0
number  = int(input('Enter a number'))
sqlist = [] # list of square numbers

for i in range(1, number + 1):
    # append the square number to the list
    sqlist.append(str(i ** 2)) # ** is the potency operator in Python
    counter += 1 
    if counter % 5 == 0:
        print " ".join(sqlist)
        del sqlist[:] # reset the list

“輸入之前的平方數”建議您應該打印 <= 到輸入的平方值。 您的代碼會根據輸入打印出許多正方形。

while 循環將是將平方值限制為輸入的更好方法。 要在同一行打印 5,您需要防止前四個進入下一行,您可以使用打印 function 的end=參數來執行此操作。

如果要打印的方格數不是 5 的倍數,您還需要在循環結束時添加額外的行尾 print() 調用。

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

output:

1 4 9 16 25
36 49 64 81 100
121 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM