'while用户名!=str()'将不接受字符串

2024-10-01 02:27:46 发布

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

我的导师让我做一个'ID printer',我想让程序在输入你的名字时不接受整数,但是这样做不会接受字符串。我的代码在下面。在

 User_Name = ""
 def namechecker():
    print("Please Input Your name")
    User_Name = str(input(":"))
    while User_Name == "":
         print("Please input your name")
         User_Name = str(input(":"))


    while User_Name != str():
         print("Please use characters only")
         print("Please input your name")
         User_Name = input (":")

print("Thankyou, ", User_Name)
namechecker()

Tags: name程序idinputyour名字printerprint
2条回答

如果您想跟上检查数字的想法,还可以使用str.isdigit公司()

像这样:

def namechecker():
  User_Name = ""
  while True:
    User_Name = input("Please input your name: ") # input will always be a string
    if User_Name.isdigit(): # check if the string contains only digits // returns True or False
      print("Please use chracters only")
      continue # stay inside the loop if the string contains only digits
    else: break # leave the loop if there are other characters than digits  
  print("Thankyou, ", User_Name)

namechecker()

请注意,如果给定的字符串只包含个数字,这个代码才会请求另一个输入。如果要确保字符串只由字母字符组成,则可以使用字符串.isalpha()

^{pr2}$

这样就可以了,而且输入中不允许有数字。但是,您应该阅读Built-in Types上的文档。在

你的问题很不清楚。在仔细阅读之后,我认为您希望获得一个只有字母字符的用户名。您可以使用str.isalpha来完成此操作:

def getUserName():
   userName = ''
   while userName == '' or not userName.isalpha():
        userName = input('Please input your name: ')
        if not userName.isalpha():
            print('Please use alphabet characters only')
   return userName

userName = getUserName()
print('Thank you, {}'.format(userName))

相关问题 更多 >