常见的一些BUG,但实际上在编写代码时,我们应该尽可能避免这些类型的错误:
- 变量名与函数名冲突:
python
def main():
print("Hello, World!")
main = 5
print("The value of main is:", main)
- 函数参数传递错误:
python
def add(a, b):
return a + b
result = add(1, 2)
print("1 + 2 =", result)
- 运算符优先级错误:
python
age = 10
if age < 18:
print("未成年")
elif age >= 18:
print("成年")
else:
print("奇怪,你的年龄不在合理范围内")
- 嵌套循环计算错误:
python
for i in range(10):
for j in range(10):
if i == j:
print(i)
- 条件语句逻辑错误:
python
def is_positive(number):
if number > 0:
return "Yes"
elif number < 0:
return "No"
else:
return "Maybe"
result = is_positive(-5)
print("-5 是正数吗?", result)
- 函数返回值错误:
python
def get_square(a):
return a ** 2
result = get_square(5)
print("5 的平方是:", result)
- 变量作用域错误:
python
def outer_function():
global result
result = 10
def inner_function():
result = 5
inner_function()
print("outer_function 中的 result:", result)
- 循环未正确终止:
python
for i in range(10):
if i == 5:
break
print(i)
- 函数递归调用导致无限循环:
python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n = 10
result = factorial(n)
print("10 的阶乘是:", result)
- 类属性与实例属性混淆:
python
class Person:
height = 170
p = Person()
print("Person 类的 height 是:", Person.height)
print("实例 p 的 height 是:", p.height)
- 误将全局变量当作局部变量:
python
def function():
global x
x = 10
function()
print("主程序中的 x:", x)
- 在循环中修改列表长度:
python
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i == 3:
my_list.remove(i)
print("删除了元素")
- 切片越界:
python
my_string = "Hello, World!"
print(my_string[9:10])
- 函数参数传递错误(列表切片):
python
def print_list(lst):
print(lst)
print_list([1, 2, 3][:3])
- 误将整数当作字符串:
python
age = 18
if age < 18:
print("未成年")
elif age >= 18:
print("成年")
else:
print("奇怪,你的年龄不在合理范围内")