天天看點

2.Control FlowControl 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
banana
1 mattresses
2 dog kennels
3 machine
4 cheese