如果不满足if语句,如何停止代码运行

时间:2019-08-13 21:57:02

标签: python

我正在做一个学校项目,我要添加的是一行代码,如果年龄小于15岁或年龄大于100岁,该代码将阻止代码运行 我尝试中断,但会继续进行下一行。

while True:
    try:

        age = int(input("How old are you? "))
    except ValueError:
        print("Please enter a valid age!")

        continue
    if age < 15:
        print("sorry you are too young to enter the store!")
        break
    if age > 100:
        print("Please come back in the next life") 
        break
    else:
        break

    print("")
    print("Welcome to Jim's Computer Store", name)
    print("") while True:                                    
    try:
       cash = int(input("How much cash do you currently have? $"))
    except ValueError:
        print("Please enter a valid value! ")

        continue
    else:
        break

2 个答案:

答案 0 :(得分:0)

只需在exit()条件之后添加if就可以了。

一个例子是:

x = 5
if x < 2:
    print "It works"
else:
    exit()

或者没有else语句:

x = 5
if x < 2:
    print "It works"
exit()

答案 1 :(得分:0)

我建议您逐步进行。问题中的代码对于此目的而言太长。当第一步的行为如您所愿时,您可以执行另一步。

这是否如您所愿?

name = "John"
while True:
    try:
        age = int(input("How old are you? "))
    except ValueError:
        print("Please enter a valid age!")
        continue
    break
# Here, we can assume that 'age' is an integer
if age < 15:
    print("sorry you are too young to enter the store!")
    exit()
if age > 100:
    print("Please come back in the next life") 
    exit()
print("")
print("Welcome to Jim's Computer Store", name)
# When the code above will be validated, the next step will be easy

while循环是为了确保age是整数,当他中断循环时(如果age不是整数,则程序将执行continue指令然后返回循环的开头。