当前位置:   article > 正文

【自用】python编程:从入门到实践_python编程从入门到实践

python编程从入门到实践

一、变量和简单数据类型

1.3 字符串

变量的命名只能包含字母、下划线和数字,数字不能打头
f字符串:f是format的简写,python会把花括号内的变量变换为其值
练习2-3 :个性化消息 用变量表示一个人的名字,并向其显示一条消息。显示的消息应非常简单,下面是一个例子。
Hello Eric,would you like to learn some Python today?

name = "Eric"
print("Hello %s,would you like to learn some Python today?" % name)
print(f"Hello {name},would you like to learn some Python today?")
  • 1
  • 2
  • 3

练习2-4 :调整名字的大小写 用变量表示一个人的名字,再以小写、大写和首字母大写的方式显示这个人名。

name = "liMing"
# 转小写
name = name.lower()
print(name.upper())
print(name.lower())
print(name.title())
'''
LIMING
liming
Liming
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

练习2-5 :名言 找一句你钦佩的名人说的名言,将其姓名和名言
打印出来。输出应类似于下面这样(包括引号)。
Albert Einstein once said,“A person who never made a mistake never tried anything new.”
练习2-6:名言2 重复练习2-5,但用变量famous
_person 表示名人的姓名,再创建要显示的消息并将其赋给变量message ,然后打印这条消息。

练习2-7 :剔除人名中的空白 用变量表示一个人的名字,并在其开头和末尾都包含一些空白字符。务必至少使用字符组合"\t"和"\n" 各一次。
打印这个人名,显示其开头和末尾的空白。然后,分别使用剔除函数lstrip() 、rstrip() 和strip() 对人名进行处理,并将结果打印出来。

# 加上空白
name = "liming"
name = "\t" + name + "\n"
print(name)
print(name.lstrip())
print(name.rstrip())
print(name.strip())
'''
	liming

liming

	liming
liming
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

1.4 数

练习2-8 :数字8 编写四个表达式,分别使用加法、减法、乘法和除法运算,但结果都是数字8。为使用函数调用print() 来显示结果,务必将这些表达式用圆括号括起来。

print((4+4))
print((9-1))
print((2*4))
print(int(24/3))
  • 1
  • 2
  • 3
  • 4

小结

大小写函数:
大写upper()
小写lower()
首字母大写title()
剔除空白函数:
左边剔除空白lstrip()
右边剔除空白rstrip()
全部剔除strip()

二、列表简介

3.1 列表定义

[]:表示列表,并用逗号分隔其中的元素,索引从0而不是1开始

练习3-3 :自己的列表 想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。根据该列表打印一系列有关这些通勤方式的宣言

list = ['bike','motorcycle','jeep']
for i in list:
    print("I would like to own a "+i)
  • 1
  • 2
  • 3

3.2 修改、添加和删除元素

  • list.append():在列表尾部添加元素
  • list.insert(idx,val):在列表的任意位置idx添加元素val
  • del list[idx]:删除列表中的元素
  • val = list.pop():删除列表最后一个元素并返回值
  • val = list.pop(idx):弹出列表中任何位置处的元素
  • list.remove(val):找到元素val在该列表的位置,并删除
    注释:方法 remove() 只删除第一个指定的值
