PHP前端开发

python整数怎么表示

百变鹏仔 1个月前 (01-22) #Python
文章标签 整数
python整数的表示方法:1、可以使用字符串str的isdigit方法判断字符串是否是一个仅有数字组成;2、也可以使用【try-except】语句。

本教程操作环境:windows7系统、python3.9版,DELL G3电脑。

python整数的表示方法:

1、可以使用字符串str的isdigit方法判断字符串是否是一个仅有数字组成,也就是整数。如果是整数退出while循环,否则继续请求输入。

while True:x = input('Input an integer: ')if x.isdigit():breakelse:print 'Please input an *integer*'

2、也可以使用try-except语句。如果输入的字符串是整数,那么它可以用用int()函数,转换为int类并退出循环,否则会出现ValueError,可以使用try-except语句捕获ValueError,然后继续请求输入。

立即学习“Python免费学习笔记(深入)”;

while True:try:x = input('Input an integer: ')x = int(x)breakexcept ValueError:print 'Please input an *integer*'

相关免费学习推荐:python视频教程