循环结构学习

while循环

# -*- coding: utf-8 -*-
"""
功能:采用while循环输出百遍口号
作者:CXF
时间:2021年11月4日
"""
i = 1 #初始条件
while i <= 100: #循环条件
    print('第{}口号:好好学习,天天向上'.format(i))
    i += 1 #迭代条件(更新条件)

死循环结束用:Ctrl + c
第一种方法

"""
功能:采用while循环计算1+2+3+……+100
作者:CXF
时间:2021年11月4日
"""

sum = 0
i = 1 #初始条件
while i <= 100: #循环条件
    sum = sum + i #累加条件
    i = i + 1 # 更新条件
print('1 + 2 + 3 +……+100 = {}'.format(sum))

第二种方法

"""
功能:采用循环计算1+2+3+……+100
作者:CXF
时间:2021年11月4日
"""

sum = 0
for i in range(1,101):
    sum = sum + i
print('1 + 2 + 3 +……+100 = {}'.format(sum))

水仙花数

# -*- coding: utf-8 -*-
"""
功能:采用while循环打印水仙花数
作者:CXF
时间:2021年11月4日
"""

n = 100 #初始条件
while n <= 999: # 循环条件
    n_str = str(n)
    p1 = int ( n_str[2]) # 个位数
    p2 = int ( n_str[1]) # 十位数
    p3= int ( n_str[0]) # 百位数
    if n == p3**3 + p2**3 + p1 **3:
        print('{} = {}^3 + {}^3  + {}^3 '.format(n, p3, p2, p1))
    n = n + 1 # 更新条件

Guess you like

Origin blog.csdn.net/qq_62590351/article/details/121149493