python range倒序_《Python编程:从入门到实践》读书笔记

第一部分:基础知识

起步下载和安装省略,第11章测试部分省略。本文包含2-10章。

多少字我没数,大概花了5天时间过完基础部分,包括电脑+iPad,iPad+笔记(+电脑)两遍,经常把自己绕进去然后绕出来,第8、9章的时候觉得自己是爬不出来了,11章即将结束的时候又有万里长征最后一步的兴奋。

OK,这依然是第一步,后面路还很长,继续加油~~~

第2章:变量和简单数据类型

1,变量命名:只能包含数字、字母和下划线,不可以以数字打头;不能包含空格,不建议用python关键字和函数用做变量名,可以用驼峰法命名,比如变量名是几个英文的组合,从第二个单词起首字母大写,方便辨认和理解。

2,字符串包含在引号中。

3,字符串大小写修改

.title():首字母大写

.upper():全部大写

.lower():全部小写

4,制表符:t

换行符:n

5,删除空白

.rstrip():删除右侧空白

.lstrip():删除左侧空白

.strip():删除全部空白

要永久删除的话,需要将删除操作的结果存到变量中,否则可以理解为生成一个新的变量。


>>>favorite_language = 'python '
>>>favorite_language = favorite_language.rstrip() >>>favorite_language
'python'

6,浮点数:python中带小数点的数字。

str()可以将数字变成字符串,方便打印。

7,python之禅:用import this调用出来。

第3章:列表简介

可以将任何东西加入列表中,命名通常为复数,用[]表示列表,用逗号分隔元素。

1,访问列表元素:列表名[索引位置],如下,访问并打印bicycles列表的第一个元素,索引从0开始,而非从1开始。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']


print(bicycles[0])

同样,索引为-1,指列表倒数第一个元素.

2,修改列表元素:列表名[索引位置]='新元素'

如上例:bicycle[0]='yamaha'

3,添加列表元素:

.append():在列表末尾添加元素

.insert(位置,'新元素'),在列表指定位置添加新元素。

4,删除元素:

1) del 列表名[位置]:删除列表指定位置的元素,删除后无法访问。

如:del bicycles[2]

2) .pop():删除列表末尾的元素,并且可以继续使用该元素,该元素命名为 列表名.pop() 。

相应的,.pop(位置),可以删除任何位置的元素,并且可以继续使用该元素。

3).remove('元素名'):知道元素的值,直接删除该元素,删除后也可以继续使用。

4,列表排序

1).sort()

永久改变列表,按升序排列。

.sort(reverse=True)

列表按降序排列,永久改变列表。

2)sorted(列表名)

升序排列,不改变列表顺序。

sorted(列表名,reverse=True)

降序排列,不改变列表顺序

3).reverse()

倒序打印列表

5,len(列表名)

确认列表长度

第4章 操作列表

1,用for循环遍历整个列表:对列表的每个元素都执行一遍循环步骤。 (不要遗漏for后面的冒号)。

magicians = ['alice', 'david', 'carolina']


for magician in magicians:


print(magician.title()+", that was a great trick!")


print("I can't wait to see your next trick, "+magician.title()+".n")

2,range()函数创建数值列表。

1)range()

for value in range(1,5):

print(value)

结果为1,2,3,4.

2)要直接创建列表,需要用list()转换。

numbers=list(range(1,6))

print(numbers)

#[1,2,3,4,5]

even_numbers=list(range(2,11,2))

print(even_numbers)

#[2,4,6,8,10]

3)平方列表

squares = []

for value in range(1,11):

square = value**2

squares.append(square) print(squares)

#[1,4,9,16,25,36,49,64,81,100]

上述案例也可以解析为:

squares=[value**2 for value in range(1,11)]

print(squares)

3,对列表的简单计算

min(列表名)

max(列表名)

sum(列表名)

4,列表切片

列表名[0:3],从列表第一个开始,第三个结束(不包含第三个)

列表名[:3]列表第三个之前的所有子集(不包含第三个)

列表名[2:]列表第三个及以后的所有子集

列表名[:]整个列表

5,遍历切片

for player in players[:3]

6,复制列表:先创建包含整个列表的切片。

