我是 Python 的新手。我有以下 if 语句:if(userGuess == "0" or userGuess == "1" or userGuess == "2" or userGuess == "3" or userGuess == "4" or userGuess == "5" or userGuess == "6" or userGuess == "7" or userGuess == "8" or userGuess == "9"): print("\n>>>error: cannot use integers\n") continue基本上,如果用户输入任何数字,循环将重置。有什么办法可以写出这个语句来让它更高效一点吗?(即更少的代码和更清洁)
3 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
possibilities = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
if userGuess in possibilities:
#do something
或者,如果您愿意与整数进行比较,则可以执行以下操作:
if userGuess < 10:
#do something
郎朗坤
TA贡献1921条经验 获得超9个赞
你可以这样做:
nums = [str(i) for i in range(10)] # gets a list of nums from 0 to 9
if userGuess in nums:
print("Num found")
慕哥6287543
TA贡献1831条经验 获得超10个赞
假设userGuess
是一个字符串并且可以不是单个字符,
if(any(c.isdigit() for c in userGuess): ....
如果猜测应该正好是一个字符,你可以
if(len(userGuess) != 1 or userGuess in "0123456789"): ....
要么
if(len(userGuess) != or userGuess.isdigit()): ...
想一想,这isdigit
是更好的方法。假设用户输入了孟加拉语号码৩
?৩.isdigit()
是True
。
添加回答
举报
0/150
提交
取消