Python学习常见错误
1. TypeError: not enough arguments for format string
TypeError: not enough arguments for format string
或者
TypeError: %d format: a number is required, not str
错误代码:
def personInfor(name, age, sex=1):
if sex == 1:
print("这个男孩儿的姓名%s,今年%d岁了" % name % age)
else:
print("这个女孩儿的姓名%d,今年%d岁了" % name % age)
personInfor(age=20, name="Lisa", sex=0)
正确表示
%d 表示number
%s 表示String
有两个参数的时候表示方法
“%d,%s”%{number,str}
def personInfor(name, age, sex=1):
if sex == 1:
print("这个男孩儿的姓名%s,今年%d岁了" % (name, age))
else:
print("这个女孩儿的姓名%s,今年%d岁了" % (name, age))
personInfor(age=20, name="Lisa")
2. python positional argument follows keyword argument
python positional argument follows keyword argument
当参数的位置不正确时,就会报上面的错误;
关键字参数必须跟随在位置参数后面! 因为python函数在解析参数时, 是按照顺序来的, 位置参数是必须先满足, 才能考虑其他可变参数.
谨记!!!!
错误代码:
def personInfor(name, age, sex=1, *lesson):
if sex == 1:
print("这个男孩儿的姓名%s,今年%d岁了,学了%s" % (name, age, lesson))
else:
print("这个女孩儿的姓名%s,今年%d岁了,学了%s" % (name, age, lesson))
//编译不通过
personInfor(age=20, name="Gerry", sex=0,"Math", "English", "History")
正确代码:
personInfor("Lisa", 20, "Math", "English", "History")
3.TypeError: personInfor() got multiple values for argument 'age’
参数重复赋值
这里面在顺序参数已经为age赋值了,又通过关键字参数重复赋值,导致参数重复赋值。
TypeError: personInfor() got multiple values for argument 'age'
错误写法:
这里原本是想把 "Math", "English", "History"
赋值给*lesson
,但是编辑器认为是在name, age, sex=1
赋值了,造成2次赋值。
def personInfor(name, age, sex=1, *lesson):
if sex == 1:
print("这个男孩儿的姓名%s,今年%d岁了,学了%s" % (name, age, lesson))
else:
print("这个女孩儿的姓名%s,今年%d岁了,学了%s" % (name, age, lesson))
personInfor("Math", "English", "History", age=20, name="Gerry", sex=0)
正确写法:
def personInfor(name, age, sex=1, *lesson):
if sex == 1:
print("这个男孩儿的姓名%s,今年%d岁了,学了%s" % (name, age, lesson))
else:
print("这个女孩儿的姓名%s,今年%d岁了,学了%s" % (name, age, lesson))
personInfor("Lisa", 20, "Math", "English", "History")
结论:
不定长参数和关键字参数不能同时使用
4.Python错误:TypeError: ‘int’ object is not callable解决办法
TypeError: 'int' object is not callable
错误代码:
def sum(x):
sum = 0
def inner(x):
nonlocal sum
sum = 6
if x == 1:
return 1
elif x == 2:
return 1
else:
return sum(x - 1) + sum(x - 2)
错误原因和解决方法
其中函数名和参数名重复了,把重复的函数或参数名重命名即可
后续会持续更新补充
Kotlin技术专栏
长老说 这个公众号涉猎的很多,总有一款适合你。 和优秀为伴,做一个优秀的人