循环
1 """ 2 while 条件: 3 满足条件 4 #只要条件满足,会无限循环执行 5 """ 6 i = 0 7 sum = 0 8 while i<=100: 9 sum = sum + i 10 i += 1 11 print(sum)
while循环猜数字
1 #无限次猜数字 2 import random 3 num = random.randint(1,100) 4 count = 0 5 flag = True 6 while flag: 7 guess_num = int(input("请输入你猜测的数字:")) 8 count += 1 9 if guess_num == num: 10 print("猜中了!") 11 flag = False 12 else: 13 if guess_num > num: 14 print("大了") 15 else: 16 print("小了") 17 print("你猜测了",count,"次")
while嵌套循环打印九九乘法表
不换行 end=‘ ’
1 #定义外层循环的控制变量 2 i = 1 3 while i <= 9: 4 #定义内层循环的控制变量 5 j = 1 6 while j <= i: 7 print(f"{j}*{i}={j * i}\t",end=' ') 8 j += 1 9 i += 1 10 print() #print空内容,就是一个换行
for循环
case : 找“a”
""" for 临时变量 in 待处理数据集: 循环满足条件时执行的代码 """ #case:查看字符串有几个a string = "aaaaaaaaaa" count = 0 for i in string: if i == 'a': count += 1 print(count)
range语句
#语法1 range(num) #遍历:序列类型 for i in range(5): print(i) #语法2 range(num1.num2) #获得从1开始到5结束的序列(不包含5) for j in range(1,5): print(j) #语法3 range(num1.num2.step) #获得从1开始到5结束的序列(不包含5) #step为步长 for k in range(1,10,3): print(k)
range case:求偶数个数
count = 0 num = int(input("请输入一个数:")) for i in range(1,num): if i%2==0: count += 1 print(f"1~{num}一共有{count}个偶数")
for循环的嵌套打印九九乘法表
for i in range(1,10): for j in range(1,i+1): print(f"{j}*{i}={j*i}\t",end=' ') print()
循环中断
continue关键字:跳过本次循环,执行下一次
break关键字:结束循环
标签:count,循环,while,range,num,print,python3 From: https://www.cnblogs.com/smll1/p/17780625.html