(初学者Python)依赖用户输入创建if/else语句?

问题描述:

我正在尝试创建一个简单的脚本,它会询问用户将输入答案的问题(或者出现可选答案的提示?),程序会根据输入输出响应。(初学者Python)依赖用户输入创建if/else语句?

例如,如果我说

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 

行的东西。请尽可能描述性,因为这是我的学习练习。提前致谢!

+0

使用'=='比较相等性,并使用'else'语句。 – Christian 2014-11-02 03:14:06

你很近。读一个很好的教程:)

#!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是一个声明,而不是一个函数。不要使用()
+0

我复制/粘贴到我的PyCharm中,当我尝试输入答案时出现此错误。 (是或否) – 2014-11-02 03:25:47

+0

回溯(最近呼叫最后一次): 文件“C:/ Users/Shawn/PycharmProjects/helloworld/Test Prograsm.py”,第3行,在 prompt1 = input('我可以让这个愚蠢的')。lower() 文件“”,第1行,在 NameError:名称'yes'未定义 – 2014-11-02 03:27:16

+1

您必须改为使用Python 2.x。 'print()'是Python 3中的一个函数,所以我认为你正在使用Python 3.在Python 2中使用'raw_input'。更新你的问题标签以表明你的Python版本。 – 2014-11-02 03:29:17

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

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