Python:在代码前面验证
Python: Validating earlier in the code
这是我的代码,是 children 的测验。我需要帮助的是,在代码向用户询问其 class 之后,它应该立即验证输入是否有效,而不是在最后执行并显示消息
"Sorry, we can not save your data as the class you entered is not valid."
我尝试将整个 if、elif 和 else 语句移动到紧跟其后:
users_class = int(input("Which class are you in? (1,2 or 3)"))
但这无济于事。任何帮助将不胜感激:)
import time
import random
import math
import operator as op
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
users_class = int(input("Which class are you in? (1,2 or 3)"))
input("Press Enter to Start...")
start = time.time()
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
if users_class == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
您只需在 class 用户所在的问题之后添加一个额外的条件。通常我们会在此处设置一个循环,以便在用户输入无效响应时再次询问用户。
print ("Hi {}! Welcome to the Arithmetic quiz...".format(username))
while True:
users_class = int(input("Which class are you in? (1,2 or 3)"))
if users_class in [1, 2, 3]:
break
print('Please make sure you enter a class from 1 to 3')
您应该在 input
之后立即检查输入是否有效,如下所示:
import sys
users_class = int(input("Which class are you in? (1,2 or 3)"))
if users_class not in {1,2,3}:
print("Sorry, you must enter either a 1, 2, or 3!")
sys.exit(1)
请注意,sys.exit(1)
调用将退出程序。
现在,这不是最可靠的做事方式。如果用户输入的不是数字,例如 int(...)
将引发异常,因为它无法将 "dog" 转换为整数。此外,您可能希望程序继续要求有效输入,而不是停止并退出。这里有一些代码可以做到这一点:
while True:
try:
# try to convert the user's input to an integer
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
# oh no!, the user didn't give us something that could be converted
# to an int!
print("Please enter a number!")
else:
# Ok, we have an integer... is it 1, 2, or 3?
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
# the input was 1,2, or 3! break out of the infinite while...
break
print(users_class)
你问完之后需要直接检查这个值是1、2还是3,所以你可以把if直接移到users_class = int(input("Which class are you in? (1,2 or 3)"))
之后。
将correct_answers=0
移到if上面,然后将timeTaken
设置为0
。
这个有效:
import time
import random
import math
import operator as op
import sys
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
users_class = int(input("Which class are you in? (1,2 or 3)"))
correct_answers = 0
timeTaken = 0
if users_class == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
sys.exit(0);
input("Press Enter to Start...")
start = time.time()
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
如果无效,则通过 sys
退出,否则按照您当前的代码继续。
这是我的代码,是 children 的测验。我需要帮助的是,在代码向用户询问其 class 之后,它应该立即验证输入是否有效,而不是在最后执行并显示消息 "Sorry, we can not save your data as the class you entered is not valid." 我尝试将整个 if、elif 和 else 语句移动到紧跟其后:
users_class = int(input("Which class are you in? (1,2 or 3)"))
但这无济于事。任何帮助将不胜感激:)
import time
import random
import math
import operator as op
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
users_class = int(input("Which class are you in? (1,2 or 3)"))
input("Press Enter to Start...")
start = time.time()
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
if users_class == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
您只需在 class 用户所在的问题之后添加一个额外的条件。通常我们会在此处设置一个循环,以便在用户输入无效响应时再次询问用户。
print ("Hi {}! Welcome to the Arithmetic quiz...".format(username))
while True:
users_class = int(input("Which class are you in? (1,2 or 3)"))
if users_class in [1, 2, 3]:
break
print('Please make sure you enter a class from 1 to 3')
您应该在 input
之后立即检查输入是否有效,如下所示:
import sys
users_class = int(input("Which class are you in? (1,2 or 3)"))
if users_class not in {1,2,3}:
print("Sorry, you must enter either a 1, 2, or 3!")
sys.exit(1)
请注意,sys.exit(1)
调用将退出程序。
现在,这不是最可靠的做事方式。如果用户输入的不是数字,例如 int(...)
将引发异常,因为它无法将 "dog" 转换为整数。此外,您可能希望程序继续要求有效输入,而不是停止并退出。这里有一些代码可以做到这一点:
while True:
try:
# try to convert the user's input to an integer
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
# oh no!, the user didn't give us something that could be converted
# to an int!
print("Please enter a number!")
else:
# Ok, we have an integer... is it 1, 2, or 3?
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
# the input was 1,2, or 3! break out of the infinite while...
break
print(users_class)
你问完之后需要直接检查这个值是1、2还是3,所以你可以把if直接移到users_class = int(input("Which class are you in? (1,2 or 3)"))
之后。
将correct_answers=0
移到if上面,然后将timeTaken
设置为0
。
这个有效:
import time
import random
import math
import operator as op
import sys
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
users_class = int(input("Which class are you in? (1,2 or 3)"))
correct_answers = 0
timeTaken = 0
if users_class == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
elif users_class == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correct_answers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
sys.exit(0);
input("Press Enter to Start...")
start = time.time()
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
如果无效,则通过 sys
退出,否则按照您当前的代码继续。