2.Control Flow

Control Flow

if,elif,else

if phone_balance < 5:
    phone_balance += 10
    bank_balance -= 10
if season == 'spring':
    print('plant the garden!')
elif season == 'summer':
    print('water the garden!')
elif season == 'fall':
    print('harvest the garden!')
elif season == 'winter':
    print('stay indoors!')
else:
    print('unrecognized season')
  • 以下等同于false
    • None
    • 任何数值型,值为0
      • 0,0.0,0j,Decimal(0),Fraction(0,1)
    • 空容器
      • “”,[],{},(),set(),range(0)

Loops


for

  • 迭代器 iteration
    • 可以是任何容器,文件以及字典
    • 每次取一个元素
    • 明确迭代
      • 预定义迭代次数
  • 利用for loop我们可以创建一个lists或者修改一个lists
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
    print(city)
print("Done!")
new york city
mountain view
chicago
los angeles
Done!
  • Operation and Method

    • range(start,end,step)
    • 三个参数必须全部是整数
    • 缺省
      • start = 0
      • step = 1
    • 三种情况
      • range(3)
        • 0 到 3-1 步长为1
      • range(2,6)
        • 2 到 6-1 步长为1
      • range(1,10,2)
        • 1 到 10-1 步长为2
  • c++或java中for的使用

for i in range(start,end):
    arr[i] #Operation
  • 容器使用
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']

for index in range(len(cities)):
    cities[index] = cities[index].title()
New York City
Mountain View
Chicago
Los Angeles

  • For loop for dictionary
cast = {
           "Jerry Seinfeld": "Jerry Seinfeld",
           "Julia Louis-Dreyfus": "Elaine Benes",
           "Jason Alexander": "George Costanza",
           "Michael Richards": "Cosmo Kramer"
       }

for key in cast:
    print(key)

Jerry Seinfeld
Julia Louis-Dreyfus
Jason Alexander
Michael Richards

只能访问key

for key, value in cast.items():
    print("Actor: {}    Role: {}".format(key, value))
Actor: Jerry Seinfeld    Role: Jerry Seinfeld
Actor: Julia Louis-Dreyfus    Role: Elaine Benes
Actor: Jason Alexander    Role: George Costanza
Actor: Michael Richards    Role: Cosmo Kramer

通过item获取字典的键值对,然后利用unpacking 赋值给key和value,以既访问key,又访问value

  • while
    • 无需明确迭代次数
card_deck = [4, 11, 8, 5, 13, 2, 8, 10]
hand = []

# adds the last element of the card_deck list to the hand list
# until the values in hand add up to 17 or more
while sum(hand)  < 17:
    hand.append(card_deck.pop())

Zip and Enumerate

  • Zip
    • return 迭代器
    • 需要转换成一个list
    • method and Operation:
      • zip(list1,list2)

        返回了一个迭代器

        list(zip(list1,list2))

        或者for item,weight in zip(items,weights)

items = ['banana','mattresses','dog kennels','machine','cheese']
weights = [15,34,42,120,5]

print(list(zip(items,weights)))
[('banana', 15), ('mattresses', 34), ('dog kennels', 42), ('machine', 120), ('cheese', 5)]
    • zip(*manifest)
      • 解包

        items,weights = zip(*manifest)

items = ['banana','mattresses','dog kennels','machine','cheese']
weights = [15,34,42,120,5]

manifest = []
for item, weight in zip(items,weights):
    manifest.append((item,weight))

print(manifest)
items1,weights1 = zip(*manifest)

print(items1)
print(weights1)

[('banana', 15), ('mattresses', 34), ('dog kennels', 42), ('machine', 120), ('cheese', 5)]
('banana', 'mattresses', 'dog kennels', 'machine', 'cheese')
(15, 34, 42, 120, 5)

Process finished with exit code 0

items = ['banana','mattresses','dog kennels','machine','cheese']
for i,item in zip(range(len(items),items))
    print(i,' ',item)
  • Enumerate
items = ['banana','mattresses','dog kennels','machine','cheese']
for i,item in zip(range(len(items)),items):
    print("{} {}".format(i,item))

输出

id item
0 banana
1 mattresses
2 dog kennels
3 machine
4 cheese

猜你喜欢

转载自blog.csdn.net/a245293206/article/details/89843358