Python基础学习-核心知识点

1.      操作列表

1.1   遍历列表

通过for循环对列表进行遍历:

fruits = ['apple','orange','banana']
for fruit in fruits:
 
print(fruit)

注意:注意缩进、不要漏掉冒号

1.2   创建数值列表

创建数值列表常用range()函数:

ss = []
for v in range(1,11):
    s=v**2
    ss.append(s)
print ss

注意:数字列表可以进行统计计算,函数包括min()、max()、sum()

列表解析表达式:ss=[v**2 for v in range(1,11)]

1.3   列表切片

ss[0:2] 取前两个元素   ss[-2:]取最后两个元素 cc=ss[ : ] 复制列表

2 元组

  元组是不可修改的元素,即不可变的列表被称为元组

2.1 元组的定义

D = (20,5)
print (D[0])

2.1 元组的遍历和列表一样

2.3 修改元组变量

   虽然不能修改元组的元素,但是可以给存储元组的变量赋值。

3  if语句

   检查多个条件使用and ,or 

   检查特定值是否不包含在列表中 not in

  Ifconditional_test:

    do something

if – elif-else 结构

3.1使用if 语句处理列表

4字典

4.1创建字典

dic={}
dic[
'book']='python'
dic['price']=50
print(dic)

4.2删除键值对

dic={'book':'python','price':56}
del dic['book']
print(dic)

4.3遍历字典

4.3.1遍历所有的键-值对

user = {
     
'name':'666',
     
'sex':'man',
     
'address':'wuhan'
}
for key,value in user.items():
       
print ("\nKey:"+ key)
       
print "value:"+ value

编写用于遍历字典的for循环,可声明两个变量,用于存储键值对中的键和值,两个变量可任意定义。

4.3.2遍历字典中的所有键

user = {
     
'name':'666',
     
'sex':'man',
     
'address':'wuhan'
}
for key in user.keys():
       
print ("\nKey:"+ key.title())

4.3.3按顺序遍历所有键

使用函数sorted()

user = {
     
'name':'666',
     
'sex':'man',
     
'address':'wuhan'
     }
for key in sorted(user.keys()):
       
print ("\nKey:"+ key.title())

4.3.4遍历字典中的所有值

user = {
     
'name':'666',
     
'sex':'man',
     
'address':'wuhan'
}
for value in sorted(user.values()):
       
print ("\nvalue:"+ value.title())

 

字典列表:列表中的元素是字典

字典中存储列表:value值是列表

字典中存储字典:value值是字典

 

5函数(在函数中修改列表)

# coding=utf_8_decode
def print_models(unprinted_designs,completed_models):
   
while unprinted_designs:
           current_design =unprinted_designs.pop()
          
print("Printing model:"+current_design)
          completed_models.append(current_design)
def show_completed_models(completed_models):
   
print("\nThefollowing models have been printed:")
   
for completed_modelin completed_models :
       
print(completed_model)
unprinted_designs = [
'iphonecase','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs
,completed_models)
show_completed_models(completed_models)

 

注意:禁止函数修改列表

可向函数传递列表的副本而不是原件,这样函数所做的任何修改只影响副本,而丝毫不影响原件

Function_name(list_name[:])

5.1传递任意数量的实参

# coding=utf_8_decode
def make_pizza(*toppings):
   
"""打印顾客点的所有配料"""
   
print(toppings)
make_pizza(
'pepperoni')
make_pizza(
'a','b','c')

注意:形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到元组中。

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

对于接受任意数量的实参,为了能够传递各样信息,可将函数编写成能够接受任意数量的键-值对:

应用情境:创建用户简介的时候,对于受到的信息难以确定是什么样的信息,因此设计函数build_profile()接受名和姓,同时还接受任意数量的关键字实参

