if / elif / else语句

时间:2020-06-27 01:44:46

标签: python

我的程序/项目是关于询问用户他的身高是否足以坐过山车,并提供对“是”或“否”答案的说明。我的问题是,如果用户输入的不是“是”或“否”,我想说“请输入是或否”。在尝试插入该语句之前,我的代码一直有效。如何插入该语句而不会出现错误。

rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
    print('Please exit the ride!')
elif rc1 == 'yes':
    rc2 = int(input('How tall are you? '))
if rc2 <= 119:
    print('You are not tall enough for this ride!')
else:
    print('Enter and enjoy the ride!')

4 个答案:

答案 0 :(得分:1)

几件事。就像上面一样,while循环是一种持续提示用户的好方法,直到您以所需的格式获得输入,并且rc2变量在if语句中定义并且不可用于比较,因此需要更早地对其进行定义,因此它可供您的第二个条件使用。像这样:

rc1 = input('Are you tall enough to ride this roller coaster? ')
rc2 = 0
while str.lower(rc1) not in ('yes', 'no'):
    print('Please answer yes or no')
    rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
    print('Please exit the ride!')
elif rc1 == 'yes':
    rc2 = int(input('How tall are you? '))
if rc2 <= 119:
    print('You are not tall enough for this ride!')
else:
    print('Enter and enjoy the ride!')

答案 1 :(得分:0)

我添加了一个while循环,看起来类似于以下内容:

answer = None
rc2 = None
while answer not in ("yes", "no"):
    answer = input('Are you tall enough to ride this roller coaster? ')
    if answer == "yes":
        rc2 = int(input('How tall are you? '))
    elif answer == "no":
        print('Please exit the ride!')
    else:
        print("Please enter yes or no.")
    
if rc2 <= 119:
    print('You are not tall enough for this ride!')
else:
    print('Enter and enjoy the ride!')

答案 2 :(得分:0)

这是我的解决方案:

rc1 = input('Are you tall enough to ride this roller coaster? ')
rc2 = None
if rc1 == 'no':
    print('Please exit the ride!')
elif rc1 == 'yes':
    rc2 = int(input('How tall are you? '))
if rc2 != None:
    if rc2 <= 119:
        print('You are not tall enough for this ride!')
    else:
        print('Enter and enjoy the ride!')

OR

rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
    print('Please exit the ride!')
elif rc1 == 'yes':
    rc2 = int(input('How tall are you? '))
    if rc2 <= 119:
        print('You are not tall enough for this ride!')
    else:
        print('Enter and enjoy the ride!')

您必须在开始时初始化rc2变量。出现错误的原因是因为程序甚至不知道变量是什么时,正在检查rc2是否小于或等于119。 rc2仅在rc1等于yes时存在。为了以后使用它,rc2必须存在,无论条件如何。

答案 3 :(得分:0)

我还得到了一种更快速的解决方案,其工作量超出了我的预期。谢谢您的帮助

rc1 = input('Are you tall enough to ride this roller coaster? ')
while rc1 not in ('yes', 'no'):
    print('Please enter yes or no.' )
    rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
    print('Please exit the ride!')
elif rc1 == 'yes':
    rc2 = int(input('How tall are you? '))
    if rc2 <= 119:
        print('You are not tall enough for this ride!')
    else:
        print('Enter and enjoy the ride!')