三元操作符
- Python 的作者在很长一段时间不肯加入三元操作符就是怕跟C语言一样搞出国际乱码大赛,蛋疼的复杂度让初学者望而生畏,不过,如果你一旦搞清楚了三元操作符的使用技巧,或许一些比较复杂的问题反而迎刃而解。
请将以下代码修改为三元操作符实现:
>>> x,y,z=6,5,4
>>> if x<y and x<z:"x"
elif y<x and y<z:"y"
else:"z"
'z'
【小甲鱼的↓↓】
>>> small = x if (x < y and x < z) else (y if y < z else z)
z
range 和for in
【学会提高代码的效率】你的觉得以下代码效率方面怎样?有没有办法可以大幅度改进(仍然使用while)?
1. i = 0
2. string = 'ILoveFishC.com'
3. while i < len(string)):
4. print(i)
5. i += 1
>>>
0
1
2
3
4
5
6
7

【1 这样成了列表模式了】
a="love you"
print(list(range(len(a))))
[0, 1, 2, 3, 4, 5, 6, 7]
密码验证
设计一个验证用户密码程序,用户只有三次机会输入错误,不过如果用户输入的内容中包含"*"则不计算在内。
password="liucd"
count=3
temp=input("请输入你的密码:")
while count>0:
if temp==password:
print("yes,进入程序……")
break
elif "*" in password:print("no ,not"*"")
else:
count-=1
if count!=0:
print("no,你还有",count,"次机会。")
temp=input("请重新输入你的密码:")
else:
print("sorry,你没有机会了")
>>>
= RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/00.py
请输入你的密码:3
no,你还有 2 次机会。
请重新输入你的密码:d
no,你还有 1 次机会。
请重新输入你的密码:liucd
yes
水仙花数
- 编写一个程序,求 100~999 之间的所有水仙花数。
如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一个水仙花数
for i in range(100,999):
if i==(i//100)**3+((i-(i//100)*100)//10)**3+((i-(i//100)*100-(i-(i//100)*100)//10*10)/1)**3:
print(i)
>>>
= RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/00.py
153
370
371
407
【条理些】
for i in range(100,999):
a=i//100
b=(i-a*100)//10
c=(i-a*100-b*10)
if i==a**3+b**3+c**3:
print(i)
【小甲鱼 ↓ ↓】
for i in range(100,999):
sum=0
temp=i
while temp:
sum=sum+(temp%10)**3
temp=temp//10
if sum==i:
print(i)
三色球问题 列表原来这么玩
有红、黄、蓝三种颜色的求,其中红球 3 个,黄球 3 个,绿球 6 个。先将这 12 个球混合放在一个盒子中,从中任意摸出 8 个球,编程计算摸出球的各种颜色搭配
print("红色\t黄色\t绿色\t")
for r in range(4):
for y in range(4):
for g in range(2,7):
if r+y+g==8:
print(r,"\t",y,"\t",g)
>>>
= RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/00.py
红色 黄色 绿色
0 2 6
0 3 5
1 1 6
1 2 5
1 3 4
2 0 6
2 1 5
2 2 4
2 3 3