机器学习与数据挖掘大数据 爬虫Python AI Sql大数据

Python 必知必会基础知识(含例子)

2018-09-04  本文已影响83人  马小野

emmm,这部分学的很累,也花了很长时间,但是工欲善其事必先利其器,基础是必不可少的。Python的语法相对来说比较接近自然语言,所以也比较好理解。但是,Python对空格很敏感,可能缺少一个空格就能导致整个程序运行不出来,所以,好的书写习惯有利于提高自己的编程效率。理论学完之后不一定能全部记住,需要通过大量的实践来巩固和加深。电子书资源见文尾,下次为大家推荐一些值得关注的公众号~

1、安装

安装Python  : http://python.org/downloads/

安装文本编辑器 :http://geany.org/

单击Download下的Releases, 找到安装程序geany-1.25_setup.exe或类似的文件。 下载安装程序后, 运行它并接受所有的默认设置。

1)新建:安装完成后,新建文件,输入代码  print('Hello world!')

2)保存:文件命名以.py结束,.py指出这是一个Python程序;

3)运行:可在编辑器中直接‘执行’,也可以在windows终端运行

2、变量和简单的数据类型

1)变量:存储一个值

●  变量名只能包含字母、 数字和下划线,可以字母或下划线打头, 但不能以数字打头

●  变量名不能包含空格, 但可使用下划线来分隔其中的单词

●  不要将Python关键字和函数名用作变量名

●  变量名应既简短又具有描述性

●  慎用小写字母l和大写字母O, 因为它们可能被人错看成数字1和0

2)字符串:一系列字符

●  用引号括起的都是字符串,引号可以是单引号, 也可以是双引号

●  修改字符串大小写:全部大写 upper(),全部小写lower(),首字母大写title()

●  连接字符串:+

●  添加空白:制表符  \t,换行符  \n

●  删除空白:删除字符串开头和末尾多余的空白 rstrip(),剔除字符串开头的空白, 或同时剔除字符串两端的空白  lstrip() 和strip()

3)数字

●  整数:可进行+-*/运算,用两个乘号表示乘方运算

●  浮点数:带小数点的数

●  避免类型错误:转换为字符型 str(),不同类型变量不可以直接相加减

4)注释:# ctrl+E

5)Python之禅:在Python终端会话中执行命令import this

3、列表

由一系列按特定顺序排列的元素组成,在Python中, 用方括号[ ] 来表示列表, 并用,逗号来分隔其中的元素

1)访问列表元素

在Python中, 第一个列表元素的索引为0, 而不是1,索引指定为-1 , 可让Python返回最后一个列表元素,以此倒推

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

print(bycycle[0])

2)添加、修改和删除列表中的元素

●  修改:

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

bycycle[0]=‘honda’

print(bicycles)

●  添加:列表附加元素时, 它将添加到列表末尾 append(),列表的任何位置添加新元素 insert(位置,内容)

●  删除:知道要删除元素的位置 del,从列表中删除, 并接着使用它的值 pop(),知道要删除的元素的值 remove()

3)组织列表

●  永久性排序:sort(),反向排序 sort(reverse=True)

●  临时排序:sorted(),反向排序 sorted(reverse=True)

●  反转元素排列顺序:reverse()

●  确定列表长度:len()

4、操作列表

1)遍历整个列表:for 变量 in列表:缩进

●  编写for 循环时, 对于用于存储列表中每个值的临时变量, 可指定任何名称

●  在for 循环中, 可对每个元素执行任何操作

●  位于for 语句后面且属于循环组成部分的代码行, 一定要缩进

●  for 语句末尾的冒号告诉Python, 下一行是循环的第一行,一定要加

2)创建数值列表

●  生成一系列的数字:range(开始,截止,步长),指定的第一个值开始数, 并在到达你指定的第二个值后停止, 输出不包含第二个值

●  转换为列表:函数list() 将range() 的结果直接转换为列表 list(range(1,3))

●  统计计算:最大值 max(),最小值 min(),求和 sum()

●  列表解析:将for 循环和创建新元素的代码合并成一行, 并自动附加新元素,for 语句末尾没有冒号

