我正在尝试编写一个用户输入利率的简单代码块。该数字必须为0或更大,任何其他值将被拒绝,必须轮询用户,直到输入有效数字。如果该数字大于10%,则必须询问用户他/她是否真的期望利率高,如果用户回答是肯定的,则使用该号码,否则将要求用户输入价值再次,将进行上述检查。我无法理解嵌套循环方面的问题。非常感谢任何帮助!
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
except ValueErrror:
print("Entered value is not a number! ")
except KeyboardInterrupt:
print("Command Error!")
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
main()
答案 0 :(得分:1)
在try if inp > 10
中完成所有操作,询问用户是否满意并且如果他们是中断,elif用户输入在阈值内只是打破循环:
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
if interest_rate > 10:
confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
if confirm =="y":
break
elif 0 <= interest_rate < 10:
break
except ValueError:
print("Entered value is not a number! ")
return interest_rate
main()
答案 1 :(得分:0)
有三件事情跳出来:
1)ValueErrror
应为ValueError
2)您没有在最终测试中处理用户输入
3)您可能希望将< 10
更改为<= 10
答案 2 :(得分:0)
使print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
成为输入
answer = int(input("Are you sure?"))
if answer == "y":
break
答案 3 :(得分:0)
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
可以是:
if 0 <= interest_rate <= 10:
break
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
除了最后一行必须接受响应并处理它。
您的else
与if
在elif
break
是不必要的
答案 4 :(得分:0)
我通常更喜欢将解决方案和验证分解为不同的模块。请检查以下代码,看看我如何分解它们。因此,在调试和测试方面很容易。
def validating_user_input(num):
"""
"""
return num > 0
def getting_user_input():
"""
"""
user_input = int(raw_input("Enter the number that is greater than 0: "))
return user_input
def confirming_choose():
"""
"""
try:
user_choose = int(raw_input("Can you confirm your input? [0|1]? "))
except ValueError:
return False
return user_choose == 1
def main():
"""
"""
initial_cond = True
while initial_cond:
user_input = getting_user_input()
if validating_user_input(user_input):
if user_input > 10:
confirmation = confirming_choose()
while not confirmation:
getting_user_input()
#do you operating here
initial_cond = False
else:
print "It is not valid input."
if __name__ == "__main__":
main()