party_participator = ['mother','father']
party_participator.insert(0,'brother')
party_participator.insert(3,'uncle')
party_participator.append('sister')
del party_participator[0]
party_participator.pop()
party_participator.pop(2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.2 组织列表

  • list.sort():对列表永久排序

  • list.sort(reverse=True):对列表降序排序

  • sorted(list):对列表临时排序

  • list.reverse():倒着打印列表

  • len(list):列表长度

  • set():找出列表中独一无二的元素构成一个字典({}表示)

place=['beijing','dali','weihai','xian']

print(sorted(place))	#临时排序
place.sort()	#永久排序
place.reverse()	#顺序颠倒
print(len(place))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

三、操作列表

3.1 遍历整个列表

使用for循环,从列表中从前往后依次取出一个元素赋给fruit,执行相同的操作,注意缩进:

places=['beijing','dali','weihai','xian']

for place in places:
	print(place)
  • 1
  • 2
  • 3
  • 4

3.2 创建数值列表

使用range()函数,从开始的数到结束的数的前一个数
for value in range(1,5)		#从1到4
	print(value)
创建数字列表,list()将结果转化为列表
numbers=list(range(1,6))	#从1到5
print(numbers)

numbers=list(range(1,10,2))	#加入步长,列表相邻的数值相差2
print(numbers)
对数字列表进行简单的统计运算
numbers=[1,2,3,4,5,6,7,8,9,10]
print(min(numbers))	#列表最小值
print(max(numbers))	#列表最大值
print(sum(numbers))	#对列表元素求和
列表解析:将for循环和创建新元素的代码合并成一行
squares=[value**2 for value in range(1,11)]
print(squares)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

练习 4-9 :立方解析 使用列表解析生成一个列表,其中包含前 10 个整数的立方。

list = [i**3 for i in range(1,11)]
  • 1

3.3 使用列表的一部分

切片
fruits=['apple','orange','banana','pear']

print(fruits[0:3]) #该切片包含从0到2三个元素
for fruit in fruits[0:3]:
	print(fruit)
复制列表:**[:]在新列表上进行的操作对原列表无影响**
fruits=['apple','orange','banana','pear']
copy_fruits=fruits[:]
print(copy_fruits)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.4 元组

使用圆括号而非列表使用的方括号
元组的元素不可修改
numbers=(1,2,3,4,5)
for number in numbers:
	print(number)
  • 1
  • 2
  • 3
  • 4
  • 5

四、if 语句

4.1 if 语句

  1. if-else:要么执行if语句,要么执行else语句
  2. if-elif-else:多个条件测试

4.2 条件测试

  1. ==:判断两个值是否相等
  2. !=:判断两个值是否不等
  3. < >= <= >:数值比较
  4. and or :检查多个比较
  5. 布尔表达式:结果要么为True,要么为False
fruits=['apple','orange','banana','pear']
fruit='apple'

if fruit in fruits:
	print("Get it!")
else :
	print("Error!")
	
if fruit == 'apple':
	print("fruit is apple")
elif fruit == 'orange':
	print("fruit is orange")
else:
	print("Cannot find it!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

五、字典

5.1 使用字典

键和值之间用冒号分割,而键值对之间用逗号分隔

使用get()来访问值,如果字典中有键'height',则返回对应的值,否则返回'No point value assigned.'
alien={'color':'green','point':5}
value=alien.get('height','No point value assigned.')
print(value)

  • 1
  • 2
  • 3
  • 4
  • 5

5.2 遍历字典

遍历所有键值对items(),返回一个键值对列表
遍历所有键keys()
遍历所有值values()

alien={'color':'green','point':5}
for key,value in alien.items():
	print(f"key:{key},value:{value}")
  • 1
  • 2
  • 3

练习6-5 :河流 创建一个字典,在其中存储三条重要河流及
其流经的国家。例如,一个键值对可能是’nile’: ‘egypt’。
使用循环为每条河流打印一条消息,下面是一个例子。
The Nile runs through Egypt.
使用循环将该字典中每条河流的名字打印出来。
使用循环将该字典包含的每个国家的名字打印出来。

river = {'nile':'epypt','changjiang':'China','amazon':'peru'}
for name,country in river.items():
	print("The "+name.title()+" runs through "+country.title()+".")
  • 1
  • 2
  • 3

5.3 嵌套

练习6-11 :城市 创建一个名为cities 的字典,将三个城市
名用作键。对于每座城市,都创建一个字典,并在其中包含该
城市所属的国家、人口约数以及一个有关该城市的事实。在表
示每座城市的字典中,应包含country 、population 和fact
等键。将每座城市的名字以及有关信息都打印出来。


cities = {
    'beijing': {
        'country': 'China',
        'population': 2189,
        'fact': "Beijing is China's capital."
    },
    'new york': {
        'country': 'America',
        'population': 880,
        'fact': "New york is America's capital."
    },
    'tokyo': {
        'country': 'Japan',
        'population': 3750,
        'fact': "Tokyo is Japan's capital."
    }
}
for city, ifo in cities.items():
    print("The city is " + city + "." + city + " is from " + ifo[
        'country'] + f"and its population is {ifo['population']}")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

六、用户输入与while循环

6.1 函数input()

  1. input()让程序暂停运行,等待用户输入一些文本
  2. int()获取数值输入
  3. 求模运算符%,将两个数相除并返回余数
height=input("How tall are you?")
height=int(height)

if(height>160):
    print("\nYou are enough height to ride!")
else:
    print("\nYou didn't reach the height to ride!")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

6.2 使用while循环

for循环用于针对集合中的每个元素都执行一个代码块,而while循环则不断运行,直到指定的条件不再满足
break:不再执行余下的代码并退出整个循环
continue:不再执行余下的代码并返回至循环开头
练习7-5 :电影票 有家电影院根据观众的年龄收取不同的票
价:不到3岁的观众免费;3~12岁的观众收费10美元;超过12
岁的观众收费15美元。请编写一个循环,在其中询问用户的年
龄,并指出其票价。

prompt = "Please input your age,if you want to quit,please input quit."
while True:
    age = input(prompt)
    if age == "quit":
        break
    else:
        if int(age) in range(4, 13):
            print("pay 10")
        elif int(age) < 3:
            print("free")
        else:
            print("pay 15")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

6.3 使用while循环处理列表和字典

在列表之间移动元素

users=['Bob','Alice','Joey']
new_users=[]

while users:
    user=users.pop()
    new_users.append(user)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

删除为特定值的所有列表元素

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
  • 1
  • 2
  • 3
  • 4
  • 5

使用用户输入来填充字典

responses={}
flag=True

while flag!='no':
    name=input("What's your name:")
    response=input("Do you like Basketball(yes/no):")
    responses[name]=response
    flag=input("anyone else?(yes/no):")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

七、函数

关键字实参 是传递给函数的名称值对。因为直接在实参中将名称
和值关联起来,所以向函数传递实参时不会混淆。

def describe
_
pet(animal_type, pet_name):
"""
显示宠物的信息。"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe
_
pet(animal_type='hamster', pet_name='harry')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

形参指定默认值后,可在函数调用中省去相应的实参

def pet(name,type='dog'):	#'type'为默认值
    print(f"Its name is {name}\nIts type is {type}")
pet('Dabai')
  • 1
  • 2
  • 3

7.1 传递任意数量的形参

形参名*toppings 中的星号让Python创建一个名为toppings 的空
元组,并将收到的所有值都封装到这个元组中。
必须在函数定义中将接纳任意数量实参的形参放在最后

def make_pizza(*toppings):
"""
打印顾客点的所有配料。
"""
	print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

7.2 使用任意数量的关键字实参

def build_profile(first, last, **user_info):
"""
创建一个字典,其中包含我们知道的有关用户的一切。
"""
	user_info['first_name'] = first
	user_info['last_name'] = last
	return user_info
user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

小结

  • python中有 两种 多值参数:
    • 参数名前增加 一个 * 可以接收 元组
    • 参数名前增加 一个 ** 可以接收 字典
  • 一般在给多值参数命名时,习惯使用以下两个名字
    • *args —— 存放 元组 参数,前面有一个*
    • **kwargs —— 存放 元组 参数,前面有两个*
  • argsarguments 的缩写,有变量的含义
  • kwkeywords 的缩写,kwargs 可以记忆键值对参数
def demo(num, *args, **kwargs):
    print(num)
    print(args)
    print(kwargs)

demo(1, 2, 3, 4, 5, name="小明", age=18, gender=True)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

八、类

在这里插入图片描述
初始化对象:

  • 初始化方法就是__init__方法,__init__是对象的内置方法
  • __init__方法是专门用来定义一个类有哪些属性的方法

例子:

class Cat:

    def __init__(self, name):
        print("初始化方法 %s" % name)
        self.name = name
    
tom = Cat("Tom")
lazy_cat = Cat("大懒猫")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

8.1 根据类创建实例

练习9-1 :餐馆 创建一个名为Restaurant 的类,为其方法__init__()设置属性restaurant_name 和cuisine_type 。创建一个名为describe_restaurant() 的方法和一个名为open_restaurant() 的方法,前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。
根据这个类创建一个名为restaurant 的实例,分别打印其两个属性,再调用前述两个方法。

class Restaurant:
    def __init__(self):
        self.restaurant_name = "Dali Restaurant"
        self.cuisine_type = "bo cai"

    def describe_restaurant(self):
        print("This is " + self.restaurant_name)
        print("You can eat " + self.cuisine_type)

    def open_restaurant(self):
        print("Welcome to " + self.restaurant_name)


new = Restaurant()
new.describe_restaurant()
new.open_restaurant()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

8.2 修改属性的值

练习9-4 :就餐人数
在为完成练习9-1而编写的程序中,添加一个名为number_served 的属性,并将其默认值设置为0。根据这个类创建一个名为restaurant 的实例。打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。添加一个名set_number_served() 的方法,让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。添加一个名为increment_number_served() 的方法,让你能够将就餐人数递增。调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就餐人数。

class Restaurant:
    def __init__(self):
        self.restaurant_name = "Dali Restaurant"
        self.cuisine_type = "bo cai"
        self.number_served = 0

    def describe_restaurant(self):
        print("This is " + self.restaurant_name)
        print("You can eat " + self.cuisine_type)

    def open_restaurant(self):
        print("Welcome to " + self.restaurant_name)

    def set_number_served(self, number):
        self.numbers = number
        print(f"Set the number for dinner: {self.numbers}")
    def increment_number_served(self, number):
        self.numbers += number
        print(f"Set the number for dinner: {self.numbers}")

restaurant = Restaurant()
number = 2
restaurant.set_number_served(number)
number = 20
restaurant.increment_number_served(number)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

8.3 继承

继承的语法:

class 类名(父类名):

    pass

  • 1
  • 2
  • 3
  • 4

super()可以调用父类的方法

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 = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        print(f"This car has {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)
        self.battery_size = 75

    def describe_battery(self):
        print(f"This car has a {self.battery_size} -kWh battery.")

my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

将实例用作属性

一个名为Battery 的类中,并将一
个Battery 实例作为ElectricCar 类的属性


class Battery:
    def __init__(self,battery_size = 75):
        self.battery_size= battery_size
    def describe_battery(self):
        print(f"AAA This car has a {self.battery_size}-kWh battery.")



class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()

my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

练习9-9 :电瓶升级
在本节最后一个electric_car.py版本中,给Battery 类添加一个名为upgrade_battery() 的方法。该方法检查电瓶容量,如果不是100,就将其设置为100。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range() ,然后对电瓶进行升级,并再次调用get_range() 。你将看到这辆汽车的续航里程增加了。


class Battery:
    def __init__(self, battery_size=75):
        self.battery_size = battery_size

    def describe_battery(self):
        print(f"This car has a {self.battery_size}-kWh battery.")

    def get_range(self):
        """
        打印一条消息,指出电瓶的续航里程。"""

        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315
        print(f"This car can go about {range} miles on a full charge.")

    def upgrade_battery(self):
        if self.battery_size != 100:
            self.battery_size = 100


class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()


my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

8.4 Python标准库

生成一个位于1和6之间的随机整数
randint() 随机生成一个整数

from random import randint
randint(1,6)
  • 1
  • 2

choice()将一个列表或元组作为参数,并随机返回其中的一个元素

from random import choice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
first_up = choice(players)
  • 1
  • 2
  • 3

练习9-14 :彩票
创建一个列表或元组,其中包含10个数和5个字母。从这个列表或元组中随机选择4个数或字母,并打印一条消息,指出只要彩票上是这4个数或字母,就中大奖了。

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
str = ""
win = [choice(list) for i in range(0, 4)]
print(win)
  • 1
  • 2
  • 3
  • 4

练习9-15 :彩票分析
可以使用一个循环来明白前述彩票大奖有多难中奖。为此,创建一个名为my_ticket 的列表或元组,再编写一个循环,不断地随机选择数或字母,直到中大奖为止。请打印一条消息,报告执行循环多少次才中了大奖。

from random import choice

def lucky_number(num_list):
    """这个函数用来生成中奖彩票号码"""
    # 这个列表用来存储随机选出的号码
    luck_number_list=[]
    # 如果列表里的数不足四个,循环获取号码
    while len(luck_number_list) < 4:
        choice_number=choice(num_list)
         # 判断获取到的号码是否已经重复,如果不重复,添加到列表当中
        if choice_number not in luck_number_list:
            luck_number_list.append(choice_number)
    # 返回获奖列表
    return luck_number_list

def wining(lucky_num,my_number):
    """这个函数用来判断是否中奖,返回True 或者 false"""
    for values in my_number:
        if values not in lucky_num:
            # 一旦有一个数不在中奖列表里就返回false
            return False
    return True

def number(the_lucky_number,the_holl_number):
    """这个函数用来模拟循环多少次才能中奖"""
    n=0
    # n用来计算循环次数
    while True:
        my_ticket=lucky_number(the_holl_number)
        #调用luck_numer函数随机生成彩票
        if wining(the_lucky_number,my_ticket):
            print("恭喜中奖")
            print(f"中奖号码为{my_ticket},这是第{n}张彩票")
            break
        else:
            n+=1

number_list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
the_luck_number=lucky_number(number_list)
number(the_luck_number,number_list)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

九、文件和异常

常规操作文件代码:

# 1. 打开 - 文件名需要注意大小写
file = open("README.txt")

# 2. 读取
text = file.read()
print(text)

# 3. 关闭
file.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

如果文件无法正确打开,直接抛出异常,不会关闭文件。
with语句自动管理上下文,不管什么原因跳出with语句,都能保证正确关闭资源

with open("README.txt") as f:   
    data= f.read()
    print(data)
  • 1
  • 2
  • 3

9.1 逐行读取

#每行末尾都有两个换行符,一个来自文件,另一个来自函数调用print() 要消除这些多余的空白行,可在函数调用print() 中使用rstrip()
with open("README.txt") as file_object:
	for line in data:
		print(line)
  • 1
  • 2
  • 3
  • 4
# readline()返回一个字符串,readlines()返回一个列表
with open("README.txt") as file_object:
	data = file_object.readlines()
for line in data:
	print(line)
  • 1
  • 2
  • 3
  • 4
  • 5

9.2 写入文件

Python只能将字符串写入文本文件。要将数值数据存储
到文本文件中,必须先使用函数str() 将其转换为字符串格
式。

filename = "test.txt"
with open(filename,'w+') as file_object:
	file_object.wirte("I love python.")
  • 1
  • 2
  • 3

参数说明
练习10-3 :访客 编写一个程序,提示用户输入名字。用户做
出响应后,将其名字写入文件guest.txt中。

file_name = "guest.txt"
name  = input("Please input your name.")
with open(filename,'w') as files:
	fils.write(name.title()+"\n")
  • 1
  • 2
  • 3
  • 4

9.3 使用try-except代码处理异常

处理ZeroDivisionError 异常

try:
	print(5/0)
except ZeroDivisionError:
	print("You can't divide by zero!")
  • 1
  • 2
  • 3
  • 4

处理FileNotFoundError 异常

filename = 'alice.txt'
try:
	with open(filename, encoding='utf-8') as f:
		contents = f.read()
except FileNotFoundError:
	print(f"Sorry, the file {filename} does not exist.")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

分析文本:split() 以空格为分隔符将字符串分拆成多个部分,并将这些
部分都存储到一个列表中。

filename = 'alice.txt'
try:
	with open(filename, encoding='utf-8') as f:
		contents = f.read()
except FileNotFoundError:
	print(f"Sorry, the file {filename} does not exist.")
else:
# 计算该文件大致包含多少个单词。
	words = contents.split()
	num_words = len(words)
	print(f"The file {filename} has about {num_words} words.")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

练习10-6 :加法运算 提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数。在此情况下,当你尝试将输入转换为整数时,将引发ValueError 异常。编写一个程序,提示用户输入两个数,再将其相加并打印结果。在用户输入的任何一个值不是数时都捕获ValueError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数,再输入一些文本而不是数。


while True:
	first_num = input("Please input the first number.")
	second_num = input("Please input the second number.")
	try:
		first_num = int(first_num)
	except ValueError:
		print("Error! Please input ZHENGSHU")
	else:
		try:
			second_num = int(second_num )
		except ValueError:
			print("Error! Please input ZHENGSHU")
		else:
			print(f"The output is {first_num+second_num}")
			break
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

9.4 存储数据

使用json.dump() 和json.load()

import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f:
	json.dump(numbers, f)
  • 1
  • 2
  • 3
  • 4
  • 5

十、测试代码

一个帮助管理匿名调查的类

class AnonymousSurvey:
    def __init__(self, question):
        """存储一个问题,并为存储答案做准备。"""
        self.question = question
        self.responses = []

    def show_question(self):
        """显示调查问卷"""
        print(self.question)

    def store_response(self, new_response):
        self.responses.append(new_response)

    def show_results(self):
        print("Survey results:")
        for reponse in self.responses:
            print(f".{reponse}")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

一个使用匿名调查类的程序

from survey import AnonymousSurvey

question = "What is your favourite language?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    reponse = input("Language: ")
    if reponse != 'q':
        my_survey.store_response(reponse)
    else:
        break
print("\n Thank you to everyone who participated in the survey!")
my_survey.show_results()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

测试AnonymousSurvey 类

import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
    def test_store_single_response(self):
        question = "What is your favourite language?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')
        self.assertIn('English',my_survey.responses)
    def test_store_three_responses(self):
        question = "What is your favourite language?"
        my_survey = AnonymousSurvey(question)
        reponses = ['English','Spanish','Chinese']
        for reponse in reponses:
            my_survey.store_response(reponse)
        for reponse in reponses:
            self.assertIn(reponse,my_survey.responses)
if __name__ == '__main__':
    unittest.main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

十一、附加内容

11.1 lambda 函数

lambda介绍
if 函数案例:

get_odd_even = lambda x : "偶数" if x % 2 == 0 else "奇数"
  • 1

无参数表达式

x = lambda : "I love Python!!!"
  • 1

列表排序

a = [(1,'b'),(3,'c'),(2,'d')]
a.sort(key = lambda x :x[0])
  • 1
  • 2

map方法+lambda
map(function,iterable,…)
第一个参数接受一个函数名,后面的参数接受一个或多个可迭代的序列,返回的是一个map对象,需要人工转成list。

# def函数写法
def add(num):
    return num ** 2

x = map(add, [1, 2, 3, 4, 5])
print(list(x))
print("----------这是一个分割线----------")

# lambda函数写法
y = map(lambda num: num ** 2, [1, 2, 3, 4, 5])
print(list(y))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

filter方法+lambda

x = filter(lambda num: num % 2 == 0, range(10))
print(list(x))
# [0, 2, 4, 6, 8]`
  • 1
  • 2
  • 3

十二、数据分析

12.1 numpy函数

numpy对象
>>> import numpy as np
# 列表
>>> t1 = np.array([1,2,3])
>>> print(t1)
[1 2 3]
# 迭代对象
>>> t2 = np.array(range(10))
>>> print(t2)
[0 1 2 3 4 5 6 7 8 9]
>>> print(type(t2))
<class 'numpy.ndarray'>

>>> t3 = np.arange(10)
>>> print(t3)
[0 1 2 3 4 5 6 7 8 9]
>>> print(type(t3))
<class 'numpy.ndarray'>

>>> t4 = np.arange(2,10,2)
>>> print(t4)
[2 4 6 8]
>>> print(type(t4))
<class 'numpy.ndarray'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

索引和切片

>>> t = np.arange(0,20).reshape(5,4)
>>> t
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> # 取行
>>> t[0]
array([0, 1, 2, 3])
>>> # 取连续多行
>>> t[:2]
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> t[2:]
array([[ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> # 取不连续的多行
>>> t[[2,4]]
array([[ 8,  9, 10, 11],
       [16, 17, 18, 19]])
>>> # 取列
>>> t[:,0]
array([ 0,  4,  8, 12, 16])
>>> # 取连续的多列
>>> t[:,:2]
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13],
       [16, 17]])
>>> t[:,2:]
array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15],
       [18, 19]])
>>> # 取不连续多列
>>> t[:,[0,2]]
array([[ 0,  2],
       [ 4,  6],
       [ 8, 10],
       [12, 14],
       [16, 18]])
>>> # 取行列(第3行,第4列)
>>> t[2,3]
11
>>> # 取多行多列(第3-5行,第2-4列)
>>> t[2:5,1:4]
array([[ 9, 10, 11],
       [13, 14, 15],
       [17, 18, 19]])
>>> # 取多个不相邻的点(0,0)(2,1)
>>> t[[0,2],[0,1]]
array([0, 9])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
布尔操作
>>> t = np.arange(0,20).reshape(5,4)
>>> t
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
# 布尔索引
>>> t<10
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True, False, False],
       [False, False, False, False],
       [False, False, False, False]])
>>> # 取数组中大于10的值
>>> t[t>10]
array([11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> # 取数组中小于10的值
>>> t[t<10]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
numpy操作进阶
'''临时修改数组形状'''
# reshape()
a = np.array([[1,2,3,4],[5,6,7,8]])
a.reshape(4,2)
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
# 只是临时修改形状
a.shape
(2, 4)
>>> c = np.array([[1, 2],[3, 4],[5, 6],[7, 8]])
>>> c
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
>>> c.shape
(4, 2)

'''展平numpy数组'''
# 方法1
a.reshape(a.shape[0]*a.shape[1],)
array([1, 2, 3, 4, 5, 6, 7, 8])
#  方法2
a.flatten()
array([1, 2, 3, 4, 5, 6, 7, 8])

'''转置numpy数组'''
t
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

t.transpose()
array([[ 0,  6, 12],
       [ 1,  7, 13],
       [ 2,  8, 14],
       [ 3,  9, 15],
       [ 4, 10, 16],
       [ 5, 11, 17]])
t.swapaxes(1,0)
array([[ 0,  6, 12],
       [ 1,  7, 13],
       [ 2,  8, 14],
       [ 3,  9, 15],
       [ 4, 10, 16],
       [ 5, 11, 17]])
t.T
array([[ 0,  6, 12],
       [ 1,  7, 13],
       [ 2,  8, 14],
       [ 3,  9, 15],
       [ 4, 10, 16],
       [ 5, 11, 17]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
'''拼接numpy数组'''
t1 = np.arange(0,12).reshape(2,6)
t2 = np.arange(12,24).reshape(2,6)
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])
array([[12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])
np.vstack((t1,t2)) # 竖直拼接 沿着列的方向,对行进行拼接
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]]) 
np.hstack((t1,t2)) # 水平拼接 沿着行的方向,对列进行拼接
array([[ 0,  1,  2,  3,  4,  5, 12, 13, 14, 15, 16, 17],
       [ 6,  7,  8,  9, 10, 11, 18, 19, 20, 21, 22, 23]])
'''裁剪numpy数组'''
t = np.arange(0,20).reshape(5,4)
t
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
t.clip(9,10) # 小于9的修改为9,大于10的修改为10
array([[ 9,  9,  9,  9],
       [ 9,  9,  9,  9],
       [ 9,  9, 10, 10],
       [10, 10, 10, 10],
       [10, 10, 10, 10]])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
numpy常用小方法
'''获得最大值最小值位置'''
# 一维数组 返回索引
>>> t1
array([11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> np.argmax(t1,axis=0) #返回最大值索引
8
>>> np.argmin(t1,axis=0) #返回最小值索引
0

# 多维数组 返回每行的最大或最小值
>>> t2 = np.arange(0,16).reshape(4,4)
>>> t2
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> np.argmax(t2,axis=0)
array([3, 3, 3, 3], dtype=int64)
>>> np.argmin(t2,axis=0)
array([0, 0, 0, 0], dtype=int64)
'''生成随机数组'''
np.random.randint(low,high,(shape))
# 从给定上下限范围选取随机数整数,范围是low,high,shape是形状
>>> np.random.randint(10,20,(3,3))
array([[13, 15, 18],
       [18, 17, 15],
       [15, 10, 12]])
>>> np.random.randint(10,20,(3,3))
array([[17, 12, 16],
       [10, 10, 14],
       [15, 14, 12]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
numpy常用函数大全

numpy常用函数大全

'''字符串函数'''
# 每一个字符串改成首字母大写
>>> import numpy as np
>>> print(np.char.title(['hello python']))
['Hello Python']
# 每一个字符串改成纯小写
>>> import numpy as np
>>> print(np.char.lower(['hello python']))
['hello python']
# 每一个字符串改成纯大写
>>> import numpy as np
>>> print(np.char.upper(['hello python']))
# 按照分隔符对字符串进行分割,并返回数组列表
>>> import numpy as np
>>>
>>> print(np.char.split(['Hello Python'], sep=' '))
[list(['Hello', 'Python'])]


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号