my_foods=['pizza',falafel','cake']

friend_foods=my_foods[:]

7,元组:python中不能修改值/元素的列表被称为元组。元组用圆括号标识。

如:a=(200,50),不能通过a[0]=250进行修改。

但可以通过给元组的变量赋值修改元组变量。

如a=(200,50)

a=(400,100)

新的赋值会代替之前的元组。

8,代码格式设置

格式设置指南:PEP 8.

缩进:每级缩进都使用4个空格;

行长:每行不超过80个字符(建议);

空行:不会影响代码运行,只会影响可读性。

第5章:if语句

1,条件测试

=赋值,如car='BMW'

==判断是否相等,返回布尔值。如car=='BMW'

其他:

!=

>=

<=

>

<

and

or

2,检查特定值是否包含在列表中:in

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']

>>>'mushrooms' in requested_toppings True

相应的,检查不包含:not in

3,if语句

1)if-elif-else语句:

这三句后面都要加冒号,总是以if开头,else只能出现在末尾,else可以省略,elif可以出现多次。执行完上一句后,判断余下的是否符合下面的条件。

age = 12


if age < 4:


 price = 0


elif age < 18:


 price = 5


elif age < 65:


 price = 10


else:


 price = 5


print("Your admission cost is $"+str(price)+".")

2)测试多个条件,多个if语句,重复添加不跳过。

requested_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in requested_toppings:

print("Adding mushrooms.")


if 'pepperoni' in requested_toppings:

print("Adding pepperoni.")


if 'extra cheese' in requested_toppings:


 print("Adding extra cheese.")
print("nFinished making your pizza!")

3)检查特殊元素:用for循环减少重复崇左,用if语句处理特殊状况。

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']


for requested_topping in requested_toppings:


if requested_topping == 'green peppers':

print("Sorry, we are out of green peppers right now.")


 else:


 print("Adding "+requested_topping+".")
print("nFinished making your pizza!")

4)使用多个列表:区别不大,修改if条件即可。

available_toppings = ['mushrooms', 'olives', 'green peppers', ❶
 'pepperoni', 'pineapple', 'extra cheese']

requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] ❷


for requested_topping in requested_toppings: ❸


if requested_topping in available_toppings: ❹


print("Adding "+requested_topping+".")


else: ❺


 print("Sorry, we don't have "+requested_topping+".")
print("nFinished making your pizza!")

第6章:字典

1,字典中的键-值对:key/values/items。例如:color为键,green为值,color:green为一组键-值对。

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

字典中的键-值对数量是可以有任意组的,并且没有存储先后顺序。

要访问字典中的值,如1中示例,print(alien_0['points'])即可。

2,添加键-值对,如示例,添加2对键值对到字典alien_0中。

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

print(alien_0)


alien_0['x_position'] = 0

alien_0['y_position'] = 25

print(alien_0)

3,修改字典中的值。如上例,直接输入alien_0['color']='yellow'即可。

4,删除键值对:del alien_0['points']。

5,遍历所有键值对

分别提取键和值:for key,value in alien_0.items():示例:

user_0 = {


'username': 'efermi',


 'first': 'enrico',


 'last': 'fermi',


}


for key, value in user_0.items():

print("nKey: "+key)


 print("Value: "+value) ❸

6,遍历所有的键

for k in name.keys():

按顺序(升序)遍历所有的键

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

7,遍历所有的值

for v in name.values():

遍历所有的值并剔除重复项

for v in set(name.values()):

8,嵌套

1)字典列表:字典在列表中。

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

alien_1 = {'color': 'yellow', 'points': 10}

alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:


 print(alien)

在列表中生成字典:

# 创建一个用于存储外星人的空列

aliens = []


# 创建30个绿色的外星人


for alien_number in range(30):

new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}


 aliens.append(new_alien)

2)在字典中存储列表:

pizza = {

'crust': 'thick',


 'toppings': ['mushrooms', 'extra cheese'],


}

这种时候,可以用多用一个for循环遍历字典

favorite_languages = {

'jen': ['python', 'ruby'],


'sarah': ['c'],


'edward': ['ruby', 'go'],


 'phil': ['python', 'haskell'],


}


for name, languages in favorite_languages.items():

print("n"+name.title()+"'s favorite languages are:")


 for language in languages:

print("t"+language.title())

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())

第7章:用户输入和while循环

1,input()输入的工作原理:让用户输入一些文本,然后将文本呈现给用户。

name=input('please enter your name:')

print('hello '+name+'!')

2,int():将数字的字符串转换为数值。

>>>age = input("How old are you? ")
How old are you? 21


>>>age = int(age)

>>>age >= 18


True

3,求模运算符(余数)%,例如:4%3=1,5%3=2.

4,while循环

和for循环的区别,前者针对集合中的每个元素的一个代码块,while循环会不断循环下去,直到指定条件不满足为止。

while的使用:

current_number = 1


while current_number <= 5:


print(current_number)


current_number+= 1

