if语句和字典(第三周)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LRH2018/article/details/79690896

第五章 if语句

5-3 外星人颜色 #1

alien_color = 'green'
if alien_color == 'green':
    print("You get five points!")

输出:

You get five points!

如果不是绿色

alien_color = 'yellow'
if alien_color == 'green':
    print("You get five points!")
运行结果没有输出,因为不满足条件也没有else语句。

5-4 外星人颜色#2

alien_color = 'green'
if alien_color == 'green':
    print("You get five points!")
else:
    print("You get ten points!")

程序运行结果为

You get five points!
如果将第一行代码改为

alien_color = 'yellow'
那么结果变为

You get ten points!

5-7 喜欢的水果

favorite_fruits = ['apple', 'banana', 'peach']
if "apple" in favorite_fruits:
    print("You really like apples!")
if "watermelon" in favorite_fruits:
    print("You really like watermelon!")
if "banana" in favorite_fruits:
    print("You really like bananas!")
if "lemon" in favorite_fruits:
    print("You really like lemon!")
if "pear" in favorite_fruits:
    print("You really like pears!")

运行结果:

You really like apples!
You really like bananas!

5-8 以特殊方式和管理员打招呼

users = ['admin', 'Tom', 'Mary', 'Jerry', 'Jim']
for name in users:
    if name == 'admin':
        print('Hello '+ name + ', would you like to see a status report?')
    else:
        print('Hello '+ name + ', thank you for logging in again')

结果如下:

Hello admin, would you like to see a status report?
Hello Tom, thank you for logging in again
Hello Mary, thank you for logging in again
Hello Jerry, thank you for logging in again
Hello Jim, thank you for logging in again

第六章 字典

6-1 人:

dict = {'first_name':'Ruhua', 'last_name':'Liao', 'age':20,'city':'Guangzhou'}
for x in dict:
    print(x + ': ' + str(dict[x]))
这段代码运行结果:
first_name: Ruhua
last_name: Liao
age: 20
city: Guangzhou
6-2 喜欢的数字
nums = {'Yongheng':18, 'Jiahong':66, 'Xuntong':12345, 'Tom':555, 'Jerry':23333}
for x in nums:
    print(x + ': ' + str(nums[x]))
程序运行的结果:
Yongheng: 18
Jiahong: 66
Xuntong: 12345
Tom: 555
Jerry: 23333

6-5 河流

rivers = {'nile':'egypt', 'Changjiang River':'china', 'Yellow River':'china'}
for river in rivers:
    print("The "+ river.title() + " runs through " + rivers[river].title()+'.')
for x in rivers.keys():
    print(x.title())
for x in rivers.values():
    print(x.title())
代码执行结果为
The Nile runs through Egypt.
The Changjiang River runs through China.
The Yellow River runs through China.
Nile
Changjiang River
Yellow River
Egypt
China
China

6-8 宠物

milk = {'name':'milk','type':'dog', 'owner':'Jim' }
pick = {'name':'pick','type':'pig', 'owner':'Mary'}
tom = {'name': 'tom','type':'cat', 'owner':'Jerry'}
pets = [milk, pick, tom]
for pet in pets:
    for x in pet:
        print(x+" : "+ pet[x])
程序运行结果为
name : milk
type : dog
owner : Jim
name : pick
type : pig
owner : Mary
name : tom
type : cat
owner : Jerry







猜你喜欢

转载自blog.csdn.net/LRH2018/article/details/79690896
今日推荐