P95頁嵌套
建立空清單用以外星人
aliens = []
#建立30個綠色的外星人
for alien_number in range(0,30): 疑問:為何是alien_number???
new_alien ={'color':'green','speed':'slow','point':5}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color']='yellow'
alien['speed'] = 'high'
alien['point'] = 10
顯示前五個
print(aliens[0:5])
print('........')
以上代碼進一步拓展
for alien_number in range(0,30):
elif alien['color'] == 'yellow':#将上面if下的黃色的外星人改為紅色.....
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['point'] = 15
P96例1
存儲所有披薩資訊
pizza = {
'Crust':'thick',
'topping':['mushroom','extra cheese']
}#字典中的鍵值對的值可以是清單:'topping':['mushroom','extra cheese']
描述所點的披薩
print(' You order a '+ pizza['Crust'] +'- crust pizza '+
'with the flowing toppings:')
for topping in pizza['topping']:
print("\t"+topping) #制表符【\t】
#知識點:通路字典中的鍵名——pizza['Crust']、制表符\t的使用
#P96例二
favorite_language = {
'jen':['python','Ruby'],
'sarah':['C'],
'edward':[' Ruby','GO'],
'phil':['c++','python'],
}
for name,languages in favorite_language.items():#在items一定不能少了s
print('\n' + name.title() + "'s favorite languages are:")
for language in languages:
print( "\t"+ language.title())#for循環與print聯合使用達到循環列印
#知識點:字典鍵值對一起通路使用方法【.items()】
"""循環若第n行緊接着下一行是縮進,那麼第n+1屬于第n行,例如
#for language in languages:
print( "\t"+ language.title())第二行屬于第一行的for循環中
"""
#P97 在字典中存貯字典
users = {
'jocker':{'first_name':'li','last_name':'kunhai','age':25},
'Albert':{'first_name':'zhou','last_name':'bangqin','age':38},
for user_name,user_information in users.items():
#鍵放在user_name值放在user_information中
print("\nUser_name " + user_name)
full_name = user_information['first_name'] + "" + user_information['last_name']
print('\tfull_name ' + full_name.title())
P100使用者輸入和while循環
例子
numbers = input('pleas, input number:' )
if int(numbers) <= 45:
print('you are 6666!!!....')
#運作結果:pleas, input number:25
you are 6666!!!....
#請求使用者輸入一條資訊,并列印該條資訊
massage = input('tell sometion,and I will repeat it bakck to you: ')
#input括号内的提示語:要規範\易于明白
print(massage)
例子:
name = input("pleas enter your name: ")
print('hollo!!!'+ name + " you are 6666!!!!")
#編寫清晰的代碼
name = input('A') #如果A較長,可以先存貯在一個變量中
print(A)
改進例子如下所示:
prompt = "If you tell us who you are, we can personalize you see."
prompt += "\n what is you first name?: " # prompt += 表示在prompt後面追加字元串。
name = input(prompt)
print('\n Hello '+ name + '!')
錯誤例子
#P102用input擷取輸入值并用int()來将輸入的值轉化為數值
age = input("how old are you? :")
input = int(age)
if age < 25: #該句文法錯誤
print("...........")
#錯誤:TypeError: '<' not supported between instances of 'str' and 'int'
#因為age < 25中,age為字元串而不能與數值作比較大小
例子P103#求模量運算符