首页 > 解决方案 > 什么是使用 if 函数终止脚本的脚本内代码(当值不为真时)?

问题描述

当逻辑返回“真”结果时,我打算在“如果”逻辑之后立即结束脚本。这里是:

age=int(input("Enter your age: "))
if age<=18:
    print("You are not an adult. Please exit.")
    exit() **#here is where I need the code to terminate and exit.**
else:
    print("Your age is: ", age)
from datetime import date
print("This is the year ",date.today().year)
yr = date.today().year
yob=yr-age
print("You were born in the year: ",yob)

如果第一个“if”逻辑返回“true”,即如果年龄低于 18,脚本应该终止,那么终止序列的最合适的命令是什么。提前谢谢了。

标签: python-3.xjupyter-notebook

解决方案


结束脚本的方法有很多种。如果不在这里共享任何代码,很难说出您想要实现的目标。但总的来说你可以试试这个-

1-使用pass关键字

2-如果你使用循环,你可以使用break关键字

3-如果您使用的是函数,如果条件不成立,则不返回任何内容。

4-你也可以使用'try and except'块

5-您可以使用while循环


推荐阅读