001 输密码
设计一个验证用户密码的程序,用户只有三次机会输入错误,不过,如果用户输入的内容里包含“*”,则不算在次数内。
count = 3
password = "woaicxt"
while count > 0:
passwd = input("请输入密码:")
if passwd == password:
print("密码正确,正在进入程序")
elif'*' in passwd: #注意*用引号引起来
print("不允许包含*,您还有",count,"次机会")
continue #满足count > 0 ,不往下执行,继续while循环
else:
print("输入错误,您还有",count-1,"次机会")
count -= 1
002 求水仙花数
求100-999之间的所有水仙花数
水仙花数:如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。例如:153 = 1^3 + 5^3 + 3^3,所以153是水仙花数。
for i in range(100,1000):
sum = 0
temp = i
while temp:
sum = sum + (temp%10) ** 3 # temp%10:取出一个数的个位数部分
temp //= 10 # temp = temp // 10 (//:整除后取整数部分)
if sum == i:
print(i)
第一个for循环:i= 100,sum =0 temp =100 ---> (while循环)sum=0 temp=10 (个位数的立方和)
---> (while循环)sum=0 temp=1 ((个位数+十位数)的立方和)
---> (while循环)sum=1 temp=0 ((个位数+十位数+百位数)的立方和)
(temp=0:退出while循环,此时sum!=i,不执行if语句,直接返回for循环,取i=101,sum=0,temp=101)
第二个for循环:i =101 sum =0 temp =101 ---> sum=1 temp=10
---> sum=1 temp =1
---> sum=2 temp =0
……
第五十四个for循环:i =153 sum =0 temp =153 --->(while循环)sum=27 temp=15
--->(while循环)sum=27+5^3=152 temp=1
--->(while循环)sum=152+1^3=153 temp=0(退出while循环)
--->此时 sum==i,执行if语句
……
第九百个for循环
# 003 摸三色球
#有红、黄、蓝三种颜色的球,其中红球 3 个,黄球 3 个,绿球 6 个。先将这 12 个球混合放在一个盒子中,从中任意摸出 8 个球,编程计算摸出球的各种颜色搭配。for red in range(0,4): for yellow in range(0,4): for green in range(2,7): #摸八个球,出现绿球个数的可能性为【2,3,4,5,6】 if red + yellow + green == 8: #我的理解:满足条件,继续执行,不满足条件返回 最内部的for循环(green),然后第二个for循环(yellow),最后第一个for循环。
print(red,'\t',yellow,'\t')0 2 60 3 51 1 61 2 51 3 42 0 62 1 52 2 42 3 33 0 53 1 43 2 33 3 20 3 51 1 61 2 51 3 42 0 62 1 52 2 42 3 33 0 53 1 43 2 33 3 2改进游戏:怎么能够输出有多少种可能性。