我的程序正在运行我喜欢它,但我似乎无法弄清楚如何为用户测试分数输入添加验证。输入需要从0到100并验证每个输入的分数。
我如何修改我的代码,以便在prompt_scores函数中将输入的验证循环设置为> = 0和< = 100? 我之前尝试过一个while循环,但放在每个输入上时都被忽略了。
def calc_average(scoreOne, scoreTwo, scoreThree):
average = (scoreOne + scoreTwo + scoreThree)/3
return average
def determine_grade(studentScore):
if studentScore < 60:
return "F"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def prompt_scores():
enteredScoreOne = int(input("Please enter score 1: "))
enteredScoreTwo = int(input("Please enter score 2: "))
enteredScoreThree = int(input("Please enter score 3: "))
return enteredScoreOne, enteredScoreTwo, enteredScoreThree
def print_results(scoreOne, scoreTwo, scoreThree):
print("\nScore\tLetter Grade" )
print(str(scoreOne) + "\t\t" + determine_grade(scoreOne), \
str(scoreTwo) + "\t\t" + determine_grade(scoreTwo), \
str(scoreThree) + "\t\t" + determine_grade(scoreThree), sep = "\n")
def main():
scoreOne, scoreTwo, scoreThree = prompt_scores()
print_results(scoreOne, scoreTwo, scoreThree)
print("-----------------------")
print("Average score: " + str(int(calc_average(scoreOne, scoreTwo,scoreThree))))
print(" Final grade: " + determine_grade(int(calc_average(scoreOne, scoreTwo, scoreThree))))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main == "Y" or rerun_main == "y":
main()
main()
答案 0 :(得分:2)
enteredScoreOne = int(input("Please enter score 1: "))
while enteredScoreOne not in range(0, 101):
print("[!] Invalid input!")
enteredScoreOne = int(input("Please enter score 1: "))
等等其他变量。
如果您正在运行Python 2(假设您正在使用input
来读取字符串,那么您不是,但我会添加它以防万一),您最好替换{{1使用in range(...)
作为(0 <= enteredScoreOne <= 100)
将返回一个列表,这将消耗一点额外的内存。
答案 1 :(得分:0)
如果您使用函数,您可以在获取输入时检查输入的值,并且可以强制用户使用递归输入介于0-100之间的值,我也可以看到您正在使用python本身具有内置的其他函数,例如: sum()
。也尝试尽可能地节省内存和处理现在它似乎不是一个大问题但是当你有1000行代码时,即使这些小东西也会省你。这里我的意思是不是两次调用函数,而是可以将结果保存在变量中并使用它。我在我的代码中添加了所有这些并给出了答案。
def get_input():
try:
score=int(input("please enter score : "))
if (score >=0 and score <100):
return score
else:
print("Score should be inbetween 0-100. Try again :-(:-(:-(")
get_input()
except:#if user enters any special char except float or int tell him to enter int
print("Only integer is accepted")
def determine_grade(avg):
if studentScore < 60:
return "E"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def print_results(*args):
for i,j in enumerate(args):
print("score "+str(i)+" = "+str(j)+" grade = "+determine_grade(j))
def main():
score1 = get_input()
score2 = get_input()
score3 = get_input()
print_results(score1, score2, score3)
print("-----------------------")
avg=sum([score1,score2,score3])/3
print("Average score: " + str(avg))
print(" Final grade: " + determine_grade(avg))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main.lower() == "y":
main()
main()