为什么这段代码一直运行 else? python3

huangapple go评论61阅读模式
英文:

Why does this code keep running else? python3

问题

check = input("检查 x 还是 y。")

while True:
    print("输入是", check)
    if check == "x":
        print("跟随 x")
        break
    elif check == "y":
        print("跟随 y")
        break
    else:
        print("跟随其他")
        break

print("结束")
英文:
check = input("check for x or y. ")

while True:
    print("input was" , check)
    if input == "x":
        print("Following x")
        break
    elif input == "y":
        print("Following y")
        break
    else:
        print("Following else")
        break

print("end")

I am trying to run the if statement depending on the input but regardless of input it always goes to else.

答案1

得分: 2

你正在比较input函数,而不是调用input函数并从键盘读取输入的结果(check)。

check = input("检查x还是y。")

while True:
    print("输入是", check)
    if check == "x":
        print("跟随x")
        break
    elif check == "y":
        print("跟随y")
        break
    else:
        print("跟随其他")
        break

print("结束")
英文:

You are comparing the input function, not the result (check) of calling the input function and reading the input from the keyboard

check = input("check for x or y. ")

while True:
    print("input was" , check)
    if check == "x":
        print("Following x")
        break
    elif check == "y":
        print("Following y")
        break
    else:
        print("Following else")
        break

print("end")

huangapple
  • 本文由 发表于 2023年7月10日 17:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定