有没有更简单的方法来编写这个比较运算符语句?

我是 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

基本上,如果用户输入任何数字,循环将重置。有什么办法可以写出这个语句来让它更高效一点吗?(即更少的代码和更清洁)


慕桂英546537
浏览 128回答 3
3回答

慕尼黑的夜晚无繁华

possibilities = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]if userGuess in possibilities:&nbsp; &nbsp; #do something或者,如果您愿意与整数进行比较,则可以执行以下操作:if userGuess < 10:&nbsp; &nbsp; #do something

郎朗坤

你可以这样做:nums = [str(i) for i in range(10)] # gets a list of nums from 0 to 9&nbsp; &nbsp;&nbsp;if userGuess in nums:&nbsp; &nbsp; print("Num found")

慕哥6287543

假设userGuess是一个字符串并且可以不是单个字符,if(any(c.isdigit()&nbsp;for&nbsp;c&nbsp;in&nbsp;userGuess): &nbsp;&nbsp;&nbsp;&nbsp;....如果猜测应该正好是一个字符,你可以if(len(userGuess)&nbsp;!=&nbsp;1&nbsp;or&nbsp;userGuess&nbsp;in&nbsp;"0123456789"): &nbsp;&nbsp;&nbsp;&nbsp;....要么if(len(userGuess)&nbsp;!=&nbsp;or&nbsp;userGuess.isdigit()): &nbsp;&nbsp;&nbsp;&nbsp;...想一想,这isdigit是更好的方法。假设用户输入了孟加拉语号码৩?৩.isdigit()是True。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python