我想在这里做两件事。
如果输入不是此代码中的数字,我想打印"value entered is not a valid age"
:
age = float(input (' enter your age: '))
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
此外,如果完成此程序,我该如何重复?
答案 0 :(得分:1)
您可以使用isdigit
str
方法检查输入是否为有效数字。您可以多次将代码包装到函数中并根据需要调用它:
def func():
age = input (' enter your age: ')
if age.isdigit():
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
else:
print "value entered is not a valid age"
func()
答案 1 :(得分:0)
为了使这段代码在每次你应该添加一个循环时运行,比如while
循环,并在你想要结束这个循环时添加一个break
或添加一个条件例如运行10次,如果您想要检查输入是float
,您可以添加try
部分:
counter = 0
while counter < 10:
age = raw_input (' enter your age: ')
try :
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
counter -= 1
except ValueError:
print "value entered is not a valid age"
答案 2 :(得分:0)
按顺序安排您的案例也是一个好主意,以便更容易看到正在发生的事情(并确保您没有留下未处理的差距):
while True:
age = input("Enter your age (or just hit Enter to quit): ").strip()
if not age:
print("Goodbye!")
break # exit the while loop
try:
# convert to int
age = int(age)
except ValueError:
# not an int!
print("Value entered is not a valid age")
continue # start the while loop again
if age < 0:
print("Sorry, {} is not a valid age.".format(age))
elif age < 16:
print("You are too young to drive!")
elif age < 95:
print("You are good to drive!")
elif age <= 120:
print("Sorry, you can't risk driving!")
else:
print("What are you, a tree?")