gpt4 book ai didi

python乘法测验无效的语法

转载 作者:行者123 更新时间:2023-12-03 08:00:49 24 4
gpt4 key购买 nike

我有这个 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乘法测验无效的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61825892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com