为什么python中的!=运算符不能用于键入函数(或者只是我的代码)?

0 python string variables

我想在问一些上下文之前提供我的代码.

我的代码:

a = float(input('Insert the value for a: '))
b = float(input('Insert the value for b: '))
c = float(input('Insert the value for c: '))
if type(a) != (float() or int()):
print ('You didn\'t insert a number! Try again! This is your last chance or I will stop running!')
sleep(1)
print (a)
if type(b) != (float() or int()):
print ('You didn\'t insert a number! Try again! This is your last chance or I will stop running!')
sleep(1)
print (b)
if type(c) != (float() or int()):
print ('You didn\'t insert a number! Try again! This is your last chance or I will stop running!')
sleep(1)
print (c)
Run Code Online (Sandbox Code Playgroud)

这输出(假设我输入值):

插入a的值:8

插入b:3的值

插入c:2的值

你没有插入数字!再试一次!这是你的最后一次机会,否则我将停止运行!

8

你没有插入数字!再试一次!这是你的最后一次机会,否则我将停止运行!

3.0

你没有插入数字!再试一次!这是你的最后一次机会,否则我将停止运行!

2.0

问题是我指定如果它不是浮点数或整数,它应该传递消息.但我确实插入了一个整数,但它仍然打印出字符串.有什么问题?您可以将变量分配给数字类型吗?

Sha*_*ger 6

你调用了floatint构造函数,它们没有参数,返回零值.

所以:

if type(a) != (float() or int()):
Run Code Online (Sandbox Code Playgroud)

翻译为:

if type(a) != (0.0 or 0):
Run Code Online (Sandbox Code Playgroud)

那么(由于布尔评估规则)变成:

if type(a) != 0:
Run Code Online (Sandbox Code Playgroud)

这显然是错的.

如果你想测试精确的类型,请与in上一个tuple类型,例如:

if type(a) not in (float, int):
Run Code Online (Sandbox Code Playgroud)

通常你接受子类,所以Pythonic的方法是:

if not isinstance(a, (float, int)):
Run Code Online (Sandbox Code Playgroud)

当然,这些都不能解决您的检查问题.您a通过将a转换为a str来明确创建float.如果字符串不是合法值,它总是会成为a float,或者它会引发a .类型检查永远不会有帮助.ValueErrorfloat

所以你真正想要的是在try块中执行转换并在失败时捕获异常:

try:
    a = float(input('Insert the value for a: '))
    b = float(input('Insert the value for b: '))
    c = float(input('Insert the value for c: '))
except ValueError:
    sys.exit('You didn\'t insert a number!')  # or some equivalent action to handle failure
Run Code Online (Sandbox Code Playgroud)

如果你想循环,直到他们给你一个有效的数字,我们有几个 问题要选择 (有几十个,我也懒得将它们连接所有).