Skip to main content
 首页 » 编程设计

python之了解带条件的 While 循环

2025年05月04日9飞鱼

我刚开始使用 python,需要一些帮助来理解逻辑。 正在编写的微程序将要求用户输入名称并验证名称是否有空格,返回错误并要求用户重新输入。 (我知道我可以使用 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) 

请您参考如下方法:

这里的问题不在于 while 条件,而在于 has_space,因为它不返回可以计算的 bool 值。这会导致 while 循环内的 if 条件进入 else 分支并退出 while 循环。

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

def has_space(s): 
    return ' ' in s 

和用法:

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