一、while循环
while True:死循环,只能使用break
break: 退出当前循环
continue:继续下一轮循环
pass 在循环体或者函数体空时防止报错
import random #引入随机数
luck_num = random.randint(10,99)
luck_num_g = luck_num % 10
luck_num_s = luck_num //10
while True:
buy_num = int(input("请输入一个两位数:"))
if buy_num == luck_num:
print("一等奖")
break
elif buy_num % 10 == luck_num_s and buy_num //10 == luck_num_g:
print("二等奖")
break
else:
print("遗憾,没中奖")
二、使用while打印乘法表
正三角
i = 1 while i < 10: j = 1 while j <= i: print(j,"x",i,"=",i*j,end=" ") j += 1 print() i += 1
倒三角
i = 9 while i > 0: j = 1 while j <= i: print(j,"*",i,"=",i*j,end=" ") j += 1 print() i -= 1
向左三角
while i < 10: count = 0 while count<k: print(end=" ") count+=1 k-=1 j = 1 while j <= i: print("%s*%s=%s"%(j,i,i*j),end="\t") j += 1 print() i += 1
向左倒三角
i = 9 while i >0: k = 9 while k > i: print(end=" ") k -= 1 j = 1 while j <= i: print("%s*%s=%s"%(j,i,i*j),end="\t") j += 1 print() i -= 1
三、使用for循环
常在遍历时候使用,
在字典中取出键值,但可以用var.values()获得键值,用var.items()得到它本身
var = "今年过年不收礼啊," for val in var: print(val) #for循环嵌套 var = ["python","hello","java","c"] for val in var: print(val) for res in val: print(res) var = {"a":1,"b":2,"c":3} for val in var.items(): print(val) #在二级列表的使用中,可以使用abc这样的获得相应值,要求长度相同 var = [[1,2,3],[4,5,6],[7,8,9]] for a,b,c in var: print(a,b,c)
range(a,b) a为起始,b为最大值-1,(如果没有a那么就是从0开始 通过for循环打印乘法表
for i in range(1,10): for j in range(1,i+1): print("%sx%s=%s"%(j,i,i*j),end="\t") print() for i in range(1, 10): for j in range(i, 10): print("%sx%s=%s" % (i, j, i * j), end="\t") print() for i in range(1, 10): for k in range(1, 10 - i): print(end=" ") for j in range(1, i + 1): print("%sx%s=%s" % (j, i, i * j), end="\t") print()
来源:CSDN
作者:JJ1M8
链接:https://blog.csdn.net/JJ1M8/article/details/104331551