《Python编程从入门到实践》第一部分 基础知识


目录


一、变量和简单数据类型

1.输出

print("hello world")
message = "hello world" 
print(message)

2.字符串

 "hello world" 
 'hello world'
 "hello ‘world’" 

大小写

message = "hello world"
print(message.title())               # Hello World
print(message.upper())              # HELLO WORLD
print(message.lower())              # hello world

合并字符串

firstname = "ada"
lastname = "lovelace"
fullname = firstname + " " +lastname
print(fullname.title())          # Ada  Lovelace

使用制表符或者换行符添加空白:\t\n
删除空白
尾部 .rstrip()
头部 .lstrip()
两端 .strip()

3.数字

直接:+-*/
乘方:** 3**2  9
小数:2*0.1  0.2 但是包含的小数位不确定 0.2+0.1 =  0.300000000004
str()避免类型错误 
age = 23
message = "Happy " + str(age) +"rd Birthday!"

二、列表

1.增删改

访问

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)   #['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])   #trek
print(bicycles[-1])  #specialized

修改

bicycles[0] = 'moto'
print(bicycles[0])#moto
print(bicycles)#['moto', 'cannondale', 'redline', 'specialized']

插入

bicycles.append('homdo')
print(bicycles)#['moto', 'cannondale', 'redline', 'specialized', 'homdo']
bicycles.insert(0,'ducaati')
print(bicycles)#['ducaati', 'moto', 'cannondale', 'redline', 'specialized', 'homdo']

删除

del bicycles[0]
print(bicycles) #['moto', 'cannondale', 'redline', 'specialized', 'homdo']
popped_bicycle = bicycles.pop()
print(bicycles)  #['moto', 'cannondale', 'redline', 'specialized']
print(popped_bicycle)  #homdo
popped_bicycle = bicycles.pop(0)
print(bicycles)  #['cannondale', 'redline', 'specialized']
print(popped_bicycle)  #moto

#根据值删元素
bicycles.remove('redline')
print(bicycles)#['cannondale','specialized']

2.组织列表

永久排序

cars = ['bmw','audi','toyota','sub']

#按字母顺序排序
cars.sort()
print(cars)#['audi', 'bmw', 'sub', 'toyota']

#按字母顺序相反排序
cars.sort(reverse=True)
print(cars)#['toyota', 'sub', 'bmw', 'audi']

临时排序

cars = ['bmw','audi','toyota','sub']
print(sorted(cars))#['audi', 'bmw', 'sub', 'toyota']

#倒着打印列表
cars.reverse()#永久性
print(cars)#['sub', 'toyota', 'audi', 'bmw']

#确定列表长度
print(len(cars))

3.操作列表

1.遍历整个列表

cars = ['bmw','audi','toyota','sub']
for car in cars: #list_of_items item
    print(car)

2.创建数值列表

#遍历
for value in range(1,5):#到达5时停止
    print(value)     #1 2 3 4
    
#使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)#[1, 2, 3, 4, 5]

#使用range()指定步长
even_numbers = list(range(2,11,2))
print(even_numbers)#[2, 4, 6, 8, 10]

3.对数字列表进行简单统计

digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))#0
print(max(digits))#9
print(sum(digits))#45

4.列表解析(只需编写一行代码就能生成这样的列表)

squares = [value**2 for value in range(1,11)]
print(squares)  #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

5.切片(处理列表部分元素)

cars = ['bmw','audi','toyota','sub','auv']

#切片
print(cars[0:3]) #['bmw', 'audi', 'toyota']
print(cars[1:4]) #['audi', 'toyota', 'sub']
print(cars[:4]) #['bmw', 'audi', 'toyota', 'sub']
print(cars[2:]) #['toyota', 'sub', 'auv']
print(cars[-3:]) #['toyota', 'sub', 'auv']

#遍历切片
for car in cars[:3]:
    print(car)

#复制列表
my_cars = cars[:]
print(my_cars) #['bmw', 'audi', 'toyota', 'sub', 'auv']

6.元组(不可变的列表)

