我正在尝试学习 while 语句在 Python 中的工作原理。我正在尝试创建一个代码,该代码继续将 num1 和 num2 相乘,直到舍入 <= 10 或直到 num1 > num2。如果 10 轮前 num1 大于 num2,则循环结束,num1 获胜,否则获胜者为 num2。
我的输出只完整打印第一轮,然后一遍又一遍地打印 'Round = #'。 我希望输出看起来像这样:
Initiate Math Competition:
Round = 1
1 = #
1 = #
2 = #
2 = #
2 = #
Round = 2
1 = #
1 = #
2 = #
2 = #
2 = #
...
Math Competition Closed
Winner = 1
注意:我无法更改主程序。另外,我理解这段代码的一个问题是,在继续阻止代码检查 num1 是否超过 num2 之前,内部循环已经完成,但我不知道如何修复它。
def math_competition(num1, multiply1, max_repitition_1, num2, multiply2, max_repitition_2):
"""
-------------------------------------------------------
Returns Winner of Math Competition.
Use: winner = math_competition(num1, multiply1, max_repitition_1, num2, multiply2, max_repitition_2)
-------------------------------------------------------
Parameters:
num1: first value (int)
multiply1: first multiplying factor (int)
max_repitition_1: max repetition for the first value (int)
num2: second value (int)
multiply2: second multiplying factor (int)
max_repitition_2: second repetition factor (int)
Returns:
winner - Winner of Math Competition
-------------------------------------------------------
"""
print('Initiate Math Competition:')
rounds = 1
first_counter = 0
second_counter = 0
winner = ''
while rounds <= 10 and num1 < num2:
print('Round = {}'.format(rounds))
while first_counter != max_repitition_1:
num1 = num1 * multiply1
print('1 = {}'.format(num1))
first_counter += 1
while second_counter != max_repitition_2:
num2 = num2 * multiply2
print('2 = {}'.format(num2))
second_counter += 1
if num1 > num2:
winner = '1'
break
elif rounds <= 10 and num2 > num1:
rounds += 1
continue
else:
winner = '2'
print('Math Competition Closed')
return winner
#-------------------------MAIN PROGRAM---------------------------#
cases = [[20, -8, 4, 30, 2, 3], [15, 2, 2, 18, 5, 3], [12, 4, 2, 3400, 1, 5]]
for c in cases:
winner = math_competition(c[0],c[1],c[2],c[3],c[4],c[5])
print('Winner is: {}'.format(winner))