【问题标题】:Python While loop not ending when variable changes [closed]变量更改时Python While循环未结束[关闭]
【发布时间】:2016-04-10 14:28:27
【问题描述】:

当 var[5] 从 "" 变为 "left" 或 "right" 时,while 循环不会停止

#Variable Input
name = input("Enter your name: ")
place = input("Enter where you live: ")
sex = input("Are you a boy (Y/N): ")
scaryanimal = input("Enter the type of animal that you are most scared of: ")
happyanimal = input("Enter your favourite type of animal: ")
var=[name,place,sex,scaryanimal,happyanimal,""]

#Main story

#Other code goes here

#Offending While loop

while var[5].lower() != "left" or var[5].lower() != "right": 
        var[5] = input("Did he go left or right: ")
        print(var[5])

【问题讨论】:

  • 我看不出你在哪里改变var[5]。如果你认为vari = input(...) 改变了var 的内容,你可能误解了列表赋值的语法。
  • 糟糕,刚刚意识到我忘记用 var[5] 替换 vari,我将 var[5] 更改为一个变量,以检查它是否是错误的数组。 :-(
  • 您的原始代码是否“正确”使用 var[5] 而不是 vari

标签: python loops python-3.x while-loop


【解决方案1】:

我读到你说你的变量正在改变,但是在哪里?

两件事:你必须改变你正在检查的变量并且你必须改变那个条件测试,当变量var[5]不同于'left'或不同时,while循环条件是True 'right'(如果它是“left”,那么它与“right”不同,因此循环将继续)

所以...

while var[5].lower() != "left" and var[5].lower() != "right": 
    var[5] = input("Did he go left or right: ")
    print(var[5])

【讨论】:

    猜你喜欢
    • 2016-01-12
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 2016-06-14
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多