如何在不知道两个整数的值的情况下减去它们?

2024-09-27 00:13:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在做这个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'

我还是不明白我哪里出错了。有人能帮我吗?谢谢。你知道吗


Tags: inpy定义line数字方向tempfile
3条回答

'x''y'不是数字,而是字符串。你认为x和y是什么数字?你知道吗

如果要使用以前分配的变量,只需传递xy

subtractNumber(x, y)

如果要在两个字母后面使用ascii字符代码,请使用:

subtractNumber(ord('x'), ord('y'))

int是用来将某些东西转换成整数的东西。你知道吗

x = '5'
y = int(x)

将导致y具有值5

int(x)x=5返回5。但是,您将字符'x'发送到intint不知道如何将其转换为整数。你知道吗

这应该对你有用

In [3]: def subtractNumber(x, y):
   ...:     return (int(x) - int(y))
   ...:

In [4]: subtractNumber(5, -6)
Out[4]: 11

In [5]: subtractNumber(5, 6)
Out[5]: -1

In [6]: subtractNumber(-5, 6)
Out[6]: -11

In [7]: subtractNumber(-5, -6)
Out[7]: 1

在您的示例中,'x''y'是不表示数字的字符串,因此它们不能使用int()进行转换。

所以你不能这么做:

subtractNumber('x', 'y')

但是,这些方法可行:

>>> subtractNumber(13, 7) # Regular integers
13
>>> subtractNumber('13', '7') # Strings that contain digits can be converted to int
13
>>> x = 13
>>> y = 7
>>> subtractNumber(x, y) # Here, x and y are variables, not strings
13

相关问题 更多 >

    热门问题