1. while循环
(1) 代码
1. 示例
i = 0
while i < 100:print(f"第{i}次循环")i += 1
2. 计算从1加到100的和
i = 1
sum = 0
while i <= 100:sum += ii += 1
print(f"1加到100的和是{sum}")
3. 使用while循环无限次猜测随机产生的数字,直到猜对,结束循环
import random
num = random.randint(1, 100)conditions = True
i = 1
while conditions:guess_num = int(input(f"请输入第{i}次猜测的数字:"))if guess_num == num:print(f"你在第{i}次猜对了")conditions = Falseelif guess_num != num:if guess_num > num:print("你猜的数字大了")elif guess_num < num:print("你猜的数字小了")i += 1print(f"num = {num}")
4. 使用print打印99乘法表
(1) print不换行
print("hello", end='')
print("world", end='')
(2) 制表符\t可让多行字符对齐
print("hello\tworld")
print("super\tcarrydoinb")
(3) 输出空行
print()
(4) 99乘法表代码
j = 1
while j < 10:i = 1while i <= j:if i == j:print(f"{i}*{j}={i * j}")elif i < j:print(f"{i}*{j}={i*j}\t", end='')i += 1j += 1
2. for循环
(1) 遍历字符串
tmp_str = "supercarrydoinb"
for i in tmp_str:print(f"{i} ", end='')
(2) 判断字符串中有多少个a
tmp_str = "supaearcarrydoianba"
cnt = 0
for i in tmp_str:if i == "a":cnt += 1
print(f"the num of a in {tmp_str} is {cnt}")
(3) range语句(range与for循环可以搭配使用)
1.
2.
3.
4. 使用for+range获取1到n之间有多少个偶数
EvenNum_cnt = 0
tmp_num = 101
for i in range(1, tmp_num):if 0 == i % 2:EvenNum_cnt += 1
print(f"EvenNum_cnt = {EvenNum_cnt}")
5. 注意:for循环中第一个遍历为临时变量,作用域在循环内部,若要在循环外访问,需要在使用变量之前定义
6. 99乘法表
for i in range(1, 10):for j in range(1, i+1):if j == i:print(f"{i}*{j}={i*j}")elif j < i:print(f"{i}*{j}={i*j}\t", end='')
7. 案例练习
all_salary = 10000
everyone_salary = 1000
for i in range(1, 21):if all_salary > 0:performance = random.randint(1, 10)if (performance >= 1) and (performance < 5):print(f"员工{i}, 绩效为{performance}, 低于5, 不发工资,下一位")continueelif (performance >= 5) and (performance <= 10):all_salary -= everyone_salaryprint(f"向员工{i}发放工资{everyone_salary}元,账户余额还剩{all_salary}元")elif all_salary <= 0:print("工资发完了,下个月再领吧")break
if all_salary > 0:print(f"员工工资发放完毕,剩余资金{all_salary}元归老板所有,哈哈哈哈哈哈哈哈哈")