在为Python培训编写作业时,我遇到了一些奇怪的事情。 守则:
number = 0
while number is not int:
try:
number = int(input("Give a number to start counting with: "))
break
except ValueError:
print('Please enter a valid number!')
print("the computer starts counting at number: ", number)
无论我填写什么作为number的值,while循环都会运行。填充0、6甚至一个字母,while循环将运行。 如果我加上:
print(type(number))
对它来说,它甚至说它是一个整数。那么为什么while循环没有检测到这一点呢? 现在这个程序做了我想要的,但我发现它的行为很奇怪,我不理解
要检查
number
的类型,必须执行if type(number) is not int
,但要正确构建循环,您必须这样做:
事实上,您不需要检查
number
的类型来停止循环,try: ... except:
语句中的break
将完成您的工作相关问题 更多 >
编程相关推荐