第五章

5-5 外星人颜色 :将练习5-4中的if-else 结构改为if-elif-else 结构。 
·如果外星人是绿色的,就打印一条消息,指出玩家获得了5个点。 
·如果外星人是黄色的,就打印一条消息,指出玩家获得了10个点。 
·如果外星人是红色的,就打印一条消息,指出玩家获得了15个点。
for i in range(0,3):
    alian_color = input()
    if alian_color == 'green':
        print('You got 5 points.')
    elif alian_color == 'yellow':
        print('You got 10 points.')
    elif alian_color == 'red':
        print('You got 15 points')

green
You got 5 points.
red
You got 15 points
yellow
You got 10 points.

5-7 喜欢的水果 :创建一个列表,其中包含你喜欢的水果,再编写一系列独立的if 语句,检查列表中是否包含特定的水果。
·将该列表命名为favorite_fruits ,并在其中包含三种水果。 
·编写5条if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如“You really like bananas!”。
favorite_fruits = ['apple','banana','orange']
for fruit in favorite_fruits:
    if fruit == 'apple':
        print('You really like apples!')
5-8 以特殊方式跟管理员打招呼:创建一个至少包含5个用户名的列表,且其中一个用户名为'admin' 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。
·遍历用户名列表,并向每位用户打印一条问候消息。 如果用户名为'admin' ,就打印一条特殊的问候消息,如“Hello admin, would you like to see a status report?”。
·否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
users = ['admin','test','guest','normal']
for user in users:
    if user == 'admin':
        print('Hello, ' + user.title() + ', would you like to see a status report?')
    else:
        print('Hello, ' + user.title() + ', thank you for logging in again')

Hello, Admin, would you like to see a status report?
Hello, Test, thank you for logging in again
Hello, Guest, thank you for logging in again
Hello, Normal, thank you for logging in again
5-11 序数:序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。 
·在一个列表中存储数字1~9。
·遍历这个列表。
·在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序 数都独占一行。
nums = range(1,10)
for num in nums:
    print(num,end = '')
print()
for num in nums:
    if num == 1:
        print('1st',end = ' ')
    elif num == 2:
        print('2nd',end = ' ')
    elif num == 3:
        print('3rd',end = ' ')
    else:
        print(str(num) + 'th',end = ' ')
print()

123456789
1st 2nd 3rd 4th 5th 6th 7th 8th 9th



猜你喜欢

转载自blog.csdn.net/qq_36185481/article/details/79617868