python 基础语法

Pyth 打印输出

print("Hello, Python!")

2. 变量赋值

x = 10
name = "John"

3. 数据类型

Python 有多种基本数据类型,包括整数、浮点数、字符串、列表(List)、元组(Tuple)、字典(Dictionary)和集合(Set)。

number = 42          # 整数
float_number = 3.14   # 浮点数
greeting = "Hello"    # 字符串
names = ["John", "Jane", "Foo"]  # 列表
person = ("John", 30)  # 元组
ages = {"John": 30, "Jane": 25}  # 字典
unique_numbers = {1, 2, 3, 3, 4}  # 集合

4. 条件语句

age = 20
if age > 18:
    print("You are an adult.")
elif age == 18:
    print("You are an adult.")
else:
    print("You are a minor.")

5. 循环

Python 中的循环包括 for 循环和 while 循环。

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

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

6. 列表推导式

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

7. 函数定义

def greet(name):
    print(f"Hello, {name}!")

greet("John")

8. 类和对象

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

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

person = Person("John", 30)
person.greet()

9. 模块和包

# 导入模块
import math

# 从模块中导入特定函数
from datetime import datetime

10. 文件操作

# 读取文件
with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

# 写入文件
with open('new_file.txt', 'w') as file:
    file.write("Hello, World!")

11. 异常处理

try:
    # 尝试执行的代码
    result = 10 / 0
except ZeroDivisionError:
    # 如果发生了 ZeroDivisionError,则执行这里的代码
    print("Cannot divide by zero.")

12. 装饰器

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

Python 的语法简洁而强大,非常适合快速开发和原型制作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jet-W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值