我不明白为什么这段代码不起作用:(

时间:2019-10-14 09:14:48

标签: python

如果用户名的长度在3到9个字符之间,我会尝试不接受。

print (""+winner+", please input your first name, maximum of 10 characters.")
winnername = str(input())
length = (int(len(winnername)))
if 3 > length > 10:
    loop5 = 1
    while loop5 == 1:
        print ("name is too short")
        winnername = input()
        length = len(winnername)
        if (length) <3 and (length) <10:
            break

print ("name accept")

如果提供的输入不符合以上文字概述的要求,我希望它会循环并要求用户提供其他输入。

4 个答案:

答案 0 :(得分:4)

if 3 > length > 10:正在检查以确保长度小于3且大于10,这是不可能的。

因此,支票应为if 2 < length < 10:(这对于3到9的长度是正确的)

答案 1 :(得分:0)

winner = "Mustermann"
# Build a string called "prompt"
prompt = winner + ", please input your first name, between 3 and and 10 characters."
loopLimit = 5 # Make this a variable, so it's easy to change later
loop = 0 # Start at zero
winnername = "" # Set it less than three to start, so the while loop will pick it up
# Put the while loop here, and use it as the length check
# Use an or to explicitely join them
while True: # Set an infinite loop 
    loop += 1 # Increment the loop here. 
    # Add the string to the input command. The "input" will use the prompt
    # You don't need the "str()", since input is always a string
    winnername = input(prompt)
    length = len(winnername)
    # Separate the checks, to give a better error message
    if (length < 3): 
        print ("Name is too short!") # Loop will continue
    elif (length > 10): 
        print("Name is too long!") # Loop will continue
    else: # This means name is OK. So finish
        print("Name accepted!")
        break # Will end the loop, and the script, since no code follows the loop

    if loop >= loopLimit:
        # Raise an error to kill the script
        raise RuntimeError("You have reached the allowed number of tries for entering you name!")

答案 2 :(得分:0)

让我修复您的代码,简洁整洁:

while True:
    # I don't know if `winner` is defined
    firstname = input(""+winner+", please input your first name, maximum of 10 characters.")
    if 3 < len(firstname) < 10:
       break
    print("name is too short or too long")

print('name accepted')

问题是3 > length > 10将永远不会执行,因为3永远不会比>10

答案 3 :(得分:0)

关于您的第一句话,据我所看到的代码,您实际上是在尝试允许最大字符数为10,而不是9。

以下是您尝试实现的可能解决方案。下面的脚本将不断询问用户,直到名称长度在允许的范围内。

print ("'+winner+', please input your first name, maximum of 10 characters.")

while True:
    winnername = str(input())
    if(len(winnername) < 3):
        print("Name is too short")
    elif(len(winnername) > 10):
        print("Name is too long")
    else:
        break

print ("Name accepted")

您还可以考虑先对 winnername 进行一些验证(不允许使用空格或其他任何特殊字符)。

寻找你感兴趣的贴纸↓↓↓
豫ICP备18024241号-1