Python 3.x Python if优先级和停止脚本

Python 3.x Python if优先级和停止脚本,python-3.x,Python 3.x,现在,如果我输入1或0,这将起作用,但如果我输入5,则会出现一个错误,即未定义下一个变量。出于某种原因,如果不满足条件,python不会停止,是否有手动命令停止,比如return、exit或类似的命令?这是否有效取决于ifs和ELSE从侧面推动了多少。我是这方面的新手,所以尽可能地描述一下。谢谢。我暗自怀疑你真正想要的是: leftmost=int(input('Enter leftmost digit: ',)) if leftmost not in [0, 1]: print("Yo

现在,如果我输入1或0,这将起作用,但如果我输入5,则会出现一个错误,即未定义下一个变量。出于某种原因,如果不满足条件,python不会停止,是否有手动命令停止,比如return、exit或类似的命令?这是否有效取决于ifs和ELSE从侧面推动了多少。我是这方面的新手,所以尽可能地描述一下。谢谢。

我暗自怀疑你真正想要的是:

leftmost=int(input('Enter leftmost digit: ',))
if leftmost not in [0, 1]:
    print("You've entered a wrong value of", leftmost)
else:
    next1=int(input('Enter the next digit: ',))
if next1 not in [0, 1]:
    print("You've entered a wrong value of", next1)
else:
    next2=int(input('Enter the next digit: ',))
if next2 not in [0, 1]:
    print("Youve entered the wrong value of", next2)
else:
    next3=int(input('Enter the next digit: ',))
if next3 not in [0, 1]:
    print("Youve entered the wrong value of", next3)
else:
    print('Values entered', leftmost, next1, next2, next3)

请注意重复次数的显著减少和错误处理的改进。

“出于某种原因,如果条件不满足,python不会停止”——为什么要停止?这是一个不相关检查的顺序列表。谢谢,我想我只是把所有内容移到了一边,你能为3.4 python初学者推荐一些文档吗?@Saristas,也许吧?谢谢,我部分理解这是什么,但这对我的老师来说可能太复杂了,应该是一个简单的脚本嗯,我们都是从零开始的,所以这对我来说太复杂了,但我问过我的老师关于while函数,他迷路了,因为我们还没走到这一步。还有,你应该寻求治疗,你这个愤怒的小家伙。@Saristas如果你的老师不理解,你可能需要一个新的!你说得对,jonrsharpe,他只是不使用python编写代码,所以他学到了一些东西,然后教我们,我希望他会变成一个真正懂python的人。
def enter_binary(prompt):
    while True:
        try:
            i = int(input(prompt))
        except ValueError:
            print("Please enter an integer.")
        else:
            if i not in (0, 1):
                print("You've entered the wrong value of {0}.".format(i))
            else:
                return i

digits = []
digits.append(enter_binary('Enter leftmost digit: '))
for _ in range(3):
    digits.append(enter_binary('Enter the next digit: '))

print('Values entered: {0}'.format(" ".join(map(str, digits))))