我刚开始学习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)
这里的问题不是while条件,而是
has_space
,因为它不返回可以计算的布尔值。这将导致while循环中的if条件进入else分支并退出while循环。你知道吗一个可能的解决方案可能是重写方法,如:
使用方法:
只需添加
return True
并访问全局valiable问题的出现是因为函数正在访问全局变量,并且它不返回true或false。你知道吗
我相信你正在努力实现以下目标:
让我们从函数开始分析代码的错误:
这里,在检查每个字符是否为空格时,要求用户插入一个名称,并将其分配给一个局部变量
s
,该变量与全局变量s
不一致。你知道吗这意味着您要解析用户输入,要求为最初插入的名称中的每个空格输入一个新名称,而不做任何处理。你知道吗
此外,在
if
中使用此函数作为布尔条件,但该函数不返回任何内容:这被视为返回None
,if None
与if False
相同。你知道吗更好的方法是将控件和用户输入请求分为两个不同的功能,例如:
相关问题 更多 >
编程相关推荐