如何检查输入是否为Python中的自然数?

编程入门 行业动态 更新时间:2024-10-18 18:25:33
本文介绍了如何检查输入是否为Python中的自然数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

现在,我正在尝试制作一个简单的井字游戏,并且当用户选择棋盘的下一步操作时,我需要检查输入的内容是否为一位数字的自然数.我不认为仅制作一个 ['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中的自然数?

本文发布于:2023-11-29 20:47:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647587.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自然数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!