常见的一些BUG

常见的一些BUG,但实际上在编写代码时,我们应该尽可能避免这些类型的错误:

  1. 变量名与函数名冲突:
python 复制代码
def main():  
   print("Hello, World!")
main = 5  
print("The value of main is:", main)  
  1. 函数参数传递错误:
python 复制代码
def add(a, b):  
   return a + b
result = add(1, 2)  
print("1 + 2 =", result)  
  1. 运算符优先级错误:
python 复制代码
age = 10
if age < 18:  
   print("未成年")  
elif age >= 18:  
   print("成年")  
else:  
   print("奇怪,你的年龄不在合理范围内")  
  1. 嵌套循环计算错误:
python 复制代码
for i in range(10):  
   for j in range(10):  
       if i == j:  
           print(i)  
  1. 条件语句逻辑错误:
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)  
  1. 函数返回值错误:
python 复制代码
def get_square(a):  
   return a ** 2
result = get_square(5)  
print("5 的平方是:", result)  
  1. 变量作用域错误:
python 复制代码
def outer_function():  
   global result  
   result = 10
def inner_function():  
   result = 5
inner_function()  
print("outer_function 中的 result:", result)  
  1. 循环未正确终止:
python 复制代码
for i in range(10):  
   if i == 5:  
       break  
   print(i)  
  1. 函数递归调用导致无限循环:
python 复制代码
def factorial(n):  
   if n == 0:  
       return 1  
   else:  
       return n * factorial(n-1)
n = 10  
result = factorial(n)  
print("10 的阶乘是:", result)  
  1. 类属性与实例属性混淆:
python 复制代码
class Person:  
   height = 170
p = Person()  
print("Person 类的 height 是:", Person.height)  
print("实例 p 的 height 是:", p.height)  
  1. 误将全局变量当作局部变量:
python 复制代码
def function():  
   global x  
   x = 10
function()  
print("主程序中的 x:", x)  
  1. 在循环中修改列表长度:
python 复制代码
my_list = [1, 2, 3, 4, 5]
for i in my_list:  
   if i == 3:  
       my_list.remove(i)  
       print("删除了元素")  
  1. 切片越界:
python 复制代码
my_string = "Hello, World!"
print(my_string[9:10])  
  1. 函数参数传递错误(列表切片):
python 复制代码
def print_list(lst):  
   print(lst)
print_list([1, 2, 3][:3])  
  1. 误将整数当作字符串:
python 复制代码
age = 18
if age < 18:  
   print("未成年")  
elif age >= 18:  
   print("成年")  
else:  
   print("奇怪,你的年龄不在合理范围内")  
相关推荐
初遇你时动了情8 分钟前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html
成功人chen某24 分钟前
配置VScodePython环境Python was not found;
开发语言·python
QQ27402875628 分钟前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
前端小崔37 分钟前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器
哎呦你好1 小时前
HTML 表格与div深度解析区别及常见误区
前端·html
运维@小兵1 小时前
vue配置子路由,实现点击左侧菜单,内容区域显示不同的内容
前端·javascript·vue.js
2301_786964361 小时前
EXCEL Python 实现绘制柱状线型组合图和树状图(包含数据透视表)
python·microsoft·excel
skd89991 小时前
小蜗牛拨号助手用户使用手册
python
「QT(C++)开发工程师」1 小时前
STM32 | FreeRTOS 递归信号量
python·stm32·嵌入式硬件
史迪仔01121 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式