根据用户输入创建 if/else 语句

问题描述 投票:0回答:2

我正在尝试创建一个简单的脚本,该脚本将提出一个问题,用户将输入答案(或者可能会出现带有可选答案的提示?),并且程序将根据输入输出响应。

例如,如果我说

prompt1=input('Can I make this stupid thing work?')

我想要一些类似于

的东西
if prompt1='yes': 
    print('Hooray, I can!')

else prompt1='No':
    print('Well I did anyway!')

elif prompt1=#an answer that wouldn't be yes or no
    #repeat prompt1

我可能以错误的方式处理这个问题。请尽可能描述性,因为这对我来说是一个学习练习。预先感谢!

python if-statement input
2个回答
2
投票

你们已经很接近了。阅读一个很好的教程:)

#!python3
while True:
    prompt1=input('Can I make this stupid thing work?').lower()

    if prompt1 == 'yes':
       print('Hooray, I can!')
    elif prompt1 == 'no':
       print('Well I did anyway!')
    else:
       print('Huh?') #an answer that wouldn't be yes or no
  • while True
    将永远循环程序。
  • 使用
    ==
    测试是否相等。
  • 使用
    .lower()
    可以更轻松地测试答案,无论大小写。
  • if/elif/elif/.../else
    是正确的测试顺序。

这是 Python 2 版本:

#!python2
while True:
    prompt1=raw_input('Can I make this stupid thing work?').lower()

    if prompt1 == 'yes':
       print 'Hooray, I can!'
    elif prompt1 == 'no':
       print 'Well I did anyway!'
    else:
       print 'Huh?' #an answer that wouldn't be yes or no
    使用
  • raw_input
    代替
    input
    。 Python 2 中的
    input
    将尝试将输入解释为 Python 代码。
  • print
    是一个语句而不是一个函数。不要将
    ()
    与它一起使用。

1
投票

另一个例子,这次是一个函数。

def prompt1():
    answer = raw_input("Can I make this stupid thing work?").lower()
    if answer == 'yes' or answer == 'y':
        print "Hooray, I can!"
    elif answer == 'no' or answer == 'n':
        print "Well I did anyway!"
    else:
        print "You didn't pick yes or no, try again."
        prompt1()

prompt1()
© www.soinside.com 2019 - 2024. All rights reserved.