if语句和字典(第三周)

第五章 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







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值