[英]How can you restrict user to only input alphabets in Python?
我是一名尝试学习 Python 的初学者。 第一个问题。
试图找到一种方法让用户只输入字母。 写了这个,但是不行! 它返回True
,然后跳过 rest,然后继续执行else
子句。 break
也不起作用。
有人能指出为什么吗? 我认为这是非常基本的,但我被困住了,如果有人能把我拉出来,我会很感激。
while True:
n = input("write something")
if print(n.isalpha()) == True:
print(n)
break
else:
print("Has to be in alphabets only.")
您的问题是print
function。 print
不返回任何内容,因此您的if
语句始终将None
与True
进行比较。
while True:
n = input("write something")
if n.isalpha():
print(n)
break
else:
print("Has to be in alphabets only.")
你的陈述应该是if n.isalpha() == True:
。 print
不会返回任何内容,因此值为None
。 然后,您将None
与True
进行比较
while True:
n = input("write something")
if n.isalpha() == True:
print(n)
break
else:
print("Has to be in alphabets only.")
我已经修复了这个错误,下面是更新的代码:
while True:
n = input("write something: ")
if n.isalpha() == True:
print(n)
break
else:
print("Has to be in alphabets only.")
不要使用print(n.isaplha())
,它将始终为 True。 删除 print() 并仅使用n.isalpha()
尝试这个:-
while True:
n = input("write something")
if print(n.isalpha()) == True:
print(n)
break
else:
print("Has to be in alphabets only.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.