【问题标题】:Logic checking statements [duplicate]逻辑检查语句 [重复]
【发布时间】:2021-01-11 17:05:33
【问题描述】:

我需要在下面的代码中添加 2 个逻辑语句。如果您未满 18 岁,我需要一个,而另一个只能让您输入 2 个字母的州。这两个语句都需要退出程序,我认为这是我感到困惑的地方。我对python很陌生,所以非常感谢任何帮助。我想我可以放 if 语句但我不知道如何让它们退出程序,我只知道如何让它们打印

print('Welcome to the US Voter Registration System')
con = input('Do You Want to Continue: Yes Or No? ')
while con == 'Yes':
    name = input('Please Enter Your First Name: ')
    name2 = input('Please Enter Your Last Name: ')

    age = int(input('Please Enter Your Age *** YOU MUST BE 18 OR OLDER ***: '))

    cit = input('Are You A US Citizen? Answer Yes or No: ')

    state = input('Please Enter Your State?' 'Please only 2 letters: ')

    zipc = int(input('Please Enter Your Zip Code? '))

    con = input('You Are Finished Please Type Done: ')

    print('NAME: ', name, name2)
    print('AGE: ', age)
    print('US CITIZEN:', cit)
    print('STATE: ', state)
    print('ZIP CODE: ', zipc)
    print('Thank You For Using the US Voter Registration System ')
    print('Please Check Your Mail For More Voting Information ')

【问题讨论】:

标签: python


【解决方案1】:

您可以使用sys.exit() 退出程序(请记住文件顶部的import sys)。

您可以使用if age < 18:(“如果年龄小于 18 岁”)检查年龄是否低于 18 岁。对于状态值的长度,您可以使用len 函数,它为您提供以字符为单位的字符串长度(从技术上讲,它为您提供序列的长度或实现__len__ 方法的任何内容,但这对于您的内容并不重要'正在尝试做)。

您也可以使用break 来结束while 循环而不是退出程序。

所以要实施这些措施:

import sys

print('Welcome to the US Voter Registration System')

...

    age = int(input('Please Enter Your Age *** YOU MUST BE 18 OR OLDER ***: '))

    if age < 18:
        print("Must be over 18!")
        sys.exit()  # or break to end the loop

    ..

    state = input('Please Enter Your State?' 'Please only 2 letters: ')
   
    if len(state) != 2:
        print("State must be exactly two letters.")
        sys.exit()  # or break to end the loop

    ..

【讨论】:

  • 非常感谢。这是有道理的……很有道理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多