python基础语法代码示例:

变量:

变量包括字符串、整数、浮点数、布尔值 动态类型,无需声明:

name = "Alice"      #字符串

age = 25                #整数

heigth = 1.68         #浮点数

is_student = True  #布尔值

#多重赋值

x,y,z = 1,2,3

a = b = c =0 

数据类型:

数据类型包括数字类型、序列类型、集合类型、布尔类型、None类型

# 数字类型

int_num = 42

float_num = 3.14

complex_num = 2 + 3j

# 序列类型

text = "Hello"          #字符串

my_list = [1,2,3]      #列表(可变)

my_tuple = (1,2,3)  #元组(不可变)

#集合类型

my_set = {1,2,3}            #集合(无序不重复)

my_dict = {"a":1,"b":2}   #字典(键值对)

#布尔类型

is_true = True

is_false = False

#None类型

nothing = None

#类型转换

int("123")       #字符串转整数

str(456)         #整数转字符串

float("3.14")   #转浮点数

运算符:

运算符包括算术运算符、比较运算符、逻辑与算符、赋值运算符、成员运算符

#算术运算符

print(10 + 3)   #加法

print(10 - 3)    #减法

print(10 * 3)    #乘法

print(10 / 3)    #除法

print(10 // 3)   #整除

print(10 % 3)  #取余

print(10 ** 3)   #幂运算

#比较运算符 

print(5 > 3)    #True

print(5 == 3)  #True

print(5 != 3)   #True

#逻辑运算符

print(True and False)   #False

print(True or False)      #True

print(not True)              #False

#赋值运算符

x = 5

x += 3   # x = x + 2

x *= 2    # x = x * 2

#成员运算符

print(2 in [1,2,3])        #True

print(4 not in [1,2,3])  #True

条件判断:

#if-elif-else

score = 85

if score >= 90:

        print("优秀")

elif score >= 80:

        print("良好")

elif score >= 80:

        print("及格")

else:

        print("不及格")

#三元运算符

age = 18

status = "成年" if age >= 18 else "未成年"

#嵌套条件

x = 10

if x > 0:

        if x % 2 ==0:

                print("正偶数")

循环:

循环包括for循环遍历列表、for循环配合range、while循环、break和continue、循环else子句

#for循环遍历列表

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

for fruit in fruits:

        print(fruit)

#for循环配合range

for i in range(5):            #0,1,2,3,4

        print(i)

for i in range(2,8,2):      #2,4,6

        print(i)

#while循环

count = 0

while count < 5:

        print(count)

        count += 1

#break和continue

for i in range(10):

        if i == 3:

                continue   #跳过3

        if i == 7:

                break        #停止循环

        print(i)

#循环else子句

for i in range(3):

        print(i)

else:

        print("循环正常结束")        #未被break时会执行

列表:

#创建列表

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

mixed = [1,"hello",3.14,True]

empty = []

#访问元素

print(numbers[0])          #第一个:1

print(numbers[-1])         #最后一个:5

print(numbers[1:3])        #切片:[2,3]

#修改列表

numbers.append(6)              #添加元素

numbers.insert(0,0)            # 指定位置插入

numbers.extend([]7,8)         #扩展列表

numbers.remove(3)                #删除指定值

popped = numbers.pop()        #删除并返回最后一个

numbers.sort()                        #排序

numbers.reverse()                  #反转

#列表推导式

squares = [x**2 for x in range(5)]        #[0,1,4,9,16]

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

#常用操作

length = len(numbers)           #长度

index = numbers.index(5)      #  查找索引

count = numbers.count(2)      # 计数

字典:

# 创建字典
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# 访问值
print(person["name"])        # Alice
print(person.get("age"))     # 25
print(person.get("country", "未知"))  # 不存在时返回默认值

# 修改和添加
person["age"] = 26           # 修改
person["email"] = "alice@example.com"  # 添加

# 删除
del person["city"]
age = person.pop("age")      # 删除并返回值

# 遍历字典
for key in person:
    print(key, person[key])

for key, value in person.items():
    print(f"{key}: {value}")

for value in person.values():
    print(value)

# 字典推导式
squares_dict = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}

# 常用方法
keys = person.keys()         # 所有键
values = person.values()     # 所有值
items = person.items()       # 所有键值对
person.clear()               # 清空字典

函数:

# 基本函数定义
def greet(name):
    return f"Hello, {name}!"

result = greet("Bob")
print(result)  # Hello, Bob!

# 默认参数
def power(base, exponent=2):
    return base ** exponent

print(power(3))      # 9
print(power(2, 3))   # 8

# 关键字参数
def introduce(name, age, city):
    print(f"{name}, {age}, {city}")

introduce(age=25, name="Alice", city="Paris")

# 可变参数
def sum_all(*args):          # 元组形式
    return sum(args)

def print_info(**kwargs):    # 字典形式
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 返回值
def calculate(x, y):
    return x + y, x - y, x * y  # 返回多个值(元组)

add, sub, mul = calculate(10, 5)

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

# 与列表推导结合使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))

# 作用域
global_var = 10

def my_function():
    local_var = 5
    global global_var
    global_var = 20  # 修改全局变量

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