這是一個非常愚蠢的問題,但我沒有在一段時間內使用過它,並且不記得如何去做。我正在做一個遞歸問題,並需要顯示數字倒數基本顯示遞歸如何工作。但是,我似乎無法弄清楚。這是我的代碼。Python while loop subtraction
def main():
#have user input first number
x = int(input('Enter the first number: '))
#have user input second number
y = int(input('Enter the second number: '))
#calculate result by calling recursive function
result = mult(x, y)
#print the result
print(x, 'times', y, 'is', result)
#define a function that uses recursion
def mult(x, y):
# create a loop to display the numbers
count = y
while count > 0:
print('First number =', x, 'Second number =', count)
count -= 1
#use recursion to multiply the numbers
if x == 0:
return 0
elif x == 1:
return y
else:
return y + mult(x - 1, y)
main()
我需要的輸出這樣說:
Enter the first number: 5
Enter the second number: 7
First number = 5 Second Number = 7
First number = 5 Second Number = 6
First number = 5 Second Number = 5
First number = 5 Second Number = 4
First number = 5 Second Number = 3
First number = 5 Second Number = 2
First number = 5 Second Number = 1
5 times 7 = 35
所以它的工作大部分,但現在它顯示的是這樣的:
Enter the first number: 5
Enter the second number: 7
First number = 5 Second number = 7
First number = 5 Second number = 6
First number = 5 Second number = 5
First number = 5 Second number = 4
First number = 5 Second number = 3
First number = 5 Second number = 2
First number = 5 Second number = 1
First number = 4 Second number = 7
First number = 4 Second number = 6
First number = 4 Second number = 5
First number = 4 Second number = 4
First number = 4 Second number = 3
First number = 4 Second number = 2
First number = 4 Second number = 1
First number = 3 Second number = 7
First number = 3 Second number = 6
First number = 3 Second number = 5
First number = 3 Second number = 4
First number = 3 Second number = 3
First number = 3 Second number = 2
First number = 3 Second number = 1
First number = 2 Second number = 7
First number = 2 Second number = 6
First number = 2 Second number = 5
First number = 2 Second number = 4
First number = 2 Second number = 3
First number = 2 Second number = 2
First number = 2 Second number = 1
First number = 1 Second number = 7
First number = 1 Second number = 6
First number = 1 Second number = 5
First number = 1 Second number = 4
First number = 1 Second number = 3
First number = 1 Second number = 2
First number = 1 Second number = 1
5 times 7 is 35
也請說明什麼輸出是*而不是*。 – mkrieger1
將'print'語句移到if語句上方'mult'函數內部。 – camden
我得到的輸出是這個第一個數字= 5第二個數字= 6的無限循環。它甚至沒有輸出第二個數字作爲第一個數字7並且不低於6 – Classicalclown