# coding=utf_8_decode
def build_profile(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_profile(
'albert','einstin',location='princet',field='physics')
print user_profile

注意:build_profile()的定义要求提供名和姓,同时允许用户根据需要提供任意数量的名称-值对。形参**user_info中的两个星号让python创建一个名为user_info的空字典,并将收到的所有名称-值对都封装在该字典中。

5.3将函数存在模块中

# coding=utf_8_decode
import lists
from lists importbuild_profile
user_profile = build_profile(
'albert','einstin',location='princet',field='physics')
print user_profile

1.      可以用import导入模块名

然后用module_name.function_name()调用函数

2.      直接导入特定函数

From module_name import function_name

5.3.1可以使用AS给函数指定别名

5.4函数编写总结

1.给函数制定描述性名称,且只在其中使用小写字母和下划线。

2.每个函数都应包含简要地阐述其功能的注释

3.给形参指定默认值时,等号两边不要有空格

6类

# coding=utf_8_decode
class Dog():
      
def __init__(self, name, age):
           
self.name= name
           
self.age= age
      
def sit(self):
           
print (self.name+"isnow sitting")
      
def roll_over(self):
           
print (self.name + "rolledover!")

注意:方法__init__两个下划线,方法中self必不可少,因为创建实例时会自动传入实参self,每个与类相关联的方法都自动传递实参self,它是一个指向实例本身的引用。

Self作为前缀的变量都可供类中的所有方法使用

6.1继承

# coding=utf_8_decode
class Dog(object):
      
def __init__(self, name, age):
           
self.name= name
           
self.age= age
      
def sit(self):
           
print (self.name+"isnow sitting")
      
def roll_over(self):
           
print (self.name + "rolledover!")
class Tdog(Dog):
      
def __init__(self, name, age ,sex):
          
super(Tdog,self).__init__(name,age)
          
self.sex=sex
      
def run(self):
          
print (self.name + "isnow running")

my_dog = Tdog(
'www',6,'m')
my_dog.run()

注意:python2.7的语法

ClassXXX(object):

     Def __init__(self,c,b,d)

Classxxx(XXX):

Def __init__(self,c,b,d)

Super(XXX,self). __init__(c,b,d)

Super()是一个特殊函数,帮助Python将父类与子类关联起来

6.2重写父类方法

# coding=utf_8_decode
class Dog(object):
      
def __init__(self, name, age):
           
self.name= name
           
self.age= age
      
def sit(self):
           
print (self.name+"isnow sitting")
      
def roll_over(self):
           
print (self.name + "rolledover!")
class Tdog(Dog):
      
def __init__(self, name, age ,sex):
          
super(Tdog,self).__init__(name,age)
          
self.sex=sex
      
def sit(self):
           
print (self.name+"isnow sitted!!!!!!!!!!!")
my_dog = Tdog(
'www',6,'m')
my_dog.sit()

6.3导入类

From module_nameimport *

6.4python标准库

Python标准库是程序员编写好的一组模块

7文件和异常

# coding=utf_8_decode
with open('text_files\filename.txt')as file_object:

注:在文件路径中使用反斜杠(\)而不是斜杠(/)

7.1逐行读取

# coding=utf_8_decode
filename = 'test.txt'
with open(filename)as file_object:
   
for linein file_object:
       
print(line)

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

# coding=utf_8_decode
filename = 'test.txt'
with open(filename)as file_object:
      lines = file_object.readlines()
for line in lines:
   
print(line.strip())

readlines()从文件中读取每一行,并将其存储在一个列表中

7.3写入文件

# coding=utf_8_decode
filename = 'test.txt'
with open(filename,'w') as file_object:
    file_object.write(
"I love programming")

8异常处理

8.1使用try-except代码块

# coding=utf_8_decode
try:
   
print(5/0)
except ZeroDivisionError:
   
print("o不能做分母")
print("成功跳坑")

8.2处理FileNotFoundError

# coding=utf_8_decode
from pandas.compat import FileNotFoundError
filename =
'test.txt'
try:
   
with open(filename) as ff:
        contents = ff.read()
except FileNotFoundError:
         
print("文件不存在")

8.3 存储数据

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

json.dump()

# coding=utf_8_decode
import json
numbers = [
1,2,3]
filename =
'D:/numbers.json'
with open(filename,'w') as f :
    json.dump(numbers
,f)

json.load()

# coding=utf_8_decode
import json
numbers=[]
filename =
'D:/numbers.json'
with open(filename)as f :
    numbers = json.load(f)
   
print(numbers)

8.3.2 重构

代码能够正确的运行,但可做进一步的改进——将代码划分一系列的完成具体的工作的函数,使得代码更加清晰、更容易理解。


9 Web应用程序之Django入门

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值