---初学者必背PY基础实例代码100例---

liftword14小时前技术文章6

---初学者必背PY基础实例代码100例---

下面是关于Python数据类型、控制结构、函数、数据结构、类与继承的100个示例代码。这些示例将帮助你理解每个概念的基本用法和一些常见应用。


(一)数据类型示例(20例)


1. 整数和浮点数

```python

a = 10

b = 3.14

print(type(a), type(b))

```


2. 字符串

```python

s = "Hello, World!"

print(s)

```


3. 列表

```python

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

print(lst)

```


4. 元组

```python

t = (10, 20, 30)

print(t)

```


5. 字典

```python

d = {'name': 'Alice', 'age': 25}

print(d)

```


6. 集合

```python

set1 = {1, 2, 3}

set2 = {3, 4, 5}

print(set1.union(set2))

```


7. 布尔值

```python

flag = True

print(flag)

```


8. None类型

```python

x = None

print(x)

```


9. 类型转换

```python

x = int(3.7)

y = str(123)

print(x, y)

```


10. 字符串格式化

```python

name = "Tom"

age = 30

print(f"My name is {name} and I am {age} years old.")

```


11. 列表切片

```python

lst = [0,1,2,3,4,5]

print(lst[2:5])

```


12. 字典获取值

```python

d = {'a': 1, 'b': 2}

print(d.get('a'))

```


13. 集合运算

```python

s1 = {1,2,3}

s2 = {3,4,5}

print(s1 & s2) # 交集

```


14. 复制列表

```python

lst1 = [1, 2]

lst2 = lst1.copy()

print(lst2)

```


15. 多类型列表

```python

mixed = [1, 'two', 3.0, True]

print(mixed)

```


16. 计算字符串长度

```python

s = "Python"

print(len(s))

```


17. 列表元素出现次数

```python

lst = [1,2,2,3,4,2]

print(lst.count(2))

```


18. 字典更新

```python

d = {'x': 1}

d.update({'y': 2})

print(d)

```


19. 集合添加元素

```python

s = {1,2}

s.add(3)

print(s)

```


20. 布尔值逻辑

```python

a = True and False

b = True or False

print(a, b)

```


(二)控制结构示例(20例)


21. if语句

```python

x = 10

if x > 5:

print("x大于5")

```


22. if-elif-else

```python

score = 85

if score >= 90:

print("A")

elif score >= 70:

print("B")

else:

print("C")

```


23. for循环

```python

for i in range(5):

print(i)

```


24. while循环

```python

count = 0

while count < 5:

print(count)

count += 1

```


25. 嵌套循环

```python

for i in range(3):

for j in range(2):

print(f"i={i}, j={j}")

```


26. 控制跳出(break)

```python

for i in range(10):

if i == 5:

break

print(i)

```


27. 控制继续(continue)

```python

for i in range(5):

if i == 2:

continue

print(i)

```


28. 使用pass占位

```python

if x > 0:

pass # 未来填充代码

```


29. 列表推导式

```python

squares = [x**2 for x in range(10)]

print(squares)

```


30. 字典推导式

```python

squared_dict = {x: x**2 for x in range(5)}

print(squared_dict)

```


31. 判断语句嵌套

```python

x = 10

if x > 5:

if x < 15:

print("x在5到15之间")

```


32. 三元表达式

```python

result = "偶数" if x % 2 == 0 else "奇数"

print(result)

```


33. 使用pass

```python

def future_feature():

pass

```


34. try-except异常处理

```python

try:

1 / 0

except ZeroDivisionError:

print("不能除以零!")

```


35. for循环遍历字典

```python

d = {'a': 1, 'b': 2}

for key, value in d.items():

print(key, value)

```


36. 逐行读取文件(示例)

```python

# with open('file.txt', 'r') as f:

# for line in f:

# print(line.strip())

```


37. 断言

```python

assert 2 + 2 == 4

```


38. 简单的条件表达式

```python

max_value = x if x > y else y

```


39. 定义函数

```python

def greet(name):

return f"Hello, {name}"

```


40. 使用递归

```python

def factorial(n):

return 1 if n == 0 else n * factorial(n - 1)

```


(三)函数示例(20例)


41. 无参数函数

```python

def hello():

print("Hello")

hello()

```


42. 有参数函数

```python

def add(a, b):

return a + b

print(add(3, 5))

```


43. 默认参数

```python

def power(base, exponent=2):

return base ** exponent

print(power(3))

```


44. 可变参数(*args)

