python入门之for循环和while循环

本文详细介绍了Python中的循环结构,包括for循环与while循环的基本用法、嵌套循环的应用及9x9乘法表的实现。此外,还讲解了break和continue语句在循环控制中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、for循环举例

复制以下代码运行,即可理解代码。

str1 = 'python'
for i in str1:
    if i == 'n':
        print(i, end='')
    else:
        print(i)

print()
print('----------------')  # 区分上下部分

for i in str1:
    if i == 'h':
        print('遇见h, 结束整个循环且没有打印h')
        break
    print(i)

print('----------------')  # 区分上下部分

for i in str1:
    if i == 'h':
        print('遇见h, 结束这次循环, 即不打印h')
        continue
    print(i)

二、while循环

# basic cycle
i = 0
while i < 5:
    print("dear, I'm sorry")
    i += 1
print('forgive you only this time')

# summation
i = 1
s = 0
while i <= 100:
    s += i
    i += 1
print(s)

# summation -- while and if
i = 1
s = 0
while i <= 100:
    if i % 2 == 0:
        s += i
    i += 1
print(s)

三、while嵌套循环

i = j = 0
while i < 5:
    j = 0
    while j < 5:
        print('*', end='')  # at the end of 'print()', the default is '\n'
        j += 1
    print()  # when a row go to end, we need to enter
    i += 1

i = j = 0
while i < 5:
    j = 0
    while j <= i:
        print('*', end='')  # at the end of 'print()', the default is '\n'
        j += 1
    print()  # when a row go to end, we need to enter
    i += 1

四、while嵌套循环打印9x9乘法表

i = j = 1
while i <= 9:
    # 一行表达式开始
    j = 1
    while j <= i:
        print(f'{j} * {i} = {i*j}', end='\t')
        j += 1
    # 一行表达式结束
    print()
    i += 1

五、break和continue语句

# the usages of break
i = 1
while i <= 5:
    if i == 4:
        print('I was full')
        break
    print(f'{i} apples had been ate')
    i += 1

print(end='\n')  # enter,looks clearly

# the usages of continue
i = 1
while i <= 5:
    if i == 3:
        print('I have eaten a big worm,this apple will not be eaten')
        i += 1
        continue  # this "continue" is not necessary
    print(f'{i} apples had been ate')
    i += 1

print(end='\n')  # enter,looks clearly

# another method
i = 1
while i <= 5:
    if i != 3:
        print(f'{i} apples had been ate')
        i += 1
    else:
        print('I have eaten a big worm,this apple will not be eaten')
        i += 1

print(end='\n')  # enter,looks clearly

# another method
i = 1
while i <= 5:
    if i == 3:
        print('I have eaten a big worm,this apple will not be eaten')
        i += 1
# this "continue" is not necessary
    print(f'{i} apples had been ate')
    i += 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

二十四桥_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值