【问题标题】:How do you make consecutive if statements?你如何制作连续的if语句?
【发布时间】:2016-02-13 13:56:03
【问题描述】:

我一直在学习用 python 编写代码,并且我想出了一个好主意来编写一个程序。依据如下:

if input() == 'unnamed variable':
   print('this')
if input() == 'another unnamed variable'
   print('this other response')

如果不先满足第一个 if 语句,我不能输入另一个未命名的变量

我希望我的程序根据输入打印一些不同的内容供用户阅读

如何使用连续的 if 语句?我试过 elif 和其他。我可以背靠背说出 80 个 if 语句吗?

任何帮助将不胜感激,在此先感谢

【问题讨论】:

  • 这取决于您到底想做什么,但您可以使用循环并将continue 语句放入条件句中。

标签: python-3.x console-application


【解决方案1】:

如果你想根据用户输入做不同的事情,那么首先,你应该只要求用户输入一次。所以你应该只调用一次input() 并将响应保存到一个变量中:

response = input()

然后,您可以使用if、elif 和else 来检查多个不同的条件并每次执行不同的操作:

if response == 'some input':
    print('User entered some input')
elif response == 'some other input':
    print('User entered some input')
elif response == 'some even more different input':
    print('User entered some even more different input')
else:
    print('User entered something I do not recognize')

因此,您只需询问用户一次并存储响应,然后将响应与多个不同的值进行比较:如果其中一个条件为真,则执行该部分并跳过剩余的条件检查。

【讨论】:

  • 谢谢,更聪明的写作方式,它符合我的目的。谢谢你的提示。我正在查找如何继续代码而不是在打印后结束
【解决方案2】:

您可以将嵌套的 if -elif-elif-else 替换为 'or'

if cond1 or cond2 or cond3

您可以将嵌套的 if-if-if 替换为 'and'

if cond1 and cond2 and cond3

它可以帮助您重新设计大型 if-else 链

【讨论】:

    【解决方案3】:

    您可以定义输入,然后检查是否相等。

    userInput = input(" > ")
    aNumber = 5
    if userInput == 'y' or userInput == 'yes':
        print("You said yes!")
    elif userInput == 'no':
        print("You said no.")
    elif userInput == 'maybe' and aNumber == 5:
        print("you said maybe, and aNumber is equal to 5!")
    else:
        print("I can't understand you.")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2016-07-30
      • 2023-03-21
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多