Python 基本语法实例练习

以下是一些 Python 语法的实例练习:

1. 变量和数据类型

# 整数
a = 10
print(a)

# 浮点数
b = 3.14
print(b)

# 字符串
c = "Hello, World!"
print(c)

# 布尔值
d = True
print(d)

# 列表
e = [1, 2, 3, 4, 5]
print(e)

# 元组
f = (6, 7, 8, 9, 10)
print(f)

# 字典
g = {'name': 'Alice', 'age': 30}
print(g)

2. 控制流语句

# if 语句
x = 10
if x > 5:
    print("x is greater than 5")

# if-else 语句
y = 3
if y > 5:
    print("y is greater than 5")
else:
    print("y is not greater than 5")

# for 循环
for i in range(5):
    print(i)

# while 循环
count = 0
while count < 5:
    print(count)
    count += 1

3. 函数

# 定义函数
def add_numbers(a, b):
    return a + b

print(add_numbers(3, 4))

# 匿名函数(lambda 表达式)
square = lambda x: x**2
print(square(5))

4. 列表推导式

# 生成一个包含 1 到 10 的平方的列表
squares = [i**2 for i in range(1, 11)]
print(squares)

5. 类和对象

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

p = Person("Bob", 25)
p.introduce()
  • 天道酬勤

    与人方便,与己方便。

    Related Posts

    python练习3

    小M在工作时遇到了一个问题,他需要将用户输入的不带千分位逗号的数字字符串转换为带千分位逗号的格式,并且保留小数部分。小M还发现,有时候输入的数字字符串前面会有无用的 0,这些也需要精简掉。请你帮助小M编写程序,完成这个任务。 测试样例样例1: 输入:s = “1294512.12412”输出:’1,294,512.12412′ 样例2: 输入:s = “0000123456789.99”输出:’123,456,789.99′ 样例3: 输入:s = “987654321”输出:’987,654,321′ ②

    Python陪练2–二维数组

    小R正在计划一次从地点A到地点B的徒步旅行,总路程需要 N 天。为了在旅途中保持充足的能量,小R每天必须消耗1份食物。幸运的是,小R在路途中每天都会经过一个补给站,可以先购买完食物后再消耗今天的1份食物。然而,每个补给站的食物每份的价格可能不同,并且小R在购买完食物后最多只能同时携带 K 份食物。 现在,小R希望在保证每天食物消耗的前提下,以最小的花费完成这次徒步旅行。你能帮助小R计算出最低的花费是多少吗? **输入 ** n 总路程需要的天数k 小R最多能同时携带食物的份数data[i] 第i天补给站每份食物的价格**输出 ** 返回完成这次徒步旅行的最小花费**约束条件 ** 1 < n,k < 10001 < data[i] < 10000测试样例样例1: 输入:n = 5 ,k = 2…

    You Missed

    四大顶尖AI模型

    线上数字人体验地址

    DeepSeek在线使用平台汇总

    AI工具集

    分享目前最全AI工具合集

    python练习3