pandas 永无休止的循环

sxissh06  于 2023-02-06  发布在  其他
关注(0)|答案(5)|浏览(111)

循环应该在我输入YES或NO后结束,但它一直询问“AREYouDONEYES/NO”输入以下代码有什么问题

def Cable_df():
    YES = 'YES'
    NO = 'NO'
    v = ''
    while v != YES:
        x = input('Enter STARTING splice of cable').upper()
        y = input('Enter TERMINAL splice of cable ').upper()
        Z = input('Enter cable SIZE ').upper()
        v = input('ARE YOU DONE YES/NO ')
        while v != YES or v != NO:
            print('Must answer YES/NO')
            v = input('ARE YOU DONE YES/NO ')
4nkexdtk

4nkexdtk1#

您面临的问题是在条件中使用的逻辑:

while v != YES or v != NO:
  • 如果v==“是”,则v != YES的计算结果为... ...假,但是
  • 如果v==“是”,则v != NO计算为... ...
    *使False or True的值为True,并且循环无限运行。正确的输入不会停止循环,因为“NO”也会使'NO' != YES的值为True。

换句话说,您需要将while循环中的条件更改为另一个条件,该条件的计算结果为False,以便用户输入正确。
由于接受用户输入“是”和“否”,此类条件将为:

while not( (v == YES) or (v == NO) ):

上面的while条件等价于使用Python关键字in的条件,它检查一个值是否出现在列表中:

while v not in [YES, NO]:

上述指定条件的方法使代码看起来像英语,通常不需要解释它做了什么,因为它将循环 “,而v不等于包含YES和NO的列表中的值*”。如果这是一个优势,取决于程序员的英语说得有多好,以及使用这种方法编写和记录循环中断条件是否听起来有吸引力。
另一种说法是:

while v != YES and v != NO:

因为not ( A or B ) == not A and not B
理解布尔逻辑的一个常见问题是单词 orand 在口语中的使用方式。例如,如果你被问到:“Do you want A or do you want B?”,你认为你只能选择其中一个,如果你两个都选,布尔逻辑or也可以。

vxbzzdmp

vxbzzdmp2#

在你的第二圈

while v != YES or v != NO:

你在检查v != YES还是v != NO,任何一个条件都足以满足检查,并保持循环继续,所以它会一直继续,直到v同时是YESNO
也许你是想写

while v != YES and v != NO:

这将确保只有当x1M5N1X * 和 * x1M6N1X时循环才继续,因此一旦x1M7N1X是x1M8N1X或x1M9N1X,循环将停止。

sshcrbum

sshcrbum3#

使用break结束循环。例如while v == YES or v == No: break

2q5ifsrm

2q5ifsrm4#

问题出在第二个while循环中,因为条件“v!= YES or v!= NO”总是True。要正确检查输入是“YES”还是“NO”,您应该使用“v!= YES and v!= NO”。下面是更正后的代码:

def Cable_df():
    YES = 'YES'
    NO = 'NO'
    v = ''
    while v != YES:
        x = input('Enter STARTING splice of cable:').upper()
        y = input('Enter TERMINAL splice of cable:').upper()
        Z = input('Enter cable SIZE:').upper()
        v = input('ARE YOU DONE YES/NO:')
        while v != YES and v != NO:
            print('Must answer YES/NO:')
            v = input('ARE YOU DONE YES/NO:')
yyyllmsg

yyyllmsg5#

对于已写入continue的while循环,必须满足以下条件:
v不等于“是”

  • -或者--
    v不等于“否”
    这两个条件将始终被选中,因此,因为v只能被赋予一个值-这些选项中的一个将始终为真
    使用IN语句
def Cable_df():
    YES = 'YES'
    NO = 'NO'
    v = ''
    while v != YES:
        x = input('Enter STARTING splice of cable').upper()
        y = input('Enter TERMINAL splice of cable ').upper()
        Z = input('Enter cable SIZE ').upper()
        v = input('ARE YOU DONE YES/NO ')
        while v not in (YES, NO):
            print('Must answer YES/NO')
            v = input('ARE YOU DONE YES/NO ')

进一步参考:https://www.w3schools.com/python/ref_keyword_in.asp

相关问题