如果没有current_number+=1,该循环会不断执行下去,反复输出1,除非关掉python或者按Ctrl+c强行停止

5,while中的退出条件:给用户喊停的机会。

prompt = "nTell me something, and I will repeat it back to you:"


prompt+= "nEnter 'quit' to end the program. "


message = ""


while message != 'quit':


message = input(prompt)


 if message != 'quit':


print(message)

2)while中的使用标志

接上例:

active = True

while active:


 message = input(prompt)


if message == 'quit':

active = False


else:

print(message)

我们将变量active设置True,如果它为真,设置为false,后面不执行即可。

3)break退出

prompt = "nPlease enter the name of a city you have visited:"


prompt+= "n(Enter 'quit' when you are finished.) "


while True:

city = input(prompt)


 if city == 'quit':


break


 else:


print("I'd love to go to "+city.title()+"!")

6,while中的continue,只要满足就继续执行。

current_number = 0


while current_number < 10:


current_number+= 1

if current_number % 2 == 0:


continue


 print(current_number)

7,while在列表和字典中的使用

1)在列表间移动元素

# 首先,创建一个待验证用户列表


# 和一个用于存储已验证用户的空列表


unconfirmed_users = ['alice', 'brian', 'candace'] ❶


confirmed_users = []


# 验证每个用户,直到没有未验证用户为止


# 将每个经过验证的列表都移到已验证用户列表中


while unconfirmed_users:

current_user = unconfirmed_users.pop()

print("Verifying user: "+current_user.title())

confirmed_users.append(current_user)

# 显示所有已验证的用户


print("nThe following users have been confirmed:")


for confirmed_user in confirmed_users:


print(confirmed_user.title())

2)删除包含特定值的所有列表元素


pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']


print(pets)


while 'cat' in pets:


pets.remove('cat')


print(pets)

3)使用用户输入填充字典

略,不想写了。。。

第8章:函数

1,定义函数:def,如下示例,第一部分是函数名,第三部分是函数主体,第四部分是函数的执行。

def greet_user(username):


 """显示简单的问候语"""


print("Hello, "+username.title()+"!")

greet_user('jesse')

2,实参和形参:如上例,username为形参,是函数完成其工作所需要点一项信息。'Jesse'是一个实参,是调用函数时传递给函数的信息。实参被储存在形参中。

1)位置实参,和形参一一对应,可以调用多次,位置不能随意变动。

def describe_pet(animal_type, pet_name):


 """显示宠物的信息"""


print("nI have a "+animal_type+".")


 print("My "+animal_type+"'s name is "+pet_name.title()+".")

describe_pet('hamster', 'harry') ❷

2)关键字实参,与位置无关,直接描述形参对应的值。如上例,最后一行改为:describe_pet(animal_type='hamster', pet_name='harry')

3,默认值

编写函数时直接指定某形参的值,如下:


def describe_pet(pet_name, animal_type='dog'):

4,返回值

用return语句返回。

def get_formatted_name(first_name, last_name, middle_name=''): ❶


"""返回整洁的姓名"""


 if middle_name: ❷


full_name = first_name+' '+middle_name+' '+last_name


 else: ❸


full_name = first_name+' '+last_name


 return full_name.title()


musician = get_formatted_name('jimi', 'hendrix')


print(musician)


musician = get_formatted_name('john', 'hooker', 'lee') ❹


print(musician)

5,返回字典

def build_person(first_name, last_name):


 """返回一个字典,其中包含有关一个人的信息"""


person = {'first': first_name, 'last': last_name} ❶


return person ❷

6,函数和while循环结合使用

def get_formatted_name(first_name, last_name):


"""返回整洁的姓名"""


 full_name = first_name+' '+last_name


return full_name.title()


while True:


print("nPlease tell me your name:")


 print("(enter 'q' at any time to quit)")


 f_name = input("First name: ")


 if f_name == 'q':


break


 l_name = input("Last name: ")


if l_name == 'q':


break


formatted_name = get_formatted_name(f_name, l_name)


print("nHello, "+formatted_name+"!")

7,传递列表

def greet_users(names):


 """向列表中的每位用户都发出简单的问候"""


 for name in names:


msg = "Hello, "+name.title()+"!"


 print(msg)


usernames = ['hannah', 'ty', 'margot'] ❶


greet_users(usernames)

8,形参*toppings代表可以加入任意个实参。

def make_pizza(*toppings):


 """打印顾客点的所有配料"""


 print('nMaking a pizza with the following topping: ')

for topping in toppings:

print('- '+topping)


make_pizza('pepperoni')


