所以我在做这个Python练习,方向是:定义一个函数调用subtractNumber(x,y),它接受两个数字并返回两个数字的差。你知道吗
示例
>>> subtractNumber(20, 7)
13
>>> subtractNumber(-20, -4)
-16
>>> subtractNumber(-2, -2)
0
我的代码
def subtractNumber(x, y):
subtraction = int(x) - int(y)
return subtraction
subtractNumber('x','y')
我得到一个错误:
Traceback (most recent call last):
File "D:\Python Exercises\Temp_Learning\Python Practice9.py", line 4, in <module>
subtractNumber('x','y')
File "D:\Python Exercises\Temp_Learning\Python Practice9.py", line 2, in subtractNumber
subtraction = int(x) - int(y)
ValueError: invalid literal for int() with base 10: 'x'
我还是不明白我哪里出错了。有人能帮我吗?谢谢。你知道吗
'x'
和'y'
不是数字,而是字符串。你认为x和y是什么数字?你知道吗如果要使用以前分配的变量,只需传递
x
和y
:如果要在两个字母后面使用ascii字符代码,请使用:
int
是用来将某些东西转换成整数的东西。你知道吗将导致
y
具有值5
int(x)
当x=5
返回5
。但是,您将字符'x'
发送到int
。int
不知道如何将其转换为整数。你知道吗这应该对你有用
在您的示例中,
'x'
和'y'
是不表示数字的字符串,因此它们不能使用int()
进行转换。所以你不能这么做:
但是,这些方法可行:
相关问题 更多 >
编程相关推荐