2017-08-17 79 views
0

我寫一些代碼取值,值numberN作爲輸入和打印,第一N線乘法表如下:的Python:從while循環反向打印順序

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

我'd想要做的是反向輸出如下所示:

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') 
+0

你可以爲範圍(N):' –

+1

@Professor_Joykill應該爲'範圍內的我(1,N + 1)' – bendl

+0

@allouticey這個輸出:[40,36,32 ,28,24,20,16,12,8,4]是否可以?如果是的話,我給你發新的解決方案 –

回答

0

我想,你可以讓程序向上計數。

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

是的,這工作。 – allouticey

0

你可以改變你while循環像這樣:

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

(i = i -1)?你測量(我=我+ 1)? –

+0

我做了,修好了,謝謝 –

2

我反而建議使用與該range方法,這樣的循環:

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

應該是'range(1,N + 1)' – bendl

+0

對不起,我的壞,謝謝 –

+0

我會用for循環,但是我用while循環做了這個特定的一段代碼。 – allouticey

0

沖銷列表[ :: - 1](你錯過了':'),你解析兩次相同的數字N,但在這種情況下,你可以做

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

如果你絕對必須使用while循環來做,可能像下面這樣的工作。

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

儘管我非常建議使用for循環代替。