make_pizza('mushrooms', 'green peppers', 'extra cheese')

9,将函数存储在模块中

1)导入整个模块

新建一个.py的文件,将某个函数模块出存在文件夹中,在其他文件中调用该模块。

如,创建一个pizza.py的文件,包含函数如下:

def make_pizza(size, *toppings):


 """概述要制作的比萨"""


print("nMaking a "+str(size)+
 "-inch pizza with the following toppings:")


for topping in toppings:

print("- "+topping)

在新的文件中调用该函数:

import pizza


pizza.make_pizza(16, 'pepperoni') ❶


pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

2)导入特定函数

from pizza import make_pizza

make_pizza(16, 'pepperoni')


make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

3)使用as命名:

命名函数:from pizza import make_pizza as mp

命名模块:import pizza as p

4)导入模块中所有函数所有函数

from pizza import *

第9章:类

1,创建和使用类class

如示例,class Dog():创建一个名为Dog的类,类的首字母要大写。

__init__():类中的函数称为方法,函数中的所有都适用于方法。唯一的差别是调用方法的方式。

该方法包含self、name、age3个形参,self必不可少且位于其他形参前面。用该方法创建Dog实例时将自动传入实参self,每个与类相关联的方法调用都自动传递实参self。self会自动传递,我们只需要提供最后两个实参的值。

class Dog(): ❶


 """一次模拟小狗的简单尝试""" ❷


def __init__(self, name, age): ❸


"""初始化属性name和age"""


self.name = name ❹


self.age = age


 def sit(self): ❺


"""模拟小狗被命令时蹲下"""


print(self.name.title()+" is now sitting.")


def roll_over(self):


"""模拟小狗被命令时打滚"""


 print(self.name.title()+" rolled over!")

Dog类的另两个方法sit()和roll_over()因为不需要额外的信息(名字和年龄),因此只有一个形参self。

2,根据类创建实例。

(此处的snip,是省略上面类中内容的意思)

class Dog():


--snip--


my_dog = Dog('willie', 6) ❶


print("My dog's name is "+my_dog.name.title()+".") ❷


print("My dog is "+str(my_dog.age)+" years old.") ❸

3,给属性设定默认值

如示例,self.odometer_reading=0

class Car():


def __init__(self, make, model, year):


"""初始化描述汽车的属性"""


self.make = make


self.model = model


self.year = year


self.odometer_reading = 0 ❶


def get_descriptive_name(self):


--snip--


def read_odometer(self): ❷


"""打印一条指出汽车里程的消息"""


print("This car has "+str(self.odometer_reading)+" miles on it.")


my_new_car = Car('audi', 'a4', 2016)

print(my_new_car.get_descriptive_name())


my_new_car.read_odometer()

4,修改属性的值,

1)在打印读数前把它修改为需要的值即可。

class Car():


 --snip--


my_new_car = Car('audi', 'a4', 2016)

print(my_new_car.get_descriptive_name())


my_new_car.odometer_reading = 23 ❶
my_new_car.read_odometer()

2)或者通过方法修改:

class Car():


 --snip--


 def update_odometer(self, mileage): ❶


"""将里程表读数设置为指定的值"""


self.odometer_reading = mileage


my_new_car = Car('audi', 'a4', 2016)

print(my_new_car.get_descriptive_name())


my_new_car.update_odometer(23) ❷
my_new_car.read_odometer()

5,继承

1)子类的方法:__init__()

例如,在上例Car类的基础上进行继承创建ElectricCar。


class Car(): ❶


"""一次模拟汽车的简单尝试"""


def __init__(self, make, model, year):


self.make = make


self.model = model


self.year = year


self.odometer_reading = 0


def get_descriptive_name(self):


long_name = str(self.year)+' '+self.make+' '+self.model


return long_name.title()


def read_odometer(self):


print("This car has "+str(self.odometer_reading)+" miles on it.")


def update_odometer(self, mileage):


if mileage >= self.odometer_reading:


self.odometer_reading = mileage


 else:


print("You can't roll back an odometer!")


def increment_odometer(self, miles):


self.odometer_reading+= miles


class ElectricCar(Car):


 """电动汽车的独特之处"""


 def __init__(self, make, model, year): ❸


"""初始化父类的属性"""


super().__init__(make, model, year) ❹



my_tesla = ElectricCar('tesla', 'model s', 2016) ❺


print(my_tesla.get_descriptive_name())

如示例,父类必须包含在当前文件中,且位于子类前面,父类又称为超类(superclass)。子类也可以修改,定义,重写父类的某些属性,和父类中的写法类似。

