我有这个python乘法测验。
import random
score = 0
continue = True
while continue:
a = random.randint(1, 12)
b = random.randint(1, 12)
product = a * b
guess = int(input('What is '+str(a)+' times '+str(b)+'? (press "q" to quit):'))
if guess == 'q':
continue = False
if guess != product:
print('Sorry, this is wrong. It should be '+str(product)+'.')
continue = False
if guess == product:
print('Good job. You got it right.')
print('Thanks for playing! You scored '+str(score)+'.')
当我尝试在
SyntaxError: invalid syntax
行运行它时,它总是说continue = True
。在添加
continue
查询之前,它运行良好:import random
score = 0
while True:
a = random.randint(1, 12)
b = random.randint(1, 12)
product = a * b
guess = int(input('What is '+str(a)+' times '+str(b)+'? (press "q" to quit):'))
if guess == 'q':
break
if guess != product:
print('Sorry, this is wrong. It should be '+str(product)+'.')
if guess == product:
print('Good job. You got it right.')
print('Thanks for playing! You scored '+str(score)+'.')
我不确定
continue = True
行有什么问题。据我所知,这是将True
分配给变量continue
。请帮忙! 最佳答案
continue
是python关键字,例如if
,else
,True
,break
等,因此您无法为其分配值。如果要使用此名称,请尝试continue_
(来自pep8)。
同样,使用continue_
修复程序输入'q'
也会导致异常,因为python尝试执行int('q')
,但这是行不通的。
您没有在函数中增加分数,因此如果正确添加score += 1
会有所帮助。
import random
score = 0
continue_ = True
while continue_:
a = random.randint(1, 12)
b = random.randint(1, 12)
product = a * b
guess = input('What is '+str(a)+' times '+str(b)+'? (press "q" to quit):')
if guess == 'q':
break
if int(guess) != product:
print('Sorry, this is wrong. It should be '+str(product)+'.')
continue_ = False
if int(guess) == product:
print('Good job. You got it right.')
score += 1
print('Thanks for playing! You scored '+str(score)+'.')
例如将输出
What is 6 times 7? (press "q" to quit):42
Good job. You got it right.
What is 10 times 7? (press "q" to quit):70
Good job. You got it right.
What is 8 times 7? (press "q" to quit):56
Good job. You got it right.
What is 9 times 10? (press "q" to quit):90
Good job. You got it right.
What is 2 times 12? (press "q" to quit):24
Good job. You got it right.
What is 12 times 3? (press "q" to quit):36
Good job. You got it right.
What is 11 times 6? (press "q" to quit):66
Good job. You got it right.
What is 11 times 7? (press "q" to quit):q
Thanks for playing! You scored 8.
关于python - python乘法测验无效语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61825892/