Skip to main content
 首页 » 编程设计

python之(初学者 Python)根据用户输入创建 if/else 语句

2024年10月25日12zhwl

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

例如,如果我要说

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 

我可能会以错误的方式解决这个问题。请尽可能描述,因为这对我来说是一个学习练习。提前致谢!

请您参考如下方法:

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

#!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 是语句而不是函数。不要将 () 与它一起使用。