完美解决丨TypeError: fun() takes 2 positional arguments but 3 were given

简介: 完美解决丨TypeError: fun() takes 2 positional arguments but 3 were given

```python def fun(a, b): return a + b

c = fun(1, 2, 3) ``` ``` Traceback (most recent call last): File "test.py", line 5, in <module c = fun(1, 2, 3) TypeError: fun() takes 2 positional arguments but 3 were given ```

上面的代码中, fun 函数定义了两个必须参数,但在调用 fun 函数时,传入了 3 个参数,导致了报错。

解决办法:

```python def fun(a, b): return a + b

c = fun(1, 2, 3) ```

原理解释:

python 中函数的定义和调用是遵守参数个数一致的原则的,如果函数定义了两个参数,那么在调用函数时,也要传入两个参数,否则就会报错。

编程题

请使用 Python 实现以下功能:

  • 计算两个数字的和,并输出和的结果。

```python def addTwoNums(a, b): return a + b

num1 = 1 num2 = 2 result = addTwoNums(num1, num2) print(result) ```

  • 输入一个数字,判断是否为奇数,如果是奇数就输出 True ,否则就输出 False 。

```python def isOdd(num): return num % 2 == 1

print(isOdd(1)) print(isOdd(2)) print(isOdd(3)) ```

  • 输入一个数字,判断是否为偶数,如果是偶数就输出 True ,否则就输出 False 。

```python def isEven(num): return num % 2 == 0

print(isEven(1)) print(isEven(2)) print(isEven(3)) ```

  • 输入一个英文字符串,判断字符串中是否包含数字。

```python def hasNumber(str): return any(map(lambda x: x.isdigit(), str))

print(hasNumber('abc')) print(hasNumber('abc123')) ```

  • 输入一个英文字符串,判断字符串中是否包含大写字母。

```python def hasUpperCase(str): return any(map(lambda x: x.isupper(), str))

print(hasUpperCase('abc')) print(hasUpperCase('abc123')) print(hasUpperCase('ABC123')) ```

  • 输入一个英文字符串,判断字符串是


相关文章
|
1月前
arguments,callee&caller
arguments,callee&caller
32 3
|
4月前
|
SQL 数据库连接 数据库
【Python】已完美解决:executemany() takes exactly 2 positional arguments (3 given)
【Python】已完美解决:executemany() takes exactly 2 positional arguments (3 given)
76 6
|
4月前
|
Python
【Python】已解决:TypeError: write._Log() takes 0 positional arguments but 1 was given
【Python】已解决:TypeError: write._Log() takes 0 positional arguments but 1 was given
117 0
|
4月前
|
开发者 Python
【Python】已解决:SyntaxError: positional argument follows keyword argument
【Python】已解决:SyntaxError: positional argument follows keyword argument
167 0
TypeError: custom() got an unexpected keyword argument ‘path‘
TypeError: custom() got an unexpected keyword argument ‘path‘
149 0
|
计算机视觉
成功解决TypeError: __init__() got an unexpected keyword argument 'n_iterations'
成功解决TypeError: __init__() got an unexpected keyword argument 'n_iterations'
成功解决TypeError: __init__() got an unexpected keyword argument 'serialized_options'
成功解决TypeError: __init__() got an unexpected keyword argument 'serialized_options'
解决TypeError: __init__() takes from 1 to 3 positional arguments but 6 were given
解决TypeError: __init__() takes from 1 to 3 positional arguments but 6 were given
446 0
解决TypeError: __init__() takes from 1 to 3 positional arguments but 6 were given
error: implicit declaration of function ‘RAND_egd’ [-Werror=implicit-function-declaration]
error: implicit declaration of function ‘RAND_egd’ [-Werror=implicit-function-declaration]
127 0