如何为我的代码添加循环,使其重复10次,然后提供最终分数?这是我到目前为止尝试过的代码:
import random
randomNumber1 = random.randint ( 1,250 )
randomNumber2 = random.randint ( 1,250 )
def askQuestion():
global randomNumber1
global randomNumber2
userAnswer = int( input( "What is " + str(randomNumber1) + " + " + \
str(randomNumber2) + " ?: ") )
return userAnswer
def checkAnswer (userAnswer):
global randomNumber1
global randomNumber2
correctAnswer = randomNumber1 + randomNumber2
print()
if userAnswer == correctAnswer:
print("Congratulations!")
else:
print( "It's wrong. The correct answer is", correctAnswer )
def main():
userAnswer = askQuestion()
checkAnswer(userAnswer)
main()
答案 0 :(得分:0)
该脚本询问由ask_questions函数
的参数指定的10个问题import random
def ask_questions(n):
for q in range(n):
n1 = random.randint(1, 250)
n2 = random.randint(1, 250)
user_answer = int(input('\nWhat is {} + {}? '.format(n1, n2)))
if user_answer == n1 + n2:
print("Congratulations!")
else:
print('It\'s wrong. The correct answer is {}'.format(n1 + n2))
def main():
ask_questions(10)
main()
答案 1 :(得分:0)
import operator, random
ops = {"+": lambda a, b: operator.add(a, b),
"-": lambda a, b: operator.sub(a, b),
"*": lambda a, b: operator.mul(a, b)}
def main():
score = 0
for q in range(10):
a, b = random.randint(1, 10), random.randint(1, 10)
op = random.choice(list(ops.keys()))
ans = ops[op](a, b)
print(a, op, b, "=", end = " ")
user_input = int(input())
if user_input == ans:
score += 1
print("Scored:", score)
main()
生成两个随机数以及运算符。程序循环10次然后输出最终得分。
<强>输出强>
7 - 6 = 1
9 + 4 = 13
9 + 8 = 17
1 - 1 = 0
9 + 7 = 16
5 + 7 = 12
7 * 8 = 56
8 - 8 = 0
4 + 3 = 7
9 + 6 = 15
Scored: 10