python编程学习笔记(三)

五、if语句

1.示例

cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car=='bmw':
        print(car.upper())
    else:
        print(car.title())

输出结果:

Audi
BMW
Subaru
Toyota

2.条件测试

(1)检查相等:==

car=='bmw'  #注意是两个等号,一个等号是赋值

(2)大小写:
  python中大写和小写不一样,若不想区分大小写,可用:

>>> car='Audi'
>>> car.lower()=='audi' #变成小写形式再检查
True
>>> car  #不影响原来的变量
'Audi'

(3)检查不相等:!=
(4)比较数字:==,!=,<,<=,>,>=
(5)检查多个条件:and,or

>>> age_0,age_1=22,18
>>> age_0>=21 and age_1<21
True

(6)检查特定值是否包含在列表中:in,not in

>>> cars = ['audi','bmw','subaru','toyota']
>>> car_0='toyota'
>>> car_0 in cars #检查在列表中
True
>>> 'bmw' not in cars #检查不在列表中
False

(7)布尔表达式

game_active=True

3.if语句

(1)简单的if语句
  if conditional_test:
    do something
(2)if-else语句
  if conditional_test:
    do something 1
  else:
    do something2
(3)if-elif-else语句
  if conditional_test1:
    do something 1
  elif conditional_test2:
    do something 2
  else:
    do something3
注:可有多个elif代码块;可省略else代码块。
(4)测试多个条件:考虑使用多个if或在一个if后使用多个elif

requested_toppings=['mushrooms','cheese']

if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'apple' in requested_toppings:
    print("Adding apple.")
if 'cheese' in requested_toppings:
    print("Adding cheese.")

print("\nFinished making your pizza!")

输出结果:

Adding mushrooms.
Adding cheese.

Finished making your pizza!

4.使用if语句处理列表

(1)检查特殊元素

requested_toppings=['mushrooms','green peppers','cheese']
for requested_topping in requested_toppings:
    if requested_topping=='green peppers':  #已知青椒已用完,检查青椒
        print('Sorry,we are out of green peppers rihght now.')
    else:
        print("Adding "+requested_topping+".")#没用完的可以加
print("\nFinished making your pizza!")   

输出结果:

Adding mushrooms.
Sorry,we are out of green peppers rihght now.
Adding cheese.

Finished making your pizza!

(2)确定列表不是空的

requested_toppings=[]

if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding "+requested_topping+".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

输出结果:

Are you sure you want a plain pizza?

(3)使用多个列表

available_toppings=['mushrooms','apples','olives','cheese','pineapple']
requested_toppings=['mushrooms','green peppers','cheese']

for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding "+requested_topping+".")
    else:
        print('Sorry,we are out of '+ requested_topping +' rihght now.')
print("\nFinished making your pizza!")

输出结果:

Adding mushrooms.
Sorry,we are out of green peppers rihght now.
Adding cheese.

Finished making your pizza!

六、字典

1.一个简单的字典

字典用放在花括号{}中的一系列键-值对表示,键-值对之间用逗号分割。

alien_0={'color':'green','points':5}

print(alien_0['color'])
print(alien_0['points'])

输出结果:

green
5

2.使用字典

(1)访问字典中的值字典名[键]

alien_0={'color':'green','points':5}

new_points=alien_0['points']
print("You just earned "+str(new_points)+" points!")

输出结果:

You just earned 5 points!

(2)添加键-值对:指定字典名[键]=值

alien_0={'color':'green','points':5}
print(alien_0)

alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)

输出结果:

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

注:键-值对的排列顺序与添加顺序不一定相同。Python不关心键-值对的添加顺序,而只关心键和值之间的关联关系。
(3)先创建一个空字典

alien_0={}

然后可以分行添加各个键-对值。
(4)修改字典中的值:赋值,字典名[键]=新值

alien_0={'color':'green','points':5}
print("The alien is "+alien_0['color']+".")

alien_0['color']='yellow'
print("The alien is now "+alien_0['color']+".")

输出结果:

The alien is green.
The alien is now yellow.

(5)删除键-值对:del字典名[键]
del:永久删除

del alien_0['points']

(6)由类似对象组成的字典

favorite_languages={     #多行键值对,先回车
    'jen':'python',      #每一行都缩进4个字符
    'sarah':'c++',
    'phil':'java',
    }
print("Sarah's favorite language is "+ #语句太长,可在+后换行,注意缩进到同级。
    favorite_languages['sarah'].title()+
    ".")

输出结果:

Sarah's favorite language is C++.

3.遍历字典

(1)遍历所有键-值对:字典名.items()

favorite_languages={     
    'jen':'python',      
    'sarah':'c++',
    'phil':'java',
    'danny':'matlab',
    }
for name,language in favorite_languages.items():
#key,value可以随意设置变量名    
    print("\nName: "+name.title())
    print("Language: "+language.title())

输出结果:

```python
Name: Jen
Language: Python

Name: Sarah
Language: C++

Name: Phil
Language: Java

Name: Danny
Language: Matlab

注:遍历字典时,键-值对的输出顺序与存储顺序可能不同。
(2)遍历所有键:字典名.keys()

for name in favorite_languages.keys():

for name in favorite_languages:
    print("Name: "+name.title())

输出结果:

Name: Jen
Name: Sarah
Name: Phil
Name: Danny

因为输出顺序与存储顺序可能不同,可用sorted()按顺序遍历:

for name in sorted(favorite_languages.keys()):

(3)遍历所有值:字典名.values()

favorite_languages={     
    'jen':'python',      
    'sarah':'c++',
    'phil':'java',
    'danny':'python',
    }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language)

输出结果:

The following languages have been mentioned:
python
c++
java
python

可以使用集合(set)去掉重复:

for language in set(favorite_languages.values()):

输出结果:

The following languages have been mentioned:
python
c++
java

4.嵌套

1.字典列表

#创建30个绿色的外星人
for alien_number in range(30):
    new_alien={'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)

#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...")

#显示创造了多少外星人
print("Total number of aliens: "+str(len(aliens))+"\n\n")



#将前三个外星人设置为yellow,10,medium
for alien in aliens[:3]:
    alien['color']='yellow'
    alien['points']=10
    alien['speed']='medium'
    
#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...\n\n")



#将前5个中颜色为绿色的外星人设置为red,15,fast
for alien in aliens[:5]:
    if alien['color']=='green':
        alien['color']='red'
        alien['points']=15
        alien['speed']='fast'
    
#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...")   

输出结果:

{'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


{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...


{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
...

2.在字典中存储列表

#存储所点的pizza信息
pizza={
    'xingzhuang':'circle',
    'price':60,
    'toppings':['mushroom','cheese']
    }

print("You ordered a "+pizza['xingzhuang']+" pizza "+
      "with the following toppings:")
for topping in pizza['toppings']:
    print(topping)
print("And you need to pay "+str(pizza['price'])+" dollars.")

输出结果:

#存储所点的pizza信息
pizza={
    'xingzhuang':'circle',
    'price':60,
    'toppings':['mushroom','cheese']
    }

print("You ordered a "+pizza['xingzhuang']+" pizza "+
      "with the following toppings:")
for topping in pizza['toppings']:
    print(topping)
print("And you need to pay "+str(pizza['price'])+" dollars.")

3.在字典中存储字典

users={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
        },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
        },
    }

for username,user_info in users.items():
    print("\nUsername: "+username)
    full_name=user_info['first']+" "+user_info['last']
    location=user_info['location']
    print("\tFull name: "+full_name.title())
    print("\tLocation: "+location.title())

输出结果:

Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris

参考文献:袁国忠,Python编程:从入门到实践

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值