学习Python3是编程之旅的绝佳起点,因为它语法简洁,功能强大,且广泛应用于数据科学、Web开发、自动化脚本等领域。以下是Python3的基础语法代码演示,帮助你迈出Python编程的第一步。
python3 --version
以检查安装是否成功。python3
或 python
(取决于系统配置)进入Python交互模式,或编写脚本文件(以 .py
结尾)并执行。# 变量赋值
a = 10
b = 5.5
c = "Hello, World!"
d = True
# 打印变量
print(a) # 输出: 10
print(type(a)) # 输出:
print(b) # 输出: 5.5
print(type(b)) # 输出:
print(c) # 输出: Hello, World!
print(type(c)) # 输出:
print(d) # 输出: True
print(type(d)) # 输出:
# 算术运算符
x = 10
y = 3
print(x + y) # 输出: 13
print(x - y) # 输出: 7
print(x * y) # 输出: 30
print(x / y) # 输出: 3.3333333333333335
print(x % y) # 输出: 1
print(x ** 2) # 输出: 100
# 赋值运算符
x += 5 # 等同于 x = x + 5
print(x) # 输出: 15
# 比较运算符
print(x > y) # 输出: True
print(x < y) # 输出: False
print(x == y) # 输出: False
print(x != y) # 输出: True
age = 20
if age >= 18:
print("成人")
else:
print("未成年")
# 多重条件
if age < 13:
print("儿童")
elif 13 <= age < 18:
print("青少年")
else:
print("成人")
# for 循环
for i in range(5): # 相当于 0 到 4
print(i)
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 定义函数
def greet(name):
return f"Hello, {name}!"
# 调用函数
print(greet("Alice")) # 输出: Hello, Alice!
# 带默认参数的函数
def greet_with_default(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet_with_default("Bob")) # 输出: Hello, Bob!
print(greet_with_default("Charlie", "Hi")) # 输出: Hi, Charlie!
# 列表
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits) # 输出: ['apple', 'banana', 'cherry', 'date']
# 元组
coordinates = (10, 20)
# coordinates.append(30) # 报错: 'tuple' object has no attribute 'append'
print(coordinates) # 输出: (10, 20)
# 字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person["name"]) # 输出: Alice
person["age"] = 31
print(person) # 输出: {'name': 'Alice', 'age': 31, 'city': 'New York'}
# 集合
fruits_set = {"apple", "banana", "cherry"}
fruits_set.add("date")
print(fruits_set) # 输出: {'apple', 'banana', 'cherry', 'date'}(集合无序)
# 导入标准库模块
import math
print(math.sqrt(16)) # 输出: 4.0
# 导入特定函数
from math import pow
print(pow(2, 3)) # 输出: 8
# 导入并重命名
import numpy as np
print(np.array([1, 2, 3])) # 输出: [1 2 3]
# 写文件
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
# 读文件
with open("example.txt", "r") as file:
content = file.read()
print(content) # 输出: Hello, World!
# 定义类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# 创建对象
alice = Person("Alice", 30)
print(alice.greet()) # 输出: Hello, my name is Alice and I am 30 years old.
以上内容涵盖了Python3的基础语法,包括变量、数据类型、运算符、条件语句、循环、函数、列表、元组、字典、集合、模块导入、文件操作以及面向对象编程的基本概念。希望这些内容能帮助你快速入门Python编程!