【问题标题】:Is there a way to stop a program from running if an input is incorrect? Python如果输入不正确,有没有办法阻止程序运行? Python
【发布时间】:2021-01-10 12:52:53
【问题描述】:

我一直在尝试编写这段代码,如果某个输入不正确,我需要一种停止代码的方法,这是我目前所拥有的:

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!')

【问题讨论】:

标签: python


【解决方案1】:

导入 sys 对象并使用 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

【讨论】:

    【解决方案2】:

    首先导入这些:-

    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()
    

    【讨论】:

    • 为什么需要as exiter
    • @ppwater 因为如果我直接执行 from sys import exit 那么它会与内置的 exit() 发生冲突。所以我将它作为退出器导入。您可以使用您选择的名称。
    • 啊。好的。我认为你可以做import syssys.exit()。使用from 导入并不好恕我直言..
    • @ppwater 是的,我知道。但是,当您只需要sys.exit 时,为什么还要导入整个sys。使用from 导入不会导致任何问题。这是完全正常的
    • 我从未见过这样的做法。 sys 通常被导入为 import sys。你经常需要sys.pathsys.argv等。
    猜你喜欢
    • 2019-10-20
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多