小甲鱼python视频第八讲(课后习题)

时间:2023-01-01 21:19:33

1.for循环的使用,注意下面代码的区别

for i in range(0,10,2):
print("i love you")
for i in range(0,10):
print("i love you")
for i in range(5):
print("i love you")

2.break与continue的区别

for i in range(5):
if i == 2:
break
print(i)
for i in range(5):
if i == 2:
continue
print(i)

break是执行到i==2时,跳出整个循环,continue是跳出i==2这个循环。

while True:
while True:
break #跳出的是第二个while,但还是要打印2
print(1)
print(2)
break #跳出的是第一个while,但还是要打印3
print(3)

3.我爱你的长度

i = 0
string = "i love you"
while i < len(string):
print(i)
i += 1

改进版:

i = 0
string = "i love you"
length = len(sring)
while i < length:
print(i)
i += 1

改进原因:每次循环都要调用len()函数

4.

answer = 'i love you'
times = 3 while times:
times -= 1
key = str(input('请输入密码:')) if key == answer:
print('密码正确,进入程序....')
break
elif "*" in key:
print('密码中不能含有"*"号!您还有3次机会!',end = ' ')
continue
elif times == 0:
print('账号已被绑定,请等待十分钟!!!')
else:
print('密码输入错误!你还有',times,'次机会!',end = ' ')

另附小甲鱼的源代码:

count = 3
password = 'FishC.com' while count:
passwd = input('请输入密码:')
if passwd == password:
print('密码正确,进入程序......')
break
elif '*' in passwd:
print('密码中不能含有"*"号!您还有', count, '次机会!', end=' ')
continue
else:
print('密码输入错误!您还有', count-1, '次机会!', end=' ')
count -= 1

5.求水仙花数

for i in range(100,1000):
result = 0 #给变量起名时,尽量注意不要使用内置函数
temp = i
while temp:
result = result + (temp%10)**3 #temp是随着下面的公式变化的
temp //= 10 #地板除的使用
if result = i: #判断幂的和等于数值的大小
print(i)

另附小甲鱼源代码:

for i in range(100, 1000):
sum = 0
temp = i
while temp:
sum = sum + (temp%10) ** 3
temp //= 10 # 注意这里要使用地板除哦~
if sum == i:
print(i)

6.乒乓球的分配(3个红色,3个黄色,6个绿色,随机取出8个,一共多少种结果)看小甲鱼的,自己不会写:

print('red\tyellow\tgreen')
for red in range(0,4):
for yellow in range(0,4):
for green in range(2,7): #绿色必须有两个
if red + yellow + green = 8:
print(red,'\t',yellow,'\t',green,'\t')

注释代码:

for i in range(0,4):
print(i)
for i in range(2,7):
print(i)