Skip to main content
 首页 » 编程设计

python之我将如何禁止数字作为输入

2025年05月04日18mengfanrong

好的,所以我定义了一个函数,用户可以在其中输入他/她的名字。我想让它不允许用户为他/她的名字输入像“69”这样的数字。我该怎么做呢?这是我使用的代码:

def name(): 
    while True: 
        name = input("What is your name? ")) 
        try: 
            return str(name) 
            break 
        except TypeError: 
            print("Make sure to enter your actual name.") 

请您参考如下方法:

您可以使用 isalpha()检查名称:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

>>> "69".isalpha() 
False 
>>> "test".isalpha() 
True 

这是您修改后的代码:

while True: 
    name = input("What is your name? ") 
    if name.isalpha(): 
        break 
    else: 
        print("Make sure to enter your actual name.") 
        continue 

或者:

name = input("What is your name? ") 
 
while not name.isalpha(): 
    print("Make sure to enter your actual name.") 
    name = input("What is your name? ")