Python 语法简洁,适合入门编程。这篇笔记整理基础数据类型与控制流程。
age = 18 # int
price = 9.9 # float
name = "Python" # str
ok = True # bool
nothing = None # NoneType
nums = [1, 2, 3] # 列表,可修改
point = (1, 2) # 元组,不可修改
user = {"name": "Tom"} # 字典
tags = {"a", "b"} # 集合,元素不重复
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
Python 通过缩进表示代码块,一般使用 4 个空格。
for i in range(3):
print(i)
n = 0
while n < 3:
n += 1
def greet(name, greeting="你好"):
return f"{greeting},{name}"
print(greet("小明"))
squares = [x * x for x in range(5)]
# [0, 1, 4, 9, 16]
with open("a.txt", "w", encoding="utf-8") as f:
f.write("hello")
使用 with 可以保证文件在使用后被正确关闭。