[英]How to use try/except in a Python quiz problem
我正在尝试在此代码中输入 try/except 以供输入字母而非数字的人使用
我的代码:
def quiz():
while True:
score = 0
for questions in Quiz_qs:
print("\n" + i[0])
if guess == i[1]:
print("Correct!")
score += 1
print(score, "out of 10”)
else:
print("\nincorrect!")
print(score, "out of 10”)
break
Quiz()
我也是初学者,但也许我可以帮助你,也可以学到一些东西。 我认为问题在于您并没有要求在尝试中获得 int 答案。 使用“if”语句,您只考虑正确答案,因此“else”包括不是正确答案的所有其他答案,也包括字符答案。 您应该设置另一个条件来检查答案是否为数字,除非不是,否则请致电。
希望我有所帮助。
更改您的代码如下:
G_statements = [["What is 5+5?", "10"]]
G_statements.append(["What is the square root of 9?", "3"])
G_statements.append(["What is 30 / 3", "10"])
G_statements.append(["What is 24 x 2", "48"])
G_statements.append(["What is 40 / 5", "8"])
G_statements.append(["What is 150 - 45", "105"])
G_statements.append(["What is 9x9", "81"])
G_statements.append(["What is 25+5", "30"])
def Generalquiz():
score = 0
for i in G_statements:
print("\n" + i[0])
while True:
try:
guess = int(input("\nAnswer:"))
break
except ValueError:
print("Characters not accepted, Please enter a number")
if guess == int(i[1]):
print("Correct!")
score = score + 1
print(score, "out of 8")
print("\n")
else:
print("\nincorrect!")
print(score, "out of 8")
print("\n")
Generalquiz()
G_statements = [["What is 5+5?", "10"],
["What is the square root of 9?", "3"],
["What is 30 / 3", "10"],
["What is 24 x 2", "48"],
["What is 40 / 5", "8"],
["What is 150 - 45", "105"],
["What is 9x9", "81"],
["What is 25+5", "30"]]
# python lists support multi type variables as such ["What is 25+5", 30]
# if you declare the list this way, you can simply do 'if guess == i[1]'
def Generalquiz():
score = 0
# ask a question
for i in G_statements:
print("\n" + i[0])
# try to get a valid (not necessarily correct) answer
while True: # keep asking for a valid input
try: # TRY receiving a valid input
guess = int(input("\nAnswer:")) # try to CAST input to INT, if successful, the input was int, otherwise raise a ValueError
break
except ValueError:
print("Characters not accepted, Please enter a number")
continue # as long as we have an error (that is the input wasn't an int) CONTINUE asking for a valid input
# logic part
if guess == int(i[1]): # correct answer is a string (not the best way, see above comment), convert it to int
score+=1
print("Correct!", score, "out of ", len(G_statements)) # LENgth of G_statements, avoid constant values if possible
else: print("\n\nincorrect!", score, "out of 8\n")
注释应该足以解释,如果您刚开始编码,请尝试将问题分解为更小的块并分别解决它们,祝您好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.