python脚本陷入无限while循环

2024-06-08 06:50:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望脚本重复input问题,直到用户提示正确答案。在用户提示正确答案之后,脚本必须继续使用相对if语句(在本例中为hostnamefile)。我拿出了下面的代码,不过似乎陷入了无限循环。你知道吗

import socket

def ipFromHost():
  opt1 = input('Do you want provide  hostname or file: ') 
  while opt1 != 'hostname' or 'file':
    input('Please, type "hostname" or "file"')
  if opt1 == 'hostname':
    optHostname = input('Please, provide hostname: ')
    print(socket.gethostbyname(optHostname.strip()))
  elif opt1 == 'file':
    optFile = input('Please, provide file name: ')
    with open(optFile) as inputFile:
      for i in inputFile:
        print(socket.gethostbyname(i.strip()))

谢谢!你知道吗


Tags: or答案用户脚本inputifsockethostname
2条回答

您有一个无限循环,因为条件while opt1 != 'hostname' or 'file':检查2个条件:

  1. opt1 != 'hostname'
  2. 'file'

即使opt1 != 'hostname'将计算为True,第二个条件实际上检查'file'True还是False(比较if opt1 != 'file'if 'file')。您可以检查this关于python

因为if 'file'总是True,所以生成一个无限循环

固定

  1. while opt1 != 'hostname' and opt1 != 'file':[使用AND因为opt1必须与两个选项不同]
  2. while opt1 not in ('hostname', 'file')[在我看来更整洁了]

您的代码应该如下所示:

def ipFromHost():
  opt1 = input('Do you want provide  hostname or file: ') 
  while opt1 not in ('hostname', 'file'):
    opt1 = input('Please, type "hostname" or "file"')
while opt1 not in ["hostname", "file"]:
    opt1 = input(...

如注释中所述,while循环的条件很差。你知道吗

相关问题 更多 >

    热门问题