百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

python 示例代码(python代码详解)

wptr33 2025-06-23 22:40 23 浏览

以下是35个python代码示例,涵盖了从基础到高级的各种应用场景。这些示例旨在帮助你学习和理解python编程的各个方面。

1. Hello, World!

# python

print("Hello, World!") #result:Hello, World!

print("Hello", "World!") #result:Hello World!

print(", ".join(["Hello", "World"])) # 输出:Hello, World

# print() 在输出时自动将逗号分隔的参数用空格连接起来。

2. 变量与数据类型

# python

x = 5 # 整数

y = 3.14 # 浮点数

name = "Alice" # 字符串

is_active = True # 布尔值

""""

py变量类型是其值的类型

a = 3 #int

a = "hello" #str

可以根据需要进行转换

a = '2'

a = int(a)

""""

3. 基本算术运算

# python

a = 10

b = 3

print(a + b) # 加法

print(a - b) # 减法

print(a * b) # 乘法

print(a / b) # 除法

print(a % b) # 取余

print(a **b) # 幂运算

4. 字符串操作

# python

s = "Hello, python!"

print(s.upper()) # 转换为大写

print(s.lower()) # 转换为小写

print(s.replace("python", "World")) # 替换字符串

print(s.split(",")) # 分割字符串

5. 列表操作

# python

fruits = ["apple", "banana", "cherry"]

fruits.append("date") # 添加元素

fruits.remove("banana") # 移除元素

print(fruits[1]) # 访问元素

print(len(fruits)) # 列表长度

6. 元组操作

# python

coordinates = (10.0, 20.0, 30.0)

print(coordinates[0]) # 访问元素

# coordinates(0) = 15.0 # 元组不可变,会报错

7. 字典操作

# python

student = {

"name": "Bob",

"age": 20,

"courses": ["Math", "CompSci"]

}

print(student["name"]) # 访问值

student["age"] = 21 # 修改值

student["phone"] = "1234567890" # 添加键值对

for k in student.keys():

print(k,':', student[k],end = '\n') #输出字典所有元素

"""

name : Bob

age : 21

courses : ['Math', 'CompSci']

phone : 1234567890

"""

8. 集合操作

# python

set1 = {1, 2, 3}

set2 = {3, 4, 5}

print(set1.union(set2)) # 并集

print(set1.intersection(set2)) # 交集

print(set1.difference(set2)) # 差集

9. 条件语句

# python

age = 18

if age >= 18:

print("成年人")

elif age > 13:

print("青少年")

else:

print("儿童")

10. 循环语句 - for循环

# python

for i in range(5):

print(i)

11. 循环语句 - while循环

# python

count = 0

while count < 5:

print(count)

count += 1

12. 函数定义

# python

def greet(name):

return f"Hello, {name}!"

print(greet("Alice"))

13. 函数参数 - 默认值

# python

def greet(name, message="Hello"):

return f"{message}, {name}!"

print(greet("Bob"))

print(greet("Bob", "Hi"))

14. 函数参数 - 可变参数

# python

def add(*args):

return sum(args)

print(add(1, 2, 3, 4))

15. 匿名函数 - lambda

# python

add = lambda x, y: x + y

print(add(5, 3))

16. 列表推导式

# python

numbers = [1, 2, 3, 4, 5]

squares = [x **2 for x in numbers]

print(squares)

17. 字典推导式

# python

keys = ['a', 'b', 'c']

values = [1, 2, 3]

dictionary = {k: v for k, v in zip(keys, values)}

print(dictionary)

18. 集合推导式

# python

numbers = [1, 2, 2, 3, 4, 4, 5]

unique_even = {x for x in numbers if x % 2 == 0} # unique意为惟一的

print(unique_even)

19. 异常处理 - try-except

# python

try:

result = 10 / 0

except ZeroDivisionError:

print("除以零错误")

20. 异常处理 - try-except-else-finally

# python

try:

result = 10 / 2

except ZeroDivisionError:

print("除以零错误")

else:

print("结果是:", result)

finally:

print("执行完毕")

21. 文件操作 - 读取文件

# python

with open("example.txt", "r") as file:

content = file.read()

print(content)

22. 文件操作 - 写入文件

# python

with open("example.txt", "w") as file:

file.write("Hello, World!")

# 注意example.txt必须置于当前文件夹(程序所在文件夹)否则要求路径

23. 文件操作 - 追加文件

# python

with open("example.txt", "a") as file:

file.write("\n追加的内容")

24. 类与对象

# python

class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print(f"{self.name} says Woof!")

my_dog = Dog("Buddy", 3)

my_dog.bark()

25. 继承

# python

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

print(f"{self.name} makes a sound.")

class Cat(Animal):

def speak(self):

print(f"{self.name} says Meow!")

my_cat = Cat("Whiskers")

my_cat.speak()

26. 多态

# python

class Animal:

def speak(self):

pass

class Dog(Animal):

def speak(self):

print("Woof!")

class Cat(Animal):

def speak(self):

print("Meow!")

def make_animal_speak(animal):

animal.speak()

dog = Dog()

cat = Cat()

make_animal_speak(dog)

make_animal_speak(cat)

