while循环


while的死循环

while True:
    print("hello python!")

控制台输出10次helloPython

# 1.定义初始化循环条件的变量
index = 0
# 2.判断循环条件
while index < 10:
    print("hello python!")
    # 3.修改循环条件
    index += 1

需求:100以内的整数和(while循环实现)

index = 0
# 定义累加变量sum
sum = 0
while index <= 100:
    sum = sum + index
    index += 1

# print("100以内的整数和:"+str(sum))
# print("100以内的整数和是:%s" % sum)
# print(f"100以内的整数和是:{sum}")
print("100以内的整数和是:{}".format(sum))

求100以内的偶数和

index = 0
# 定义累加变量sum
sum = 0
while index <= 100:
    # 偶数,判断是不是偶数
    if index % 2 == 0:
        # 只有是偶数时候累加
        sum = sum + index
    index += 1

print("100以内的偶数和是:{}".format(sum))