dimensions = (200,50)
print(dimensions[0]) #200
print(dimensions[1]) #50
for dimension in dimensions:
     print(dimension) #200 50
     
#修改元组变量——只能重新定义整个元组
dimensions = (400,100)
for dimension in dimensions:
     print(dimension) #400 100

三、字典

1.访问修改

alien = {'color':'red','points':5}

#访问字典中的值
print(alien['color']) #red
#添加键-值对
alien['x_pos'] = 0
alien['y_pos'] = 25
print(alien)#{'color': 'green', 'points': 5, 'x_pos': 0, 'y_pos': 25}

#修改键值对的值
alien['color'] = 'green'

#删除键值对
del alien['points']
print(alien)#{'color': 'green', 'x_pos': 0, 'y_pos': 25}

#类似对象组成的字典
favorite_languages = {
        'jen':'python',
        'sarah':'c',
        'edward':'ruby',
        'phil':'python',
        }
print(favorite_languages)#{'jen': 'python', 'sarah': 'c', 'edward': 'ruby'}

2.遍历

#遍历键值对
for k,v in favorite_languages.items():
    print("\nkey:"+ k)
    print("value:"+v)

#遍历字典中所有键
for key in favorite_languages.keys():
    print(key.title())

#按顺序遍历字典中的所有键
for key in sorted(favorite_languages.keys()):
    print(key.title())    

#遍历字典中的所有值
for language in favorite_languages.values():
    print(language.title())

#集合—剔除重复项
for language in set(favorite_languages.values()):
    print(language.title())

3.遍历字典列表

