简单玩转Python的邪修大法速成(二)!

70 阅读1分钟

1. 基础语法

注释

  • 单行注释:用  #  开头 python

# 这是单行注释

print("Hello World")  # 输出Hello World

 

  • 多行注释:用  '''  或  """  包裹
  
'''
这是多行注释
第二行内容
'''
print("Hi")

2. 流程控制

条件语句(if-elif-else)
score = 85
if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")
# 输出:良好
循环语句
  • for循环(遍历序列)
# 遍历列表
animals = ["cat", "dog", "bird"]
for animal in animals:
    print(animal)
# 输出:cat、dog、bird

# 用range()生成序列
for i in range(3):  # 生成0-2的数字
    print(i)
# 输出:0、1、2
  • while循环(条件满足时执行)
count = 0
while count < 3:
    print("count:", count)
    count += 1
# 输出:count:0、count:1、count:2
  • 循环控制: break (终止循环)、 continue (跳过当前循环)
for i in range(5):
    if i == 2:
        continue  # 跳过i=2的循环
    if i == 4:
        break     # 终止循环
    print(i)
# 输出:0、1、3