天天看点

读书笔记

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#求模量运算符

00