🐍 Python基础入门:变量、数据类型与运算符完全指南

🐍 Python基础入门:变量、数据类型与运算符完全指南

本文是「Python零基础入门」系列的第一篇,适合没有任何编程经验的初学者。

什么是Python?

Python是一种简洁优雅的编程语言,由Guido van Rossum于1991年创造。它以易读易写的语法著称,被誉为"可执行的伪代码"。无论你是想做数据分析、Web开发、人工智能还是自动化脚本,Python都是绝佳的起点。

一、变量:数据的"标签"

变量是存储数据的容器。在Python中,给变量赋值非常简单:

# 变量赋值
name = "小明"      # 字符串
age = 25           # 整数
height = 1.75      # 浮点数
is_student = True  # 布尔值

print(name)        # 输出:小明
print(age + 1)     # 输出:26

变量命名规则

可以:使用字母、数字、下划线,但不能以数字开头

user_name = "Alice"
_score = 100
MAX_SIZE = 1024   # 常量习惯用大写

不可以

2name = "Tom"     # 不能以数字开头
my-name = "Tom"   # 不能用连字符
class = "A"       # 不能用关键字

Python关键字(保留字)

以下单词有特殊含义,不能用作变量名:False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield

二、数据类型:Python中的"物种"

Python是动态类型语言,不需要预先声明变量类型。

1. 数字类型

# 整数(int)
count = 100
big_number = 1_000_000_000  # 可以用下划线分隔,更易读

# 浮点数(float)
price = 19.99
pi = 3.14159

# 复数(complex,较少用到)
z = 3 + 4j

2. 字符串(str)

字符串是文本数据,用单引号、双引号或三引号包裹:

# 创建字符串
s1 = 'Hello'
s2 = "World"
s3 = '''这是一个
多行字符串'''

# 字符串常用操作
text = "Python编程"
print(len(text))          # 长度:8
print(text[0])            # 索引:P
print(text[-1])           # 倒数第一个:程
print(text[0:6])          # 切片:Python
print("Py" in text)       # 判断包含:True

# 字符串方法
print("  hello  ".strip())        # 去空格:"hello"
print("HELLO".lower())            # 转小写:"hello"
print("hello world".title())      # 首字母大写:"Hello World"
print(",".join(["a", "b", "c"]))   # 连接:"a,b,c"

3. 布尔值(bool)

flag = True   # 真
flag = False  # 假

# 比较运算产生布尔值
print(5 > 3)   # True
print(5 == 3)  # False

4. 空值(None)

result = None  # 表示"什么都没有"

5. 查看数据类型

print(type(42))       # <class 'int'>
print(type("hello"))  # <class 'str'>
print(type(3.14))     # <class 'float'>

三、运算符:数据的"加工工具"

1. 算术运算符

a, b = 10, 3

print(a + b)   # 加法:13
print(a - b)   # 减法:7
print(a * b)   # 乘法:30
print(a / b)   # 除法:3.333...
print(a // b)  # 整除:3(向下取整)
print(a % b)   # 取余:1
print(a ** b)  # 幂运算:1000 (10的3次方)

2. 比较运算符

x, y = 5, 10

print(x == y)  # 等于:False
print(x != y)  # 不等于:True
print(x > y)   # 大于:False
print(x < y)   # 小于:True
print(x >= y)  # 大于等于:False
print(x <= y)  # 小于等于:True

3. 赋值运算符

n = 10

n += 5   # 等价于 n = n + 5,n现在是15
n -= 3   # 等价于 n = n - 3,n现在是12
n *= 2   # 等价于 n = n * 2,n现在是24
n /= 4   # 等价于 n = n / 4,n现在是6.0

4. 逻辑运算符

p, q = True, False

print(p and q)  # 与:False(都真才真)
print(p or q)   # 或:True(一真即真)
print(not p)    # 非:False

# 实际应用
age = 25
income = 5000
can_loan = (age >= 18) and (income >= 3000)
print(can_loan)  # True

5. 成员运算符

fruits = ["苹果", "香蕉", "橙子"]

print("苹果" in fruits)      # True
print("西瓜" not in fruits)  # True

6. 身份运算符

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)      # True(同一对象)
print(a is c)      # False(值相同,但不同对象)
print(a == c)      # True(值相等)

四、类型转换

# 字符串转数字
num_str = "42"
num = int(num_str)      # 42
price_str = "3.14"
price = float(price_str) # 3.14

# 数字转字符串
s = str(100)            # "100"

# 其他转换
print(bool(1))          # True
print(bool(0))          # False
print(bool(""))         # False(空字符串)
print(bool("hello"))    # True

五、输入与输出

# 输出
print("Hello, World!")
print("姓名:", "小明", "年龄:", 20, sep=" | ")

# 格式化输出(f-string,推荐)
name = "Alice"
score = 95.5
print(f"{name}的分数是{score:.1f}分")  # Alice的分数是95.5分

# 输入(用户从键盘输入)
name = input("请输入你的名字:")
age = int(input("请输入你的年龄:"))  # 输入需要转换类型
print(f"你好,{name}!你明年就{age + 1}岁了。")

总结

概念要点
变量 存储数据的标签,命名要有意义
数据类型 int, float, str, bool, None
算术运算 + - * / // % **
比较运算 == != > < >= <=
逻辑运算 and or not
类型转换 int(), float(), str(), bool()

掌握了这些基础,你已经迈出了Python学习的第一步!接下来可以继续学习控制流(条件判断和循环),让你的程序"聪明"起来。


💡 小练习:试着写一段程序,让用户输入两个数字,然后输出它们的和、差、积、商。

下一篇预告:Python控制流:条件语句与循环完全指南

posted @ 2026-03-22 18:47  码小小小仙  阅读(18)  评论(0)    收藏  举报