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

2024-09-26 22:07:35 发布

您现在位置: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")

如果所提供的输入不符合上述文本中概述的要求,我希望它循环并向用户请求另一个输入。你知道吗


Tags: nameinputyourleniflength用户名first
3条回答

让我来修正你的代码,优雅而干净:

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

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

因此,检查应该是if 2 < length < 10:(对于长度3到9是这样的)

关于你的第一句话,据我所知,从代码中你实际上是想让字符的最大数量是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执行一些验证(不允许空格或任何其他特殊字符)。你知道吗

相关问题 更多 >

    热门问题