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

python 示例代码

itomcoil 2025-05-16 13:55 10 浏览

以下是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))

相关推荐

CentOS7服务器,这样搭建Tensorflow很快!我可以提前去吃饭了

CentOS7搭建Tensorflow框架凡是我相信的,我都做了;凡是我做了的事,都是全身心地投入去做的。WhateverIbelieved,Idid;andwhateverIdid,...

python2.0和python3.0的区别(python2.7和3.7哪个好)

Python3.0是Python语言的一次重大升级,与Python2.x系列存在许多不兼容的改动。以下是两者核心区别的全面总结,按重要性和使用频率排序:一、最关键的破坏性变更特性Pyth...

体验无GIL的自由线程Python:Python 3.13 新特征之一

全局解释器锁(GIL,GlobalInterpreterLock)是Python中备受争议的特性之一。它的主要作用是确保Python是一种线程安全的编程语言,防止多个线程同时访问和修改同一...

Python 3.8异步并发编程指南(python异步调用)

有效的提高程序执行效率的两种方法是异步和并发,Golang,node.js之所以可以有很高执行效率主要是他们的协程和异步并发机制。实际上异步和并发是每一种现代语言都在追求的特性,当然Python也不例...

Python测试框架pytest入门基础(pytest框架搭建)

Pytest简介Pytestisamaturefull-featuredPythontestingtoolthathelpsyouwritebetterprograms.T...

Python学不会来打我(8)字符串string类型深度解析

2025年全球开发者调查显示,90%的Python项目涉及字符串处理,而高效使用字符串可提升代码效率40%。本文系统拆解字符串核心操作,涵盖文本处理、数据清洗、模板生成等八大场景,助你掌握字符串编程精...

windows使用pyenv安装多python版本环境

官方的介绍。pyenvletsyoueasilyswitchbetweenmultipleversionsofPython.It’ssimple,unobtrusive,an...

Python 中 base64 编码与解码(Python 中 base64 编码与解码生成)

base64是经常使用的一种加密方式,在Python中有专门的库支持。本文主要介绍在Python2和Python3中的使用区别:在Python2环境:Python2.7.16(d...

Python项目整洁的秘诀:深入理解__init__.py文件

当你发现项目中import语句越来越混乱时,问题可能出在缺少这个关键文件上作为一名Python开发者,我曾深陷项目结构混乱的困境。直到真正理解了__init__.py文件的价值,我的代码世界才变得井然...

如何把一个Python应用程序装进Docker

准备容器无处不在,但是如何在Docker容器中运行Python应用程序呢?这篇文章将告诉你怎么做!如果您想知道,这些示例需要Python3.x。在深入讨论容器之前,让我们进一步讨论一下我们想要封装的...

python中数值比较大小的8种经典比较方法,不允许你还不知道

在Python中比较数值大小是基础但重要的操作。以下是8种经典比较方法及其应用场景,从基础到进阶的完整指南:1.基础比较运算符Python提供6种基础比较运算符:a,b=5,3...

Python程序员必看3分钟掌握if语句10个神技,第5个99%的人不知道

同事因为写错一个if被开除?全网疯传的Python避坑指南,看完我连夜改了代码!一、新手必踩的3大天坑(附救命代码)技巧1:缩进踩坑事件ifTrue:print("这样写必报错!...

为什么Python里遍历字符串比列表慢?3个底层原因揭秘

用字符串处理文本时,你可能正悄悄浪费性能。在日常Python开发中,我们经常需要遍历字符串和列表。但你是否注意过,当处理海量数据时,遍历字符串的速度明显比列表慢?这背后隐藏着Python设计的深层逻辑...

记录Python3.7.4更新到Python.3.7.8

Python官网Python安装包下载下载文件名称运行后选择升级选项等待安装安装完毕打开IDLE使用Python...

Python3中最常用的5种线程锁你会用吗

前言本章节将继续围绕threading模块讲解,基本上是纯理论偏多。对于日常开发者来讲很少会使用到本章节的内容,但是对框架作者等是必备知识,同时也是高频的面试常见问题。私信小编01即可获取大量Pyth...