Python Hangman用户输入验证
我正在用Python开发一个Hangman游戏,我需要用户验证输入,我已经尝试过了,但我不知道为什么它不起作用 我的任务是为1生成“错误”消息。空输入,2。非整数,非空输入,3。索引超出输入范围。通过索引超出范围,我的意思是我要求用户输入一个0-9之间的整数,以便从程序中已有的列表中选择一个单词Python Hangman用户输入验证,python,validation,python-3.x,user-input,Python,Validation,Python 3.x,User Input,我正在用Python开发一个Hangman游戏,我需要用户验证输入,我已经尝试过了,但我不知道为什么它不起作用 我的任务是为1生成“错误”消息。空输入,2。非整数,非空输入,3。索引超出输入范围。通过索引超出范围,我的意思是我要求用户输入一个0-9之间的整数,以便从程序中已有的列表中选择一个单词 def getLetterFromUser(totalGuesses): while True: userInput = input("\nPlease enter the lette
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的调用处于while循环中,因此它会重复检查这些条件
编辑:我拿出了不属于我的东西。非常感谢。然而,我的问题是,它仍然告诉我输入的不是字母表,而不是字母表。输入的长度(单个字符)是2,除非它计算空字符,否则没有意义 您的问题是某些验证规则应该优先于其他规则。例如,如果
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
首先有两件事: 这条线的目的是什么
userInput = userInput.lower()
如果假设userInput为整数。。
您应该尝试userInput=int(userInput)。整数没有.lower()方法
下一行
if 0 > userInput or userInput > 9
这假设userInput是一个整数(您是在比较0和9,而不是“0”和“9”)
以下看起来更好:
if not 0<=userInput<=9
如果不是0你说你想要整数答案,但是你没有将输入转换为int,但是你说如果输入不在字母表中,它应该返回一条错误消息。你要求的是两件不同的事情
您希望用户输入整数还是字符?这可能有助于您:
>>> 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
>>int(“33\n”)
33
>>>内部(“33a asfd”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:基数为10的int()的文本无效:“33a asfd”
>>>尝试:
... int(“adsf”)
... 除值错误外:
... 打印“无效输入不是数字”
...
无效输入不是一个数字
您遇到了什么问题或错误?为什么要让用户选择单词,为什么在“猜测字母”提示循环中出现该选项?@Edwin我很抱歉,如果您无意中粘贴了该选项。不管它,因为它去其他地方。对其他人:我收到的错误是,无论我输入什么,它永远都不对。它通常说“你必须输入一个字母字符”,我就是这么做的。另外,我很好奇,所以我检查了输入的长度(一个字符)及其始终为2。我不知道为什么。您的问题似乎与查看相关:)(显然,python-2.x中的原始输入现在是python-3.x中的输入)为了响应您的编辑,请尝试print(repr(userInput))
查看其中的真正内容(它不是NUL字符,它们在Python中的工作方式与在C中的工作方式不同-在Python中NUL只是另一个完全有效的字符)。我在pyscripter中,pyscripter是Python的IDE。只需按enter键进入下一行。