现在,我正在尝试制作一个简单的井字游戏,并且当用户选择棋盘的下一步操作时,我需要检查输入的内容是否为一位数字的自然数.我不认为仅制作一个 ['1','2','3'...'9'] 列表并为其调用in语句是最理想的选择.你能建议什么吗?
Right now I'm trying to make a simple tic-tac-toe game, and while user chooses the sector of the board for their next move I need to check if the input is a single-digit natural number. I don't think just making a ['1','2','3'...'9'] list and calling an in statement for it is the most optimal thing. Could you suggest anything?
推荐答案通过检查字符串 x 是否包含数字和等价的整数,可以检查其是否为一位自然数这些数字中的1到9之间,即
You can check if a string, x, is a single digit natural number by checking if the string contains digits and the integer equivalent of those digits is between 1 and 9, i.e.
x.isdigit()和1< = int(x)< = 9
此外,如果 x.isdigit()返回false,则由于使用和(它是不必要的,因为结果是已知的),因此,如果字符串不是数字,则不会出现错误.
Also, if x.isdigit() returns false, int(x) is never evaluated due to the expression using and (it is unnecessary as the result is already known) so you won't get an error if the string is not a digit.
更多推荐
如何检查输入是否为Python中的自然数?
发布评论