3)使用部分列表

●  切片:[起始,终止(不包含该元素)],若没有指定第一个索引, 自动从列表开头开始提取,若没有终止元素,则提取列表末尾的所有元素;负数索引返回离列表末尾相应距离的元素,如players[-3:]返回列表players最后三个元素

●  遍历切片 [:]

●  复制列表:可创建一个包含整个列表的切片, 方法是同时省略起始索引和终止索引 [:]

4)元组

列表适用于存储在程序运行期间可能变化的数据集,列表是可以修改的,元组是不可修改的列表。

●  定义:元组看起来犹如列表, 但使用圆括号()来标识

●  遍历:for循环

●  修改元祖变量:重新定义整个元组

5)代码格式

●  缩进:每级缩进4个空格

●  行长:小于80个字符

5、if语句

1)条件测试

每条if 语句的核心都是一个值为True 或False 的表达式, 这种表达式被称为条件测试

●  检查是否相等:=  区分大小写

●  检查是否不相等: !=

●  检查多个条件:and  or

●  检查特定值是否包含在列表:  in/not in

●  布尔表达式:条件测试的别名

2)if语句

●  if-else语句

for megican in megicans:

        if megican=='alice':

                print(megican.upper())

        else:

                print(megican.title())

●  if-elif-else 结构

相当于if-else if-else

3)用if语句处理列表

●  检查特殊元素

●  确定列表不是空的

6、字典

1)使用字典

字典:是一系列键—值对 。 每个键 都与一个值相关联, 你可以使用键来访问与之相关联的值,字典用放在花括号{} 中的一系列键—值对表示。

●  访问字典:

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

print(alien_0['color'])

print(alien_0['points'])

●  添加键值对

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

print(alien_0)

alien_0['x_position']=25

alien_0['y_position']=5

print(alien_0)

●  删除键值对 del alien_0['points']

2)遍历字典 for 循环

●  遍历所有键值对

user_0={

        'user_name':'efermi',

        'first':'enrico',

        'last':'fermi',

        }

for key,value in user_0.items():

        print('\nKey: '+key)

        print('Value: '+value)

●  遍历所有键

for key in user_0.keys():

●  按顺序遍历字典中所有键

for key in sorted(user_0.keys()):

●  遍历所有值

for value in user_0.valuses():

3)嵌套

●  将一系列字典存储在列表中, 或将列表作为值存储在字典中, 这称为嵌套

user_0={

        'user_name':'amily',

        'first':'ami',

        'last':'lily',

        }

user_1={

        'user_name':'efermi',

        'first':'enrico',

        'last':'fermi',

        }

users=[user_0,user_1]

for user in users:

        print(user)

●  在字典中存储列表

pizza={

        'crust':'thick',

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

        }

print('You ordered a '+pizza['crust']+'-crust pizza '+'with the follwing toppings:')

for topping in pizza['toppings']:

        print('\t'+topping)

●  在字典中嵌套字典

