簡體   English   中英

Python:從while循環中反轉打印順序

[英]Python: Reversing print order from a while loop

我正在寫一些代碼,將值,值numberN作為輸入並打印,輸出乘法表的前N行,如下所示:

3 * 4 = 12
2 * 4 = 8
1 * 4 = 4    

我想做的是反向說輸出看起來像這樣:

1 * 4 = 4
2 * 4 = 8
3 * 4 = 12

代碼在下面。 我已經考慮過使用[:-1]這樣的切片,但是我不確定如何實現它。 協助將不勝感激。 謝謝。

number = input("Enter the number for 'number ': ")
N = input("Enter the number for 'N': ")

if number .isdigit() and N.isdigit():
    number = int(number )
    N = int(N)
    while int(N) > 0:
        print('{} * {} = {}'.format(N,number ,N*number))
        N = N - 1
else: 
    print ('Invalid input')

相反,我建議使用帶有range方法的for循環,例如:

for i in range(1, N+1):
    print('{} * {} = {}'.format(i,number ,i*number)

您可以這樣更改while循環:

int i = 0
while i < N:
    print('{} * {} = {}'.format(i,number ,i*number))
    i = i + 1

反轉列表是[::-1](您錯過了':'),並且您解析了兩次相同的數字N,但是在這種情況下,您可以

counter = 0
while counter != N:
    print('{} * {} = {}'.format(N,number ,N*number))
    counter = counter + 1

我認為,您可以讓程序向上計數。

N = int(N)
i = 1
while int(N) >= i:
    print('{} * {} = {}'.format(N,number ,N*number)) # TODO: adjust formula
    i = i + 1

如果您絕對必須使用while循環來執行此操作,則可能會執行以下操作。

m = 1
while m <= N:
    #Do stuff with m
    m += 1

雖然我非常建議使用for循環代替。

暫無
暫無

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

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