这能看出哪点没学通?
#创建一个用于存储方形人的列表aliens = []
#创建30个外星人
for alien_number in range(30):
new_alien = {'color':'green', 'points':5, 'speed':'slow'}
aliens.append(new_alien)
#修改前三个外星人颜色分值速度
for alien in aliens[:4]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 1111
alien['speed'] = 'medium'
#将黄色改为快速15分红色
for alien in aliens[:4]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 2
alien['speed'] = 'medium'
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['points'] = 3
alien['speed'] = 'fast'
#显示前五个外星人
for alien in aliens[:10]:
print(alien)
print('...')
#显示创建了多少个外星人
print(f'Total number of aliens:{len(aliens)}')
忽略注释··
=========== RESTART: C:\Users\Administrator\Desktop\python\aliens.py ===========
{'color': 'red', 'points': 3, 'speed': 'fast'}
{'color': 'yellow', 'points': 2, 'speed': 'medium'} 为什么这三行的结果不是red 3
{'color': 'yellow', 'points': 2, 'speed': 'medium'}为什么这三行的结果不是red 3
{'color': 'yellow', 'points': 2, 'speed': 'medium'}为什么这三行的结果不是red 3
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens:30 嵌套FOR循环 如果改成4切片为什么结果不是red 4 这个说明我哪没学通??? 123456123456a 发表于 2022-1-7 17:26
嵌套FOR循环 如果改成4切片为什么结果不是red 4 这个说明我哪没学通???
你代码中有两个for循环,里面那个是在if 语句下的,只要if 不执行,for循环也不执行
你外层循环第一轮后前4个 为 红 黄黄黄,只要之后的if条件都不会执行,把里层for缩进左移一下就好了
# 创建一个用于存储方形人的列表
aliens = []
# 创建30个外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 修改前三个外星人颜色分值速度
for alien in aliens[:4]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 1111
alien['speed'] = 'medium'
# 将黄色改为快速15分红色
for alien in aliens[:4]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 2
alien['speed'] = 'medium'
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['points'] = 3
alien['speed'] = 'fast'
# r y y y
# 显示前五个外星人
for alien in aliens[:10]:
print(alien)
print('...')
# 显示创建了多少个外星人
print(f'Total number of aliens:{len(aliens)}')
{'color': 'red', 'points': 3, 'speed': 'fast'}
{'color': 'red', 'points': 3, 'speed': 'fast'}
{'color': 'red', 'points': 3, 'speed': 'fast'}
{'color': 'red', 'points': 3, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens:30
页:
[1]