用条件句理解While循环

2024-10-08 19:28:10 发布

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

我刚开始学习python,需要一些理解逻辑的帮助。 微程序am编写将要求用户输入名称并验证名称是否有空格,返回错误并要求用户重新输入。 (我知道我可以使用isalpha()函数来实现它),但我想知道我在这里做错了什么,程序第一次运行,在我重新输入名称后,即使有空格,也会执行。 提前谢谢

s = input("Please enter your name: ")
def has_space(item):
    for i in item:
        if i.isspace():
            print('Cannot contain spaces.')
            s = input("Please enter your name: ")
while 1:
    if has_space(s):
        print('0')
    else:
        break


print('Welcome ' + s)

Tags: 用户name名称inputyourifspace逻辑
3条回答

这里的问题不是while条件,而是has_space,因为它不返回可以计算的布尔值。这将导致while循环中的if条件进入else分支并退出while循环。你知道吗

一个可能的解决方案可能是重写方法,如:

def has_space(s):
    return ' ' in s

使用方法:

while not has_space(s):
    s = input("Please enter your name: ")

只需添加return True并访问全局valiable

s = input("Please enter your name: ")
def has_space(item):
    for i in item:
        if i.isspace():
            print('Cannot contain spaces.')
            global s
            s = input("Please enter your name: ")
            return True

while 1:
    if has_space(s):
        print('0')
    else:
        break


print('Welcome ' + s)

问题的出现是因为函数正在访问全局变量,并且它不返回true或false。你知道吗

我相信你正在努力实现以下目标:

while True:
    s = input("Please enter your name: ")
    if " " not in s:
        break
    print('Cannot contain spaces.')
print('Welcome ' + s)

让我们从函数开始分析代码的错误:

def has_space(item):
    for i in item:
        if i.isspace():
            print('Cannot contain spaces.')
            s = input("Please enter your name: ")

这里,在检查每个字符是否为空格时,要求用户插入一个名称,并将其分配给一个局部变量s,该变量与全局变量s不一致。你知道吗

这意味着您要解析用户输入,要求为最初插入的名称中的每个空格输入一个新名称,而不做任何处理。你知道吗

此外,在if中使用此函数作为布尔条件,但该函数不返回任何内容:这被视为返回Noneif Noneif False相同。你知道吗

更好的方法是将控件和用户输入请求分为两个不同的功能,例如:

def has_space(item):
    return " " in item

def ask_name():
    return input("Please enter your name: ")

while 1:
    s = ask_name()
    if has_space(s):
        print('Cannot contain spaces.')
    else:
        break

相关问题 更多 >

    热门问题