alien_0 = {'color':'red','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'green','points':15}

aliens = [alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)
"""
{'color': 'red', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'green', 'points': 15}
"""
aliens = []
#创建30个外星人
for alien_number in range(0,30):
    new_alien = {'color':'red','points':5}
    aliens.append(new_alien)

#修改前三个外星人
for alien in aliens[0:3]:
    if alien['color'] == 'red':
        alien['color'] = 'green'
        alien['points'] = 10
#显示前五个外星人
for alien in aliens[0:5]:
    print(alien)

4.在字典中存储列表

favorite_languages = {
        'jen':['python','ruby'],
        'sarah':['c'],
        'edward':['ruby','go'],
        'phil':['python','haskell'],
        }
for name,languages in favorite_languages.items():
    print("\n"+ name.title())
    for language in languages:
        print("\t" + language.title())

5.在字典中存储字典

users = {
        'amy':{
                'first':'albert',
                'last':'einstein',
                },
        'bob':{
                'first':'marie',
                'last':'curie',
                },
        }
        
for username,user_info in users.items():
    print("\n"+username)
    print(user_info['first']+" "+user_info['last'])

四、if语句、用户输入和while循环

1.if语句(and or in not in > >= < <= ==)

cars = ['bmw','audi','toyota','sub']

for car in cars:
    if car.lower() == 'bmw':  #判断相等时候区分大小写
        print(car.upper()) 
    elif car == 'SUB':
    	print(car.lowwer())
    else:
        print(car.title())

2.input()输入

age = input("how old are you? ")
age = int(age)
if age <= 18:
    print("You look lovely")

3.while 循环(可用break continue)

prompt = "\nenter 'quit to end the program."
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

五、函数

1.定义函数 def

#函数
def my_pet(pet,name):
    print("\nI have a " + pet + "," + name + ".")
my_pet('dog','Bob')

#关键字实参
def my_pet(pet,name):
    print("\nI have a " + pet + "," + name + ".")
my_pet(pet='dog',name='Bob') 

#默认值
def my_pet(name,pet='dog'):
    print("\nI have a " + pet + "," + name + ".")
my_pet(name='Bob')    

#让实参变成可选的
def get_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()
name = get_name('bob','lee')
print(name)

#返回字典
def build_person(first_name,last_name,age=''):
    person = {'first':first_name,'last':last_name}
    if age:
        person['age'] = age
    return person
message = build_person('amy','Davil',age=27)
print(message)

#传递列表
def greet_users(names):
    for name in names:
        print("hello,"+name)
usernames = ['Amy','Bob','Smith']
greet_users(usernames)


unprinted_designs = ['iphone','robot','pendant']
completed_modles = []
def print_models(unprinted_designs,completed_modles):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(current_design)
        completed_modles.append(current_design)
def show_completed_models(completed_models):
    for completed_modle in completed_modles:
        print(completed_modle)
print_models(unprinted_designs,completed_modles)
show_completed_models(completed_models)
#禁止函数修改列表 将列表副本传给函数 切片表示法[:]创建列表副本
print_models(unprinted_designs[:],completed_modles)

#传递任意数量的实参
def make_pizza(*toppings):
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','pepperoni','green peppers')
#*toppings中的*让python创建一个名为toppings的空元组,并将收到的所有值都封装在这个元组中


#使用任意数量的关键字实参 将函数编写成能接受任意数量的键值对
def build_person(first,last,**user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_person('amy','Davil',loc='China',field='physics')
print(user_profile)

2.将函数储存在模块中

#导入整个模块
#pizza.py
def make_pizza(size,*toppings):
    print("Making a "+str(size)+" pizza")
    for topping in toppings:
        print("-"+topping)
        
#making_pizzas,py
import pizza
make_pizza(16,'pepperoni')
make_pizza(13,'mushrooms','pepperoni','green peppers')

#2.导入特定的函数
from module_name import function_0,function_1,function_2

#3.使用as给函数指定别名
from module_name import function_name as fn

#4.使用as给模块指定别名
import module_name as mn

#5.导入模块中的所有函数
from module_name import *

规则:
1.字母小写 + _
2.指定默认值时,函数调用中的关键字实参 等号两边不要空格
3.函数名长 在(后按两下Tab 与函数体区分开

六、类

1.创建使用类

class Dog():
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.size = 0 #给属性默认值
    def sit(self):
        print(self.name.title() + " is now sitting.")
    def roll_over(self):
        print(self.name.title() + " rolled over.")
    def update_age(self,new_age):
        self.age = new_age
    def print_age(self):
        print(self.name.title() + " " + str(self.age))
        
#根据类创建实例
my_dog = Dog('whille',6)

#访问属性
my_dog.name

#调用方法
my_dog.sit()

#修改属性的值

#直接修改属性的值
my_dog.age = 2
my_dog.print_age()

#使用方法修改属性的值
my_dog.update_age(4)
my_dog.print_age()

2.继承(获得另一个类的所有属性和方法)

class Animal():#父类必须在当前文件中 位于子类前面
    def __init__(self,kind,name):
        self.kind = kind
        self.name = name
    def sit(self):
        print(self.name.title() + " is now sitting.")
    def roll_over(self):
        print(self.name.title() + " rolled over.")
    
class Animal_info():#将实例用作属性
    def __init__(self,information='China'):
        self.information = information
    def print_info(self):
        print("come from "+ self.information)
        
    
class Dog(Animal):
    def __init__(self,kind,name):
        super().__init__(kind,name)
        self.age = 1  #给子类定义属性
        self.info = Animal_info() #将实例用作属性
    def sit(self):  #重写父类方法
        print(self.name.title() + " wangwangwang.")
    def update_age(self,new_age):
        self.age = new_age
    def print_age(self):
        print(self.name.title() + " " + str(self.age))
   

my_dog = Dog('Dog','whille')
print(my_dog.name)
my_dog.print_age()
my_dog.sit()

3.导入类

#导入类
#car.py
class Car():
    --snip--
class Battery():
    --snip--
#my_car.py
import car #导入整个模块
from car import Car,Battery#导入模块中的部分类
from moudle_name import * #导入模块中的所有类

类命名—驼峰命名法(每个单词首字母大写,不使用下划线)
实例名和模块名——小写,加下划线

七、文件和异常

1.从文件中读取数据

1.1.读取整个文件

pi_digits.txt
3.1415926535
8979323846
2643383279

#file_reader.py
with open('pi_digit.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
#with可使Python妥善的打开关闭文件

.rstrip()可删除字符串末尾的空白 read()到达末尾时返回一个空字符串,而将这个空字符串显示出来的时候就是一个空行

1.2文件路径

#相对路径
with open('text_files\filename.txt') as file_object:

#绝对路径
file_path = 'C:\users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
#Linux OS X中用/

1.3逐行读取

#file_reader.py
filename = 'pi_digit.txt'
with open(filename) as file_object:
	for line in file_object:
    	print(line.rstrip())

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

filename = 'pi_digit.txt'
with open(filename) as file_object:
	lines = file_object.readlines()
	
for line in lines:
    print(line.rstrip())

1.5使用文件的内容

filename = 'pi_digit.txt'
with open(filename) as file_object:
	lines = file_object.readlines()
pi_string = ''	
for line in lines:
    pi_string += line.rstrip()

2.写入文件

filename = 'programming.txt'
with open(filename,'w') as file_object:
	file_object.write("I love programming.\n")
	file_object.write("I love programming.\n")

‘w’写入模式 指定文件若已经存在 Python将在返回文件对象前清空该文件
'r’读取模式
'a’附加模式 添加到文件尾部 若不存在该文件则会新建一个空文件
'r+'读取加写入
python只能将字符串写入到文本文件,数值需要str()转为字符串

3.异常

3.1.使用try-except try-except-else

try:
    a=5/0
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print(a)

3.2处理FileNotFoundError异常

filename = 'alice.txt'
try:
    with open(filename) as f_obj:
    	contents = f_obj.read()
except FileNotFoundError:
    print("You can't find!")
else:
	words = contents.split()#以空格为分隔符将字符串拆分为多个部分
	num_words = len(words)

pass失败时什么都不做继续执行

try:
    --snip--
except FileNotFoundError:
    pass

4.存储数据

使用json.dump()和json.load()
json.dump(要存储的数据,以及可用于存储数据的文件对象)

number_writer.py

import json

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

filename = 'number.json'
with open(filename,'w') as f_obj:
    json.dump(number,f_obj)

number_reader.py

import json

filename = 'number.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)

八、测试代码

1.测试函数

1.单元测试和测试用例
python标准库中的模块unittest提供了代码测试工具。
单元测试:用于核实函数的某个方面没有问题
测试用例:一组单元测试,一起在各个情况下的行为都符合要求
全覆盖式测试:一整套单元测试

2.可通过的测试

#测试name_function.py模块的get_formatted_name()
import unittest
from name_function import get_formatted_name
class NamesTextCase(unittest.TestCase):
	def test_first_last_name(self):
		formatted_name = get_formatted_name('amy','Joyn')
		self.assertEqual(formatted_name,'Amy Joyn')
	def test_first_last_middle_name(self):
		formatted_name = get_formatted_name('amy','joyn','mozart')
		self.assertEqual(formatted_name,'Amy Joyn Mozart')
unittest.main()

测试类必须继承unittest.TestCase的类,所有以test_打头的方法都将自动进行
self.assertEqual()函数进行比较

2.测试类

1.各种断言方法

方法核实
assertEqual(a,b)a==b
assertNotEqual(a,b)a!=b
assertTrue(x)x为True
assertFalse(x)x为False
assertIn(item,list)item在list中
assertNotIn(item,list)item不在list中

待测试类
survey.py

class AnonySurvey():
	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)

测试AnonySurvey()类

import unittest
from survey import AnonySurvey

class TestAnonySurvey(unitteat.TeatCase):
	def test_store_single_response(self):
		question = "what language didi you speak?"
		my_survey = AnonySurvey(question) 
		my_survey.store_response('English')
		
		self.assertIn('English',my_survey.responses)
unittest.main()
import unittest
from survey import AnonySurvey

class TestAnonySurvey(unitteat.TeatCase):
	def setUp(self):#可创建一系列实例并设置他们的属性,再在测试方法中直接使用
		question = "what language didi you speak?"
		my_survey = AnonySurvey(question)  #创建调查对象
		self.responses = ['English','Spanish','Chinese'] #创建答案列表
		
	def test_store_single_response(self):
		self.my_survey.store_response(self.responses[0])
		self.assertIn(self.responses[0],self.my_survey.responses)
	def test_store_three_response(self):
		--snip--
unittest.main()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值