猜字游戏用户输入验证

0 投票
4 回答
1256 浏览
提问于 2025-04-17 13:03

我正在用Python制作一个猜单词游戏,需要对用户输入进行验证。我尝试过,但不知道为什么不管用。

我的任务是为以下情况提供“错误”提示:1. 输入为空,2. 输入不是整数且不为空,3. 输入的索引超出范围。这里的索引超出范围是指,我让用户输入一个0到9之间的整数,以便从程序中已有的单词列表中选择一个单词。

def getLetterFromUser(totalGuesses):

  while True:
      userInput = input("\nPlease enter the letter you guess:")
      if userInput == '' or userInput == ' ':
          print("Empty input.")
      elif userInput in totalGuesses:
          print("You have already guessed that letter. Try again.")
      elif userInput not in 'abcdefghijklmnopqrstuvwxyz':
          print("You must enter an alphabetic character.")
      else:
          return userInput

为了更清楚,我后面的getLetterFromUser调用是在一个循环里,这样可以不断检查这些条件。

编辑:我去掉了不相关的部分。谢谢。不过,我的问题是,它还是告诉我输入不是字母,而实际上是字母。而且输入的长度(一个字符)是2,这没道理,除非它计算了空字符。

4 个回答

0

你说你想要整数的答案,但你并没有把输入转换成整数。然后你又说如果输入不是字母,就应该返回一个错误信息。你在要求两件不同的事情。

你想让用户输入一个整数,还是一个字符呢?

0

这可能对你有帮助:

>>> int(" 33   \n")
33
>>> int(" 33a asfd")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '33a asfd'
>>> try:
...     int("adsf")
... except ValueError:
...     print "invalid input is not a number"
...     
invalid input is not a number
1

你的问题是,有些验证规则应该比其他规则更重要。比如说,如果 userInput 是一个空字符串,你希望 userInput < 0 返回什么呢?如果它不是空的,但也不是数字呢?

想想哪些条件应该先检查。

你可能想了解并使用的一些函数:

"123".isdigit() # checks if a string represents an integer number
" 123 ".strip() # removes whitespaces at the beginning and end.
len("") # returns the length of a string
int("123") # converts a string to an int

撰写回答