您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python基本语法举例分析
Python作为当前最流行的编程语言之一,以其简洁优雅的语法和强大的功能受到广泛欢迎。本文将通过具体示例分析Python的核心语法结构,帮助读者快速掌握Python编程基础。
## 一、变量与数据类型
### 1.1 变量定义
Python是动态类型语言,变量无需声明类型:
```python
name = "Alice" # 字符串
age = 25 # 整数
height = 1.68 # 浮点数
is_student = True # 布尔值
类型 | 示例 | 说明 |
---|---|---|
int | x = 42 |
整数 |
float | pi = 3.14159 |
浮点数 |
str | s = "Python" |
字符串 |
bool | flag = True |
布尔值 |
list | lst = [1, 2, 3] |
可变序列 |
tuple | tup = (1, 2) |
不可变序列 |
dict | d = {'a': 1} |
键值对映射 |
set | s = {1, 2, 3} |
无序不重复元素集 |
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.333...
print(10 // 3) # 3 (整除)
print(10 % 3) # 1 (取模)
print(10 ** 3) # 1000 (幂运算)
print(5 > 3) # True
print(5 == 3) # False
print(5 != 3) # True
print(5 >= 5) # True
print(True and False) # False
print(True or False) # True
print(not True) # False
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好") # 输出此项
else:
print("继续努力")
count = 0
while count < 5:
print(count)
count += 1
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for i in range(10):
if i == 3:
continue # 跳过本次循环
if i == 7:
break # 终止循环
print(i)
def greet(name):
"""返回问候语(文档字符串)"""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# 默认参数
def power(x, n=2):
return x ** n
# 可变参数
def sum_all(*args):
return sum(args)
# 关键字参数
def person_info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.insert(1, 5) # [1, 5, 2, 3, 4]
numbers.remove(2) # [1, 5, 3, 4]
print(numbers[1:3]) # 切片 [5, 3]
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
person["city"] = "Beijing" # 添加键值对
for key, value in person.items():
print(f"{key}: {value}")
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1, 2}
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello, Python!\n")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
print(content)
import csv
# 写入CSV
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
# 读取CSV
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"发生错误: {e}")
else:
print("计算成功")
finally:
print("执行完毕")
class Dog:
# 类属性
species = "Canis familiaris"
# 初始化方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def bark(self):
return f"{self.name} says woof!"
# 创建实例
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
class Bulldog(Dog): # 继承Dog类
def run(self, speed):
return f"{self.name} runs at {speed}km/h"
bulldog = Bulldog("Max", 2)
print(bulldog.bark()) # 继承的方法
print(bulldog.run(10)) # 子类特有方法
# 导入整个模块
import math
print(math.sqrt(16))
# 导入特定函数
from random import randint
print(randint(1, 100))
# 别名导入
import numpy as np
创建mymodule.py
:
def greeting(name):
print(f"Hello, {name}")
在其他文件中使用:
import mymodule
mymodule.greeting("Alice")
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
gen = (x**2 for x in range(10))
for num in gen:
print(num)
def my_decorator(func):
def wrapper():
print("装饰器前置操作")
func()
print("装饰器后置操作")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
本文通过大量实例展示了Python的核心语法特性。Python的简洁语法使得开发者可以用更少的代码表达复杂的逻辑,这也是其广受欢迎的重要原因。建议读者在实际编码中多加练习,逐步掌握Python编程的精髓。 “`
(全文约1850字)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。