users={

        'user_0':{

                'first':'amily',

                'last':'smith',

                'location':'princeton',

                },

        'user_1':{

                'first':'efermi',

                '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()函数

●  原理

函数input() 让程序暂停运行, 等待用户输入一些文本。 获取用户输入后, Python将其存储在一个变量中。

message=input('Tell me something, and i will repeat it back to you: ')

print(message)

有时候, 提示可能超过一行, 例如, 你可能需要指出获取特定输入的原因。 在这种情况下, 可将提示存储在一个变量中, 再将该变量传递给函数input()

message='Tell me something, and i will repeat it back to you'

message+='\nWhat do you want to say? '

something=input(messgae)

print('\nHello, '+something+'!')

●  int()获取数值输入

使用函数input() 时,Python将用户输入解读为字符串,函数int() 将数字的字符串表示转换为数值表示。

age=input('How old are you? ')

age=int(age)

if age>=18:

        print("\nYou're old enough to ride!")

else:

        print("\nYou'll be able to ride when you're a little order.")

●  求模运算符: % 两个数相除并返回余数

如果一个数可被另一个数整除, 余数就为0, 因此求模运算符将返回0,可利用这一点来判断一个数是奇数还是偶数。

number=input("Enter a number, and I'll tell you if it's even or odd:")

if int(number) %2==0:

        print('\nThe number '+str(number)+' is even.')

else:

        print('\nThe number '+str(number)+' is odd.')

2)while循环

current_number=1

while current_number<=5:

        print(current_number)

        current_number+=1

●  让用户选择何时退出

prompt='Tell 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)

●  使用标志

在要求很多条件都满足才继续运行的程序中, 可定义一个变量, 用于判断整个程序是否处于活动状态。 这个变量被称为标志,可让程序在标志为True 时继续运行, 并在任何事件导致标志的值为False 时让程序停止运行。

prompt='Tell me something, and i will repeat it back to you'

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

active=True

while active:

        message=input(prompt)

        if message=='quit':

                active=False

        else:

                print(message)

●  使用break退出循环

prompt='Tell me something, and i will repeat it back to you'

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

while True:

        message=input(prompt)

        if message=='quit':

                break

        else:

                print(message)

●  在循环中使用continue

current_number=0

while current_number<=10:

        current_number+=1

        if current_number%2==0:

                continue

        print(current_number)

要返回到循环开头, 并根据条件测试结果决定是否继续执行循环, 可使用continue 语句

3)使用while循环来处理列表和字典

●  在列表之间移动元素

unconfirmed_users=['alice','brain','candy']

confirmed_users=[]

while unconfirmed_users:

        current_user=unconfirmed_users.pop()

        print('Veryfying user: '+current_user.title())

        confirmed_users.append(current_user)

print('\nThe follwing users have been confirmed:')

for confirmed_user in confirmed_users:

        print(confirmed_user.title())

●  删除包含特定元素的所有列表元素

pet=['cat','dog','goldfish','dog','cat']

print(pet)

while 'cat' in pet:

        pet.remove('cat')

print(pet)

●  由用户输入来填充字典

responses={}

polling_active=True

while polling_active:

        name=input('\nWhat is your name? ')

        response=input('\nWhich mountain would you like to climb someday?')

        responses[name]=response

        repeat=input('\nWould you like to let another person respond?(yes/no)')

        if repeat=='no':

                polling_active=False

print('\n---Poll Results---')

for name,response in responses.items():

        print(name+' would like climb '+response+'.')

8、函数

1)定义函数

def  定义以冒号结尾

def greet_user(user_name):

        print('Hello, '+user_name.title()+'!')

greet_user('jesse')

●  实参和形参

变量user_name是一个形参 ——函数完成其工作所需的一项信息。 在代码greet_user('jesse') 中,值'jesse' 是一个实参 。 实参是调用函数时传递给函数的信息。

2)传递实参

●  位置实参

要求实参的顺序与形参的顺序相同

def describe_pet(pet_type,pet_name):

        print('\nI have a '+pet_type+'.')

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

describe_pet('hamster','Henrry')

●  关键词实参

每个实参都由变量名和值组成,直接在实参中将名称和值关联起来了

def describe_pet(pet_type,pet_name):

        print('\nI have a '+pet_type+'.')

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

describe_pet(pet_type='hamster',pet_name='Henrry')

●  默认值

编写函数时, 可给每个形参指定默认值 。 在调用函数中给形参提供了实参时, Python将使用指定的实参值; 否则, 将使用形参的默认值。

def describe_pet(pet_type=‘dog',pet_name):

        print('\nI have a '+pet_type+'.')

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

describe_pet('Henrry')

3)返回值

函数返回的值被称为返回值,可使用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)

●  返回字典

def person_name(first_name,last_name):

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

        return person

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

print(musician)

4)传递列表

def person_name(names):

        for name in names:

                msg='Hello '+name.title()+'!'

        print(msg)

usernames=['jimi','hendrix','john']

person_name(usernames)

●  在函数中修改列表

在函数中对这个列表所做的任何修改都是永久性的

unprinted_designs=['iphone case','robot pendant','dodecahedron']

complete_models=[]

while unprinted_designs:

        current_design=unprinted_designs.pop()

        print('Printing model:' + current_design)

        complete_models.append(current_design)

