[英]Is there a way to stop a program from running if an input is incorrect? Python
我一直在尝试编写这段代码,如果某个输入不正确,我需要一种停止代码的方法,这是我目前所拥有的:
first_name = input('PLEASE ENTER YOUR FIRST NAME: ')
last_name = input('PLEASE ENTER YOUR SURNAME: ')
print(f'Hello {first_name} {last_name}, before you enter.')
def age_det():
age = input(f'How old are you?')
converted_age = [int(age)]
for num in converted_age:
while num>=18:
print(f'Awesome, {first_name}, welcome to Blablabla')
num += 100
while num <= 18:
break
print(f'Sorry, {first_name}, but we require you to be at least 18 to enter Blablabla.')
num += 100
age_det()
#I want the code to stop here if the age entered is under 18
username = input('Before we start, please pick a username: ')
print(f'Woah! {username}, good choice!')
导入 sys object 并使用 if 语句检查年龄是否有效。 如果不调用sys.exit()
。
import sys
age = 17
if age < 18:
sys.exit()
print("Still going") # Doesn't get printed
如果年龄至少为 18 岁:
import sys
age = 25
if age < 18:
sys.exit()
print("Still going") # Gets printed
首先导入这些:-
import sys
然后在“对不起,我们不允许 18 岁以下”行之后添加这个
input('Press Enter to Continue...')
sys.exit()
加上使用if
而不是while
您的代码可以简化为:-
import sys
first_name=input('PLEASE ENTER YOUR FIRST NAME: ')
last_name=input('PLEASE ENTER YOUR SURNAME: ')
print(f'Hello {first_name} {last_name}, before you enter.')
def age_det():
age = int(input(f'How old are you?'))
if num>=18:
print(f'Awesome, {first_name}, welcome to Blablabla')
else :
print(f'Sorry, {first_name}, but we require you to be at least 18 to enter Blablabla.')
input('Press Enter to Continue...')
sys.exit()
age_det()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.