27. 装饰器 - 基本示例

# python

def decorator(func):

def wrapper():

print("Before function call")

func()

print("After function call")

return wrapper

@decorator

def say_hello():

print("Hello!")

say_hello()

28. 装饰器 - 带参数

# python

def repeat(times):

def decorator(func):

def wrapper(*args, **kwargs):

for _ in range(times):

func(*args, **kwargs)

return wrapper

return decorator

@repeat(3)

def greet(name):

print(f"Hello, {name}!")

greet("Alice")

29. 生成器 - 基本示例

# python

def countdown(n):

while n > 0:

yield n

n -= 1

for number in countdown(5):

print(number)

# python

def fibonacci():

a, b = 0, 1

while True:

yield a

a, b = b, a + b

print("\n\n数值小于100的项:")

for num in fibonacci():

if num >= 100:

break

print(num, end=" ")

30. 生成器表达式

# python

numbers = (x for x in range(10))

for num in numbers:

print(num)

31. 模块导入 - 导入整个模块

# python

import math

print(math.sqrt(16))

32. 模块导入 - 导入特定函数

# python

from math import sqrt

print(sqrt(25))

33. 模块导入 - 重命名模块

# python

import math as m

print(m.pi)

34. 模块导入 - 重命名函数

# python

from math import sqrt as square_root

print(square_root(36))

相关推荐

oracle数据导入导出_oracle数据导入导出工具

关于oracle的数据导入导出,这个功能的使用场景,一般是换服务环境,把原先的oracle数据导入到另外一台oracle数据库,或者导出备份使用。只不过oracle的导入导出命令不好记忆,稍稍有点复杂...

继续学习Python中的while true/break语句

上次讲到if语句的用法,大家在微信公众号问了小编很多问题,那么小编在这几种解决一下,1.else和elif是子模块,不能单独使用2.一个if语句中可以包括很多个elif语句,但结尾只能有一个else解...

python continue和break的区别_python中break语句和continue语句的区别

python中循环语句经常会使用continue和break,那么这2者的区别是?continue是跳出本次循环,进行下一次循环;break是跳出整个循环;例如:...

简单学Python——关键字6——break和continue

Python退出循环,有break语句和continue语句两种实现方式。break语句和continue语句的区别:break语句作用是终止循环。continue语句作用是跳出本轮循环,继续下一次循...

2-1,0基础学Python之 break退出循环、 continue继续循环 多重循

用for循环或者while循环时,如果要在循环体内直接退出循环,可以使用break语句。比如计算1至100的整数和,我们用while来实现:sum=0x=1whileTrue...

Python 中 break 和 continue 傻傻分不清

大家好啊,我是大田。今天分享一下break和continue在代码中的执行效果是什么,进一步区分出二者的区别。一、continue例1:当小明3岁时不打印年龄,其余年龄正常循环打印。可以看...

python中的流程控制语句:continue、break 和 return使用方法

Python中,continue、break和return是控制流程的关键语句,用于在循环或函数中提前退出或跳过某些操作。它们的用途和区别如下:1.continue(跳过当前循环的剩余部分,进...

L017:continue和break - 教程文案

continue和break在Python中,continue和break是用于控制循环(如for和while)执行流程的关键字,它们的作用如下:1.continue:跳过当前迭代,...

作为前端开发者,你都经历过怎样的面试?

已经裸辞1个月了,最近开始投简历找工作,遇到各种各样的面试,今天分享一下。其实在职的时候也做过面试官,面试官时,感觉自己问的问题很难区分候选人的能力,最好的办法就是看看候选人的github上的代码仓库...

面试被问 const 是否不可变?这样回答才显功底

作为前端开发者,我在学习ES6特性时,总被const的"善变"搞得一头雾水——为什么用const声明的数组还能push元素?为什么基本类型赋值就会报错?直到翻遍MDN文档、对着内存图反...

2023金九银十必看前端面试题!2w字精品!

导文2023金九银十必看前端面试题!金九银十黄金期来了想要跳槽的小伙伴快来看啊CSS1.请解释CSS的盒模型是什么,并描述其组成部分。答案:CSS的盒模型是用于布局和定位元素的概念。它由内容区域...

前端面试总结_前端面试题整理

记得当时大二的时候,看到实验室的学长学姐忙于各种春招,有些收获了大厂offer,有些还在苦苦面试,其实那时候的心里还蛮忐忑的,不知道自己大三的时候会是什么样的一个水平,所以从19年的寒假放完,大二下学...

由浅入深,66条JavaScript面试知识点(七)

作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录由浅入深,66条JavaScript面试知识点(一)由浅入深,66...

2024前端面试真题之—VUE篇_前端面试题vue2020及答案

添加图片注释,不超过140字(可选)1.vue的生命周期有哪些及每个生命周期做了什么?beforeCreate是newVue()之后触发的第一个钩子,在当前阶段data、methods、com...

今年最常见的前端面试题,你会做几道?

在面试或招聘前端开发人员时,期望、现实和需求之间总是存在着巨大差距。面试其实是一个交流想法的地方,挑战人们的思考方式,并客观地分析给定的问题。可以通过面试了解人们如何做出决策,了解一个人对技术和解决问...