6,导入类。

1)from car import Car,打开模块car(car.py文件),并导入其中的Car类。

from car import Car ❶


my_new_car = Car('audi', 'a4', 2016)


print(my_new_car.get_descriptive_name())


my_new_car.odometer_reading = 23


my_new_car.read_odometer()

2)from car import Car, ElectricCar:

从一个模块导入多个类。

3)import car:导入整个模块

4)导入模块的所有类:from car import *

第10章:文件和异常

1,读取文件:with open(文件名)

如示例,以只读模式打开pi_digits.txt文件,并打印内容。

with open('pi_digits.txt') as file_object:


 contents = file_object.read()


 print(contents)

2,逐行读取:使用for循环(顺便消除了多余空行)

filename = 'pi_digits.txt' ❶


with open(filename) as file_object: ❷


for line in file_object: ❸


print(line.rstrip())

3,创建一个包含文件各行内容的列表

:用readlines()读取每一行并存储在列表中,然后存储到lines变量中。使用for循环打印各行。

filename = 'pi_digits.txt'


with open(filename) as file_object:


lines = file_object.readlines() ❶


for line in lines: ❷


print(line.rstrip())

4,写入文件

写入文件:调用open,以写入模式打开文件,并写入文字。

filename = 'programming.txt'


with open(filename, 'w') as file_object: ❶


file_object.write("I love programming.n")


file_object.write("I love creating new games.n")

这里的w为写入模式,读取模式:r;附加模式:a;能够读取和写入的模式:r+.

5,出现异常时,用try-except代码块处理。

1)ZeroDivisionError异常,出现该异常,即执行except模块

try:


print(5/0)


except ZeroDivisionError:


 print("You can't divide by zero!")

2)使用异常避免崩溃,保证继续执行,允许用户退出。

print("Give me two numbers, and I'll divide them.")


print("Enter 'q' to quit.")


while True:


first_number = input("nFirst number: ") ❶


if first_number == 'q':


 break


 second_number = input("Second number: ") ❷


 if second_number == 'q':


 break

try: ❶


answer = int(first_number) / int(second_number)


 except ZeroDivisionError: ❷


print("You can't divide by 0!")


else: ❸


 answer = int(first_number) / int(second_number) ❸


print(answer)

3)FileNotFoundError异常

filename = 'alice.txt'


try:


with open(filename) as f_obj:


contents = f_obj.read()


except FileNotFoundError:


 msg = "Sorry, the file "+filename+" does not exist."


print(msg)

6,分析文本:用split()确定整篇小说包含多少单词。

filename = 'alice.txt'


try:


 with open(filename) as f_obj:


 contents = f_obj.read()


except FileNotFoundError:


msg = "Sorry, the file "+filename+" does not exist."


 print(msg)


else:


# 计算文件大致包含多少个单词


words = contents.split() ❶


num_words = len(words) ❷


print("The file "+filename+" has about "+str(num_words)+" words.") ❸

7,使用多个文件,用counT_words()函数分析。

def count_words(filename):


 """计算一个文件大致包含多少个单词""" ❶


try:


with open(filename) as f_obj:


contents = f_obj.read()


 except FileNotFoundError:


 msg = "Sorry, the file "+filename+" does not exist."


print(msg)


 else:


# 计算文件大致包含多少个单词


words = contents.split()


 num_words = len(words)


print("The file "+filename+" has about "+str(num_words)+
 " words.")


filename = 'alice.txt'


count_words(filename)

只要后面把文件改为列表,就可以分析多个文件了。

8,存储数据

1)json.dump():接受实参,存储数据及可存储的文件对象。

import json


numbers = [2, 3, 5, 7, 11, 13]


filename = 'numbers.json' ❶


with open(filename, 'w') as f_obj: ❷


json.dump(numbers, f_obj) ❸

2)jason.load():读取数据到内存中。

import json


filename = 'numbers.json' ❶


with open(filename) as f_obj: ❷


numbers = json.load(f_obj) ❸


print(numbers)

3)保存和读取用户生成的数据

import json


# 如果以前存储了用户名,就加载它


# 否则,就提示用户输入用户名并存储它


filename = 'username.json'


try:


with open(filename) as f_obj: ❶


username = json.load(f_obj) ❷


except FileNotFoundError: ❸


username = input("What is your name? ") ❹


 with open(filename, 'w') as f_obj: ❺


json.dump(username, f_obj)


 print("We'll remember you when you come back, "+username+"!")


else:


print("Welcome back, "+username+"!")

第11章有时间再补充,多少字我没数,新人完结撒花~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值