【Python】Python基础知识(二):if语句,while循环,for循环

上篇:Python基础知识(一):数据类型,格式化输出,运算符


目录

if 语句

if ... else 

if ... elif ... else

if 嵌套

三目运算符

while循环

break和continue

while循环嵌套

for 循环

break

continue

while ... else

for ... else


if 语句

if True:
    print("执行")

注意:if 语句的条件后添加冒号(:

age = int(input("请输入你的年龄:"))

if age >= 18:
    print("你已经成年")

if ... else 

注意:else 后面需要添加冒号(:)

age = int(input("请输入你的年龄:"))

if age >= 18:
    print("你已经成年")
else:
    print("你未成年")

if ... elif ... else

if age < 18:
    print("童工")
elif age <= 60:
    print("合法工作年龄")
else:
    print("退休")

if 嵌套

age = int(input("请输入你的年龄:"))

if age < 18:
    print("童工")
elif age <= 60:
    print("合法工作年龄")
    wantWork = int(input("你是否想工作了吗"))
    if wantWork == 1:
        print("想工作了")
    else:
        print("不想工作")
else:
    print("退休")

三目运算符

语法

条件成立的表达式  if  条件  else  条件不成立的表达式

a = 1
b = 2
c = a if a > b else b
print(c)

 

while循环

i = 0
while i < 5:
    print("我要睡觉了zzz~")
    i += 1

效果

1-100累加

i = 1
res = 0
while i <= 100:
    res += i
    i += 1
print(res)

效果

1-100偶数累加

i = 1
res = 0
while i <= 100:
    if i % 2 == 0:
        res += i
    i += 1
print(res)

i = 0
res = 0
while i <= 100:
    res += i
    i += 2
print(res)

效果

break和continue

break       终止循环

continue  退出本次循环,继续下次循环

break

i = 1
while i <= 5:
    if i == 4:
        print("太累了,不做了")
        break
    print(f"做{i}个俯卧撑")
    i += 1

效果

continue

i = 0
while i < 5:
    i += 1
    print(f"做{i}个俯卧撑")
    if i == 3:
        print("休息一下,等下再做")
        continue

效果

while循环嵌套

i = 0
while i < 3:
    i += 1
    print(f"第{i}天")
    j = 0
    while j < 3:
        j += 1
        print(f"做{j}个俯卧撑")

效果

for 循环

str1 = "hello"
for i in str1:
    print(i)

效果

break

str1 = "hello"
for i in str1:
    if i == 'l':
        break
    print(i)

效果

continue

str1 = "hello"
for i in str1:
    if i == 'l':
        continue
    print(i)

效果

 

while ... else

else下方缩进代码指的是当循环正常结束之后要执行的代码

while循环时遇到break结束时,不会执行else代码

正常情况

i = 1
while i <= 5:
    print(f"做{i}个俯卧撑")
    i += 1
else:
    print("给你个奖励")

效果

添加continue情况

i = 0
while i < 5:
    i += 1
    print(f"做{i}个俯卧撑")
    if i == 3:
        print("休息一下,等下再做")
        continue
else:
    print("给你个奖励")

效果

添加break情况

i = 1
while i <= 5:
    if i == 4:
        print("太累了,不做了")
        break
    print(f"做{i}个俯卧撑")
    i += 1
else:
    print("给你个奖励")

效果

 

for ... else

与while ... else情况相同,遇到break结束时,不会执行else代码

 


下篇:Python基础知识(三):字符串

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GreAmbWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值