[英]Variable comes up as a string; TypeError: bad operand type for abs(): 'str'
When trying to run this code, it seems to insist that variable x is a string, even after double checking that it is an integer and converting it to one.当试图运行这段代码时,它似乎坚持变量 x 是一个字符串,即使在仔细检查它是一个整数并将其转换为一个之后也是如此。
import time
x = 0
while True:
print("")
x = input("Please give a value for X.")
try:
int(x)
except:
print("")
print("Sorry, please use an integer and try again!")
time.sleep(1)
else:
int(x)
break
abs(x)
As mentioned in the title, the error I get in response is this:正如标题中提到的,我得到的错误响应是这样的:
TypeError: bad operand type for abs(): 'str'
This also occurs for other basic operands.对于其他基本操作数也会发生这种情况。 Why is it detecting the variable as a string and how do I fix it?为什么它将变量检测为字符串,我该如何修复它?
X variable wasn't updated when you converted it to int. X 变量在您将其转换为 int 时未更新。 It should be x = int(x)
.它应该是x = int(x)
。
import time
x = 0
while True:
print("")
x = input("Please give a value for X.")
try:
x = int(x)
except:
print("")
print("Sorry, please use an integer and try again!")
time.sleep(1)
else:
x = int(x)
break
print(abs(x))
Do:做:
abs(int(x))
To convert x to integer again再次将 x 转换为整数
The function int() take an argument and if possible, convert it to an int.函数 int() 接受一个参数,如果可能,将其转换为 int。 it returns the converted argument, but does not modify it.它返回转换后的参数,但不修改它。 So, you can use it as follow examples:因此,您可以将其用作以下示例:
i=int("123")
i=int(12.5)
s="123"
i=int(s)
line = input("Please give a value for X.")
i=int(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.