Python 3 While 循环

Python 3 While loop

while True:
    name = input('Enter Texture Pack Name- ')
    name_length = len(name)

    if len(name) <= 0:
        print ('You didnt write anything, try again.')

    if len(name) == 1:
        print ('Thats not enough, try again.')

    if len(name) >= 18:
        print ('Thats to much, try again.')    

    if int(name_length) >= 2:
        break

print (('Texture Pack- %s') % (name))

所以我试图为名称描述设置 2 个限制,一个太小,一个太大。我将中断设置为 >= 2,因此超过 18 个最大限制的任何内容都会中断。我如何告诉它仅在长度大于 2 但小于 18 时才断开?

试试这个:

name = input('Enter Texture Pack Name- ')
while len(name) <= 2 or len(name) >= 18:
    print('Error - texture pack name length should be between 2 and 17 characters')
    name = input('Enter Texture Pack Name- ')

首先,我发现了几个问题。

并非所有代码都在您的 while 循环中。所有 if 语句都应该在您的 while 循环中,只需将其缩进即可。这可能是它应该的样子:

while True:
    name = input("Enter Texture Pack Name- ")
    name_length = len(name)

    if name_length <= 0 or >=18:
        print("There's an error!")
        break
    else:
        print("texture pack- %s" % (name)

希望对您有所帮助。正如您所知,break 必须在一个循环内。

编辑:丢弃顶部。我正在重写这个!

while True:
    try:
        name = input("Enter texture pack name: ")
        name_length = int(len(name))
    if name_length <= 0:
        raise ValueError("Nothing was written!")
    elif name_length == 1:
        raise ValueError("Only one character!")
    elif name_length >= 18:
        raise ValueError("More than 18!")
    else:
        break
print ("Texture pack: %s" % (name))

这将不断要求正确的输入,直到它正确为止。