python的课后练习总结4(while循环)

for循环用于针对序列中的每个元素的一个代码块。

while循环是不断的运行,直到指定的条件不满足为止。
 

while 条件:
        条件成立重复执行的代码1
        条件成立重复执行的代码2
        ……..

i = 1

while i <= 5:

        print(i)

        i = i + 1

1、使用while循环,打印1~100的所有数字

2、计算1-100内的累加(如1+2+3+4+…+100)

3、计算1-100的偶数累加和 (如2+4+6+…+100)


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



x = 1
y = 0
while x <=100:
    y = y +x
    x = x+1
print("1 到 100 的累加和为:", y)


x = 2
y = 0
while x <=100:
    y = y + x
    x = x + 2
print("1 到 100 的偶数累加和为:", y)

 

退出循环的两种不同方式:

break          终止循环

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


1、一共5个苹果,吃到第4个时吃饱了,不吃了。

total_apples = 5
eat_count = 0

while eat_count < 4:
    eat_count += 1
    print("吃了第", eat_count, "个苹果")

print("吃饱了,不吃了")

2、一共5个苹果,吃到第3个时发现一只大虫子,第3个不吃了,继续吃第4个苹果,直到吃完
 

total_apples = 5
eat_count = 0

while eat_count < total_apples:
    eat_count += 1
    if eat_count == 3:
        print("第", eat_count, "个苹果有虫子,不吃了")
        continue
    print("吃了第", eat_count, "个苹果")

print("吃完了所有的苹果")

相关推荐

  1. pythonwhile循环

    2024-01-05 19:18:01       12 阅读
  2. Python循环语句——while循环基础应用

    2024-01-05 19:18:01       32 阅读
  3. Python循环语句——while循环嵌套应用

    2024-01-05 19:18:01       26 阅读
  4. Python: for,while循环语句

    2024-01-05 19:18:01       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-05 19:18:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-05 19:18:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-05 19:18:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-05 19:18:01       20 阅读

热门阅读

  1. cocos creator人开发小游戏免费素材资源

    2024-01-05 19:18:01       38 阅读
  2. 算法:简单加密

    2024-01-05 19:18:01       30 阅读
  3. 快速搭建 linux 源码调试环境

    2024-01-05 19:18:01       38 阅读
  4. 什么是Vue-响应式数据

    2024-01-05 19:18:01       36 阅读
  5. 2023年终总结

    2024-01-05 19:18:01       32 阅读
  6. LeetCode 28.找出字符串中第一个匹配项的下标

    2024-01-05 19:18:01       46 阅读
  7. 【PHP】PHP实现RSA加密,解密,加签,验签

    2024-01-05 19:18:01       42 阅读
  8. IDEA UML图

    2024-01-05 19:18:01       34 阅读
  9. LeetCode 32:最长有效括号

    2024-01-05 19:18:01       32 阅读
  10. 安装Paddle-ChatDocuments大模型

    2024-01-05 19:18:01       36 阅读