print('\nThe following models have been printed:')

for complete_model in complete_models:

        print(complete_model)

可编写两个函数重新组织这些代码,效率更高。

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_compeled_models(completed_models):

        print('\nThe following models have been printed:')

        for completed_model in completed_models:

                print(completed_model)

unprinted_designs=['iphone case','robot pendant','dodecahedron']

completed_models=[]

print_models(unprinted_designs,completed_models)

show_compeled_models(completed_models)

5)传递任意数量的实参

Python允许函数从调用语句中收集任意数量的实参,星号* 让Python创建一个名为toppings 的空元组, 并将收到的所有值都封装到这个元组中。

def make_pizza(*toppings):

        print(toppings)

make_pizza('pepperoni')

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

●  结合使用位置实参和任意数量实参

def make_pizza(size,*toppings):

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

       for topping in toppings:

                print('- '+topping)

make_pizza(16,'pepperoni')

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

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

**user_info 中的两个星号让Python创建一个名为user_info 的空字典, 并将收到的所有名称—值对都封装到这个字典中。

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','einstein',

                                                      location='princetion',

                                                      field='physics')

print(user_profile)

5)将函数存储在模块中

将函数存储在被称为模块 的独立文件中,再将模块导入 到主程序中。import 语句允许在当前运行的程序文件中使用模块中的代码。模块 是扩展名为.py的文件, 包含要导入到程序中的代码。

●  导入整个模块

def make_pizza(size,*toppings):

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

        for topping in toppings:

                print('- '+topping)

●  将上述内容保存为pizza.py文件,再使用下面的调用语句

import pizza

pizza.make_pizza(16, 'pepperoni')

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

●  导入特定的函数

from module_name import function_0, function_1, function_2

from pizza import make_pizza

make_pizza(16, 'pepperoni')

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

●  使用as 给函数指定别名

from pizza import make_pizza as mp

mp(16, 'pepperoni')

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

●  使用as 给模块指定别名

import pizza as p

p.make_pizza(16, 'pepperoni')

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

●  导入模块中的所有函数

使用星号(* ) 运算符可让Python导入模块中的所有函数

from pizza import *

make_pizza(16, 'pepperoni')

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

9、类

1)创建和使用类

在Python中,创建类以class开头首字母大写的名称指的是类,小写的名称指根据类创建的实例。

●  创建Dog类

class Dog():

        def __init__(self,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!')

!注意!init左右两边有两个_,方法__init__() 定义成了包含三个形参: self 、 name 和age 。 在这个方法的定义中, 形参self 必不可少, 还必须位于其他形参的前面。每个与类相关联的方法调用都自动传递实参self , 它是一个指向实例本身的引用, 让实例能够访问类中的属性和方法。

●  根据类创建实例

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.")

2)使用类和实例

●  Car类

class Car():

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

                self.make=make

                self.model=model

                self.year=year

        def get_descriptive_name(self):

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

                return long_name.title()

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

print(my_new_car.get_descriptive_name())

●  给属性指定默认值

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.')

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

print(my_new_car.get_descriptive_name())

my_new_car.read_odometer()

●  修改属性的值

my_new_car.odometer_reading = 23

my_new_car.read_odometer()

3)继承

如果你要编写的类是另一个现成类的特殊版本, 可使用继承 。 一个类继承 另一个类时, 它将自动获得另一个类的所有属性和方法; 原有的类称为父类 , 而新类称为子类 。 子类继承了其父类的所有属性和方法, 同时还可以定义自己的属性和方法。定义子类时, 必须在括号内指定父类的名称。super() 是一个特殊函数, 帮助Python将父类和子类关联起来。

●  子类的方法__init__()

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)

                self.battery_size = 70

        def describe_battery(self):

                print("This car has a " + str(self.battery_size) + "-kWh battery.")

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

print(my_new_car.get_descriptive_name())

print(my_tesla.get_descriptive_name())

my_tesla.describe_battery()

电子书: https://pan.baidu.com/s/1HW3M9rpnfCpu76bWtSBcMg

上一篇下一篇

猜你喜欢

热点阅读