while循环
i = 0
while i < 5:
print(i)
i += 1
计算 1 ~ 100之间的累加和
i = 1
sum_num = 0
while i <= 100:
sum_num = sum_num + i
i += 1
print(sum_num)
跳出循环
break 跳出本层循环
continue 跳出本次循环,执行下次循环
当累加和大于 1000时跳出循环
i=1
sum = 0
while i <= 100:
sum += i
if sum > 1000:
break
i += 1
print(sum)
计算所有奇数的和
i = 1
sum = 0
while i <= 100:
% 取模 //整除
if i % 2 == 0:
i += 1
continue
sum += i
i += 1
print(sum)
随机整数的生成
from random import randint
from 模块名 import name1, name2。。。
randint(start, end) [start, end]
print(randint(-20, 20))
字符串格式化输出
hero_name = '鲁班七号'
grade = 15
print('您选择的英雄是{}当前等级为{}级'.format(hero_name,grade))
猜数字游戏
for 临时变量 in 可迭代对象:
for i in range(1,101):
print('你已经没救了,这是第{}次了'.format(i))