有关数据类型的判断

在一个小练习中,想要限制用户输入的是整数

整体内容如下

number = input("\n\t Enter a integer number, and I will tell you if it is even or odd: " + "\n\t ")
if not (type(number) is int):
    number = input("\n\t Please input a integer. " + "\n\t ")
number = int(number)

问题在于:不论输入的数字是浮点数整数if命令都会执行

我认为是if语句不合理的地方,但又不知道要怎么修改。如果是的话,要怎么修改呢? 如果不是的话,又是哪里出了问题呢?

希望大家可以支支招!多谢!

Jason990420
最佳答案

input 返回的是字符串 str, 而非intfloat, 所以not (type(number) is int)永远为True

>>> number = input("\n\t Enter a integer number, will tell you even or odd: " + "\n\t ")

         Enter a integer number, will tell you even or odd:
         123
>>> type(number)
<class 'str'>
>>> number = input("\n\t Enter a integer number, will tell you even or odd: " + "\n\t ")

         Enter a integer number, will tell you even or odd:
         1.23
>>> type(number)
<class 'str'>
>>> type(number) is int
False
>>> type(number) is float
False
>>> type(number) is str
True
>>> not (type(number) is int)
True
2周前 评论
Jason990420 (作者) 2周前
nizuitianla (楼主) 2周前
nizuitianla (楼主) 2周前
讨论数量: 1
Jason990420

input 返回的是字符串 str, 而非intfloat, 所以not (type(number) is int)永远为True

>>> number = input("\n\t Enter a integer number, will tell you even or odd: " + "\n\t ")

         Enter a integer number, will tell you even or odd:
         123
>>> type(number)
<class 'str'>
>>> number = input("\n\t Enter a integer number, will tell you even or odd: " + "\n\t ")

         Enter a integer number, will tell you even or odd:
         1.23
>>> type(number)
<class 'str'>
>>> type(number) is int
False
>>> type(number) is float
False
>>> type(number) is str
True
>>> not (type(number) is int)
True
2周前 评论
Jason990420 (作者) 2周前
nizuitianla (楼主) 2周前
nizuitianla (楼主) 2周前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!