```python

def sum_all(*args):

return sum(args)

print(sum_all(1, 2, 3))

```


45. 关键字参数(**kwargs)

```python

def print_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}={value}")

print_info(name='Alice', age=30)

```


46. 嵌套函数

```python

def outer():

def inner():

print("Inner")

inner()

outer()

```


47. 返回多个值

```python

def get_point():

return (1, 2)

x, y = get_point()

```


48. 递归函数(阶乘)

```python

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

print(factorial(5))

```


49. 匿名函数(lambda)

```python

square = lambda x: x**2

print(square(4))

```


50. 高阶函数(map)

```python

nums = [1, 2, 3]

squares = list(map(lambda x: x**2, nums))

print(squares)

```


(四)数据结构示例(20例)


51. 使用列表

```python

numbers = [1, 2, 3]

numbers.append(4)

print(numbers)

```


52. 使用元组

```python

coordinates = (10.0, 20.0)

print(coordinates)

```


53. 使用字典

```python

person = {'name': 'Alice', 'age': 25}

person['city'] = 'New York'

print(person)

```


54. 使用集合去重

```python

s = [1, 2, 2, 3]

unique = set(s)

print(unique)

```


55. 使用列表作为堆栈

```python

stack = []

stack.append(1)

stack.append(2)

print(stack.pop())

```


56. 使用列表作为队列(deque)

```python

from collections import deque

queue = deque()

queue.append(1)

queue.append(2)

print(queue.popleft())

```


57. 嵌套列表

```python

matrix = [[1, 2], [3, 4]]

print(matrix[0][1])

```


58. 使用链表(自定义)

```python

class Node:

def __init__(self, data):

self.data = data

self.next = None

```


59. 栈的实现

```python

stack = []

stack.extend([1, 2, 3])

print(stack.pop())

```


60. 队列的实现

```python

from collections import deque

q = deque([1, 2, 3])

q.append(4)

print(q.popleft())

```


(五)class类与继承示例(20例)


61. 基础类定义

```python

class Person:

def __init__(self, name):

self.name = name

def greet(self):

print(f"Hello, my name is {self.name}")

```


62. 创建实例

```python

p = Person("Alice")

p.greet()

```


63. 类的继承

```python

class Student(Person):

def __init__(self, name, student_id):

super().__init__(name)

self.student_id = student_id

def study(self):

print(f"{self.name} is studying.")

```


64. 方法重写

```python

class Animal:

def speak(self):

print("Animal makes a sound")


class Dog(Animal):

def speak(self):

print("Woof!")

```


65. 多继承

```python

class Flyer:

def fly(self):

print("Flying")


class Bird(Animal, Flyer):

pass

```


66. 类变量和实例变量

```python

class Car:

wheels = 4

def __init__(self, color):

self.color = color

```


67. 静态方法

```python

class Math:

@staticmethod

def add(a, b):

return a + b

```


68. 类方法

```python

class Person:

count = 0

@classmethod

def get_count(cls):

return cls.count

```


69. 使用@property

```python

class Rectangle:

def __init__(self, width, height):

self._width = width

self._height = height

@property

def area(self):

return self._width * self._height

```


70. 抽象类(使用abc)

```python

from abc import ABC, abstractmethod


class Shape(ABC):

@abstractmethod

def area(self):

pass

```


71. 继承抽象类

```python

class Circle(Shape):

def __init__(self, radius):

self.radius = radius

def area(self):

import math

return math.pi * self.radius ** 2

```


72. 装饰器示例

```python

def decorator(func):

def wrapper():

print("Before function")

func()

print("After function")

return wrapper


@decorator

def say_hello():

print("Hello")

```


73. 类的私有变量

```python

class Example:

def __init__(self):

self.__private_var = 42

def get_private(self):

return self.__private_var

```


74. 类的继承多层结构

```python

class Animal:

pass


class Mammal(Animal):

pass


class Dog(Mammal):

pass

```


75. 方法链

```python

class Builder:

def __init__(self):

self.result = ""

def add(self, s):

self.result += s

return self

def build(self):

return self.result

b = Builder().add("Hello").add(" ").add("World").build()

print(b)

```


76. 继承构造函数调用

```python

class Parent:

def __init__(self):

print("Parent init")


class Child(Parent):

def __init__(self):

super().__init__()

print("Child init")

```


77. 使用__str__方法

```python

class Person:

def __init__(self, name):

self.name = name

def __str__(self):

return f"Person({self.name})"

```


78. 类变量修改

