Python从0到1之流程控制

条件语句

if

if True:
    print("hello world") # hello world

if else

if 1>2:
    print("1大于2")
else:
    print("1小于2") # 1小于2

if elif else

# 年龄小于18童工,年龄18-60之间,合法工作年龄,年龄大于60,退休年龄
age = 25
if age < 18:
    print(f"年龄{age},是童工")
elif age<=60 and age >=18:
    print(f"年龄{age},合法工作年龄")
else:
    print(f"年龄{age},退休年龄") # 年龄25,合法工作年龄

if 嵌套

坐公交,有钱可上车,没钱走路,有座可以坐,没座站着
money = 1
seat = 1
if money == 1:
    print("土豪,请上车")
    if seat == 1:
        print("请入座")
    else:
        print("请站着")    
else:
    print("无法上车") # 土豪,请上车\n请入座

三元表达式

语法:条件成立的表达式 if 条件 else 条件不成立的表达式

a = 1
b = 2
c = a + b if a < b else a - b
print(c) # 3

石头剪刀布

玩家输入,电脑随机,判断输赢

import random
player = int(input("请输入出拳序号0石头1剪刀2布:"))
computer = random.randint(0,2)
if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player == 2 and computer == 0):
    print("玩家获胜")
elif player == computer:
    print("平局,再来一局")
else:
    print("电脑获胜")  # 玩家获胜

循环语句

while

while

i = 0
while i < 3:
    print(i)
    i += 1  # 0\n1\n2

while else

else是循环正常结束执行的代码

i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("循环正常结束")  0\n1\n2\n循环正常结束

while continue

continue 退出当前循环,执行下一次循环

i = 0
while i < 3:
    i += 1
    if i == 2:
        continue
    print(i) # 1\n3

while break

break 退出整个循环

i = 0
while i < 3:
    i += 1
    if i == 2:
        break
    print(i) # 1

while continue else

else是循环结束执行的代码,continue结束当前循环,循环能正常结束,else后代码会执行

i = 0
while i < 3:
    i += 1
    if i == 2:
        continue
    print(i) 
else:
    print("循环正常结束,else执行") # 1\n3 循环正常结束,else执行

while break else

else是循环结束执行的代码,break结束整个循环,循环没有正常结束,else后代码不会执行

i = 0
while i < 3:
    i += 1
    if i == 2:
        break
    print(i) # 1
else:
    print("循环没正常结束,else不执行") # 1

while 嵌套

i = 0
while i < 3:
    j = 0
    while j < 3:
        print("学习")
        j+=1
    print("好学生")
    i+=1 # 学习\n学习\n学习\n好学生*3

for

for

for i in "abc":
    print(i) # a\nb\nc

for else

else循环正常结束执行的代码

for i in "abc":
    print(i) 
else:
    print("循环正常结束,执行else") # a\nb\nc\n循环正常结束,执行else

for continue

continue结束当前循环,执行下一次循环

for i in "abc":
    if i == "b":
        continue
    print(i) # a\nc

for break

break 结束整个循环

for i in "abc":
    if i == "b":
        break
    print(i) # a

for continue else

else是循环正常结束执行的语句,continue结束当前循环,循环能正常结束,执行else语句

for i in "abc":
    if i == "b":
        continue
    print(i)
else:
    print("循环正常结束,执行else语句") # a\nc\n循环正常结束,执行else语句

for break else

else是循环正常结束执行的语句,break结束整个循环,循环没有正常结束,不执行else语句

for i in "abc":
    if i == "b":
        break
    print(i)
else:
    print("循环未正常结束,不执行else语句") # a

for 嵌套

for i in range(3):
    for j in range(3):
        print("学习")
    print("好学生") # 学习\n学习\n学习\n好学生*3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值