Python学习日记---循环基础学习(附有练习代码)

Python学习日记—字符串基础学习
此文章基于B站视频(/Python从入门到精通https://www.bilibili.com/video/av59562092/?p=204)学习所写:
一、while循环

#  while循环测试
i = 0
while i <= 4:
    print('你真帅!!!')
    i +=1
print('有眼光!!!')
#  while循环求1-100之和
i = 1
sum = 0
while i <= 100:
    sum += i
    i += 1
print(sum)
#  while循环求1-100之间偶数和:
#  方法一:
i = 0
SUM = 0
while i <= 100:
    sum += i
    i += 2
print(SUM)

#  方法二:
i = 1
SUM = 0
while i <= 100:
    if i % 2 == 0:
        SUM += i
    i +=1
print(SUM)
#  while循环嵌套
i = 1
j = 1
while i <= 3:
#    j = 1
    while j <= 3:
        print('老师,我错了!!!')
        j += 1
    print('抄作业去!!!')
    i += 1
#  while循环打印正方形:
j = 0
while j < 5:
    i = 0
    while i < 5:
        print('*',end=' ')
        i += 1
    print()
    j += 1 
#  while循环打印三角形:
j = 0
while j < 5:
    i = 0
    while i <= j:
        print('*', end=' ')
        i += 1
    print()
    j += 1
#  while循环打印九九乘法表:
j = 1
while j <= 9:
    i = 1
    while i <= j:
        print(f'{i}*{j}={i*j}', end=' ')
        i += 1
    print()
    j += 1

二、for循环

#  for循环快速体验:
str1 = 'itheima'
for i in str1:
    print(i)
#  break控制for循环:
str1 = 'itheoma'
for i in str1:
    if i == 'e':
        print('遇到e不打印。')
        break
    print(i)

#  continue控制for循环:
str1 = 'itheoma'
for i in str1:
    if i == 'e':
        print('遇到e不打印。')
        continue
    print(i)

三、break and continue

#  break
i = 1
while i <= 5:
    if i == 4:
        print('饱了')
        break
    print(f'吃了第{i}个馒头')
    i += 1

#  continue
i = 1
while i <= 5:
    if i == 4:
        print('坏了,不能吃。')
        i += 1
        continue
#  使用continue,在continue前要修改计数器,否则会陷入死循环
    print(f'吃了第{i}个馒头')
    i += 1

四、while…else 和for…else:

#  while...else
i = 1
while i <= 5:
    print('老师我错了!!!')
    i += 1
else:
    print('老师原谅我了!!!')

#  while...else之break:
i = 1
while i <= 5:
    if i ==3:
        print('态度不端正!')
        break
    print('老师我错了!!!')
    i += 1
else:
    print('老师原谅我了!!!')

#  while...else之continue:
i = 1
while i <= 5:
    if i ==3:
        print('态度不端正!')
        i += 1
        continue
    print('老师我错了!!!')
    i += 1
else:
    print('老师原谅我了!!!')
#  for...else:
str1 = 'hello world'
for i in str1:
    print(i)
else:
    print('任务结束!')
#  for...else之break:
str1 = 'hello world'
for i in str1:
    if i == 'l':
        print('遇到l不执行。')
        break
    print(i)
else:
    print('任务结束!')

#  for...else之continue:
str1 = 'hello world'
for i in str1:
    if i == 'l':
        print('遇到l不执行。')
        continue
    print(i)
else:
    print('任务结束!')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值