【问题标题】:If statements running at the same time how toif语句同时运行怎么办
【发布时间】:2022-01-04 20:58:51
【问题描述】:
if input("Raining? ") == "yes":
    print("Then you should take an umbrella")

if input("Raining? ") == "no":
    print("Then you should not take an umbrella ")

所以我希望这两个同时检查是或否,所以当我输入否时,打印的答案应该是“那么你不应该带伞”但问题是当我说不时它会问两次 示例:

Raining? no
Raining? no
Then you should not take an umbrella

有什么想法可以让我完成这项工作吗?

我只想问你下雨了吗?不,答案是那么你不应该带伞,不问你两次,第二次有效

【问题讨论】:

  • 只调用一次input(),将值存储在一个变量中,然后在两个if 语句中使用该变量。
  • 如上所述,您可以使用一个变量并检查其值,但如果您只期望 2 个不同的值,使用 else 语句也可以工作
  • 海象运算符的好案例:=

标签: python if-statement


【解决方案1】:

if 语句之前要求输入。

例如:

value = input("Raining? ")
if value == "yes":
    print("Then you should take an umbrella")
elif value == "no":
    print("Then you should not take an umbrella")

【讨论】:

  • 在py 3.8之前不需要存储,使用海象! if (value := input("Raining? ")) == "yes":
【解决方案2】:

只需保存输入以供稍后比较。

inp = input("Raining? ")
if inp == "yes":
    print("Then you should take an umbrella")
elif inp == "no":
    print("Then you should not take an umbrella ")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多