```python

class Counter:

count = 0

def increment(self):

Counter.count += 1

```


79. 动态添加方法(类型绑定)

```python

class MyClass:

pass


def new_method(self):

print("New method")


obj = MyClass()

import types

obj.new_method = types.MethodType(new_method, obj)

obj.new_method()

```


80. 单继承多重初始化调用

```python

class A:

def __init__(self):

print("A init")


class B(A):

def __init__(self):

super().__init__()

print("B init")

```


(六)其他实用示例(20例)


81. 测试所有字典值

```python

d = {'a': 1, 'b': 0}

if all(d.values()):

print('All true')

else:

print('Some false')

```


82. 生成器示例

```python

def countdown(n):

while n > 0:

yield n

n -= 1

for i in countdown(5):

print(i)

```


83. 简单的装饰器计时

```python

import time

def timer(func):

def wrapper():

start = time.time()

result = func()

end = time.time()

print(f"运行时间:{end - start}秒")

return result

return wrapper

```


84. 使用namedtuple

```python

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

p = Point(1, 2)

print(p.x, p.y)

```


85. 使用deque实现队列

```python

from collections import deque

queue = deque()

queue.append(1)

print(queue.popleft())

```


86. JSON处理

```python

import json

data = '{"name": "Alice", "age": 25}'

parsed = json.loads(data)

print(parsed['name'])

```


87. 解析日期

```python

from datetime import datetime

now = datetime.now()

print(now.strftime("%Y-%m-%d %H:%M:%S"))

```


88. 读取配置文件(ini)

```python

import configparser

config = configparser.ConfigParser()

# config.read('config.ini')

# print(config['section']['key'])

```


89. 使用异常捕获

```python

try:

result = 10 / 0

except ZeroDivisionError:

print("除零错误")

finally:

print("执行结束")

```


90. 复制对象(浅复制)

```python

import copy

lst1 = [1, 2]

lst2 = copy.copy(lst1)

```


91. 深复制

```python

deep_lst = copy.deepcopy(lst1)

```


92. 正则表达式

```python

import re

match = re.match(r'(\d+)', '123abc')

print(match.group(1))

```


93. 使用with打开文件

```python

with open('file.txt', 'w') as f:

f.write('Hello World')

```


94. 列表中的条件筛选

```python

evens = [x for x in range(10) if x % 2 == 0]

print(evens)

```


95. 计算平均值

```python

nums = [10, 20, 30]

avg = sum(nums) / len(nums)

print(avg)

```


96. 获取文件路径(os.path)

```python

import os

print(os.path.basename('/path/to/file.txt'))

```


97. 使用enumerate

```python

for index, value in enumerate(['a', 'b', 'c']):

print(index, value)

```


98. 线程示例(简单)

```python

import threading

def task():

print("Thread running")

thread = threading.Thread(target=task)

thread.start()

```


99. 定时执行(time.sleep)

```python

import time

print("Start")

time.sleep(2)

print("End after 2 seconds")

```


100. 简单类的__repr__方法

```python

class Person:

def __init__(self, name):

self.name = name

def __repr__(self):

return f"Person({self.name})"

```


以上示例涵盖了Python的基本数据类型、控制结构、函数定义与调用、常用数据结构、面向对象编程(类和继承)以及一些实用技巧。希望能帮助大家全面理解Python!

相关文章

python 示例代码

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

PYTHON学习导图与实例代码100条

以下是Python 学习导图涵盖从基础到进阶 的核心知识点,帮助你系统化学习 Python:Python 学习路线1 Python 基础语法1.1变量与数据类型- 数字(`int`, `float`,...

爆肝整理!247个Python有趣实例(附 PDF)复制即用!

学 Python 最崩溃的瞬间莫过于 —— 语法背得滚瓜烂熟,一写代码就卡壳 知道知识点却不会用,复杂需求面前秒变 “代码难民” 想找实战项目练手,不是案例太老就是代码残缺不全别慌!今天直接甩出压箱底...

值得学习练手的100个Python项目(附代码),真的太实用了

Python丰富的开发生态是它的一大优势,各种第三方库、框架和代码,都是前人造好的“轮子”,能够完成很多操作,让你的开发事半功倍。在科技飞速发展的当今时代,Python 以其简洁、高效和强大的功能,成...

新手必看!30 个 Python 核心函数详解,手把手教你玩转编程

Python 中 30 个核心函数及其含义、代码示例、注释和应用场景:print():用于输出文本或变量的值到控制台。message = "Hello, World!" # 定义一个...