python3基础编程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013862108/article/details/86004564

python 基础编程:

语法

在终端窗口中运行的解释器

>>>

linux 下环境安装

安装文本编辑器 geany

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

变量

message = “hello”

print(message)

变量的命名和使用

  1. 变量名只能 包含字母, 数字,和下划线。变量名不能以数字开头。
  2. 不要将python 关键字和函数名 用作变量名。
  3. 变量名 应该既简单又具有描述性,name 比n好
  4. 慎用小写字母i  和大写 字母 O, 因为 他们坑被人看错成 数字  1和0

字符串

可以使用 单引号 ,也可以 使用双引号括起来

“ this is a string”

‘ this is s message’

字符串 类型的变量 有什么方法:

str.title()  //将字符串中的每个单词的 首字母大写

str.upper()   //字符串 中所有字母都 大写

str.lower()   //字符串 中所有字母都 小写

name = “ada love”

print(name.title())

合并字符串 /拼接字符串 :

使用 +   号

转义字符  字符串中 的“

\n  //换行;    \t       //制表符

删除空白

str.rstrip()    //删除右边的空白

str.lstrip()   //删除左边的空白

str.strip()   //同时删除字符串两端的空白

数字 

整数

+  -   *   /

乘方运算,次方运算  ** (两个乘号)

>>> 3**2

9

浮点数

>>> 0.2 + 0.1

0.3000000000000004

类型转换为字符串 str()

age = 23;

message = “Happy “ + age + “rd Birthday!”    //str(age)  才对

print(message)

注释; 怎么注释  注释 语法

#   //#号

编码规范 python 之禅; 怎么查看  >>>import this

第三章 列表

bicycles = [‘trek’, ‘cannodale’, ‘redline’]

print(biycycles)

print(bicycles[0])

print(bicycles[-1])    //访问列表最后一个元素

如何在列表中增加元素

bicycles.append(‘ducati’)

如何 在列表中插入元素

特点;在这个位置及后边的元素 都要后移

motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

motorcycles.insert(0, ‘ducati’)

print(motorcycels)

>[‘ducati’, ‘honda’, ‘yamaha’, ‘suzuki’]

如何从列表中删除元素?

  1. 使用del

del motorcycles[0]

  1. 使用pop()

motorcycles.pop()

  1. pop()  可以弹出 列表中的 任何位置的元素。

mocorcycles.pop(1)

  1. 也可以根据值删除元素? remvoe()

moctorcycles.remove(‘ducati’)

//注意: remove() 只删除第一个指定的值。如果有多个需要循环 多次来删除

列表 有哪些 操作方法

怎么对列表排序/  对列表永久排序

cars = [‘bwm’, ‘audi’, ‘toyota, ‘subaru’]

cars.sort()

print(cars)

>[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]     //注意sort 会改变原列表

怎么倒序排列

cars.sort(reverse= True)

对列表临时排序

sorted(cars)     //注意不用. 调用自己方法,而是系统 函数, ;不改变原来列表顺序;

反转列表里的元素?

cars.reverse()      //注意会改变原来列表

如何计算列表的长度?

len(cars)

第四章: 操作列表

遍历整个列表

  1. for

magicians = [‘alice’, ‘david’,’carolina’]

for magician in maicians:

     print(maician)

//for  循环  里边 循环体 要注意缩进

创建数值列表

使用 函数range()  //生成一系列的数字

for value in range(1,5):

     print(value)

使用range() 创建数字列表

numbers = list(range(1,6))

print(numbers)

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

print(even_numbers)

对数字列表执行简单的统计计算

min()    max()    sum()

digits= [1,2,34,5,6]

min(digits)

列表解析  ;更加简洁一行代码 就能生成一个列表

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

print(squares)

使用列表的一部分

切片:

players = [‘charles’, ‘martina’, ‘michael’, ‘florence’, ‘eli’]

print(players[0:3])          //打印 下标  0, 1, 2  不包括 3下标

print(players[-3:])         //打印 最后的 三个元素,最后一个元素-1下标代表

复制列表

my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’]

friend_foods = my_foods[:]   //注意 friend_foods=my_foods 这种写法 是两个变量引用同一个列表

元组:  

一些元素不可以修改的列表, 不可变的列表称为元组。

定义元组: 使用()

dimensions=(200, 50)

print(dimensions[1])

遍历元组中的所有值

使用for

for dimension in dimensions:

     print(dimension)

修改元组变量

虽然不能修改元组的元素,但可以给存储元组的变量赋值。;/重新定义整个元组

dimensions=(200, 50)

dimensions=(400, 100)

代码规范; /代码格式

PEP8 (Python Enhancement Proposal, PEP)

缩进

      每级使用四个空格

行长

     行长 不超过 72字节

空行

    

第5章 if 语句

cars = [‘audit’, ‘bmw’, ‘subaru’, ‘toyota’]

for car in cars:

    if Car == ‘bmw’:

        print(car.upper())

    else:

        print(car.title())

相等 ==   不相等 !=

检查 多个条件 and  or

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

in   ;  not in

banned_users = [‘andrew’, ‘carolina’, ‘david’]

user = ‘marie’

if user not in banned_users:

    print(user.title()+ “,you can post a response if you wish.”)

多分枝条件语句

if  elif -else

age = 12

if age < 4:

    print(“your admission cost is $0.”)

elif age < 18:

    print(“your admission cost is $5.”)

else :

   print(“Your admission cost is $10.”)

第六章 字典

字典 是 一系列 键值 对 。值 可以  是 数字,字符串,列表, 字典

alien_0 = {‘color’ : ‘green’, ‘points’:5}

print(alien_0[‘color’])

访问字典中的值: 使用方括号

添加 键—值  对

字典是一种动态结构,可随时在其中添加键 —值  对

alien_0 = {‘color’: ‘green’, ‘points’: 5}

alien_0[‘y_position’] = 25

修改字典中的值

alien_0[‘color’] = ‘yellow’

删除 键 — 值  对

del alien_0[‘points’]

遍历 字典

for

user_0  = {‘username’: ‘efermi’, ‘first’: ‘enrico’, ‘last’ : ‘fermi’}

for key, value in user_0.items() :

    print(“key:”+ key)

    print(“value:” _value)

注意 遍历 字典时,键 -值 对的返回顺序也与存储顺序不同。 python 不关心键-值对的存储顺序

遍历字典中的所有键 keys()

for name in favorite_languages.keys():

     print(name.title())

按顺序遍历字典中的所有键:  可以对key  使用sorted() 排序

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

         print(name.title())

遍历字典中的所有值:  使用字典的方法  values()

for language in favorite_languages.values() :

创建集合: set()

for language in set(favorite_languages.values()):

          print(language.title())

嵌套:

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

在字典中存储列表:

pizza = {

    ‘crust’: ‘thick’,

    ‘toppings’: [‘mushrooms’, ‘extra cheese’],

}

在字典中存储字典

users = {

      ‘zhangsan’: {

             ‘first’ : ‘alert’,

             ‘last’ : ‘einsten’,

             ‘location’: ‘printceton’,

      },

      ‘lisi’:{

      ‘first’: ‘marie’,

              ‘last’ : ‘curie’,

              ‘location’: ‘paris’,

      },

      

}

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

name = input(“please enter your name:”)

print(“hello, “ + name + “!”)

如果从 用户 输入 接收 数字,不要忘了 接收到后 转为 int()

age = input(“how old are you “)

age = int(age)

在python2.7  中获取输入 :应该使用raw_input()  和 python 3中的input() 一样,也将输入解读为字符串

python2.7 也包含input(), 但它将用户输入解读为Python 代码。

while 循环

让用户选择何时退出

while  message != ‘quit’:

          message = input(prompt)

          print(message)

使用break 退出循环

使用 continue

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

for 循环是一种遍历列表的有效方式, 但在for 循环中不应该修改列表,否则将导致python 难以跟踪其中的元素。

要在遍历列表的同时对其进行修改,可使用while循环。

在列表之间移动元素

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)

删除  保护 多个特定值 的列表 中元素

pets = [‘dog’, ‘cat’, ‘dog’, ‘cat’]

while ‘cat’ in pets:

           pets.remove(‘cat’)

print(pets)

第八章  :函数

def  greet_user():

    “”” 简单的问候语 “””

      print(“hello!”)

greet_user()

// “””  是 文档注释

传递实参

位置实参

将 函数调用中的实参关联到函数定义中的一个形参。最简单的关联方式是基于实参的顺序。这种关联方式被称为 位置实参数

def describe_pet(animal_type, pet_name):

       print (“My “+ animal_type + “’s name is “ + pet_name.title() + “.”)

describe_pet(“hamster”, “harry”)

关键字 实参  方式调用; 这种方式 不要求 非要和形参 的顺序一样

describe_pet(“animal_type=“hamster”, pet_name=“harry”)

describe_pet(pet_name=“harry”, animal_type=“hamster”)

默认值:

def  describe_pet(pet_name, animal_type=‘dog’) :

      print(“My “ + animal_type)

describe_pet(pet_name=‘willie’)

等效的函数调用

//名字为 willie 的小狗

describe_pet(‘willie’)

describe_pet(pet_name=‘willie’)

//名为 Harry的仓鼠

describe_pet(‘harry’, ‘hamster’)

describe_pet(pet_name=‘harry’, animal_type=‘hamster’)

describe_pet(animal_type=‘hamster’, pet_name=‘harry’)

返回值

函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构。

函数的参数 是可选的,该怎么定义呢

def get_formatted_name(first_name, last_name, middle_name=‘’)

         full_name= first_name + ‘ ‘+ middle_name+ ‘ ‘ + last_name

         return full_name

musician = get_formatted_name(‘jimi’, ‘hendrix’)

musician = get_formatted_name(‘john’, ‘hooker’, ‘lee’)

参数中有列表 

注意事项:

如果不想修改列表 内容 ,或者 为了防止修改列表,可以如下方式 传递 列表类型的参数

function_name(list_name[:])

传递任意数量的实参 怎么做?

*toppings  //让 python 创建一个名为toppings 的空元组

def make_pizza(* toppings) :

         print(topping)

make_pizza(‘mushrooms’, ‘green peppers’, ‘extra cheese’)

结合 位置参数 和 任意数量 实参

def make_pizza(size , *toppings):

       print topping in toppings:

             print(topping)

make_pizza(16, ‘pepperoni’)

make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

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

**user_info   //两个**号 让python 创建一个名为user_info的空字典

def build_proifle(first, last, **user_info):

       todo…

user_profile = build_profile(‘albert’, ‘einstein’, location=‘princeton’, field=‘physics’)

将函数存储在模块中

导入模块

import pizza

使用模块中方法

pizza.make_pizza(16, ‘mushrooms’)

导入模块中特定的函数

from module_name import function_name

如:

from  pizza import make_pizza

make_pizza(16,’mushrooms’)

使用 as  给函数指定别名

from pizza import make_pizza as mp

mp(16, ‘mushrooms’)

使用 as 给模块指定别名

import pizza as p

p.make_pizza(12, ‘mushrooms’)

导入模块中的所有函数    //这种不是好的做法,尽量不要用

使用 *  号

from pizza import *

make_pizza(12, ‘mushrooms’)

第九章 类

创建和使用类

class Dog():

         “”” 模拟小狗“”“

      def  __init__(self,name,age):

                  self.name= name

                  self.age = age

     def  sit(self):

           print(self.name.title())

注意: self 是必不可少, 必须位于其他形参 的前面。

在 python2.7中创建类: 需要做细微的修改,在括号内包含单词object

class ClassName(object):

根据类创建实例

my_dog = Dog(‘willie’, 6)

print(“my dog’s name is” + my_dog.name.title() + “.”)

my_dog.siet()

访问属性 : 句点表示; . 号

调用方法 . 号

继承:

class(superClassName)    //class 后边括号 要写上 父类名字

class Car():

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

                self.make = make

                self.model = model

                self.year = year

               self.odameter_reading = 0

       def get_descriptive_name(self):

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

             return long_time.title()

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

python 2.7 中继承

class Car(object):

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

           —snip—

class ElectricCar(Car):

        def__iniit__(self,make,model,year):

              super(ElectricCar,self).__init__(make, model, year)

              —snip—

重写父类中方法

只要字类和 父类中 方法名字一样即可。

属性;  类的实例也可以作为其他类的属性

导入类

from car import Car   //从 car.py 中导入类 Car

my_new_car = Car(‘audi’, ‘a4’, 2016)

一个模块(文件)可以有多个类

from car import Car, ElectricCar

导入整个模块

import car

from module_name import *  //不推荐这种方式,容易类名字 冲突

大的工程中 经常 出现 在一个模块中导入另一个模块 ,写法 和上面一样

Python 标准库

模块:有 collections

导入标准库 中类 和 导入 自己写的模块 是一样的

from collections imports OrderedDict

类的编码风格

类名: 驼峰命名法, ; 实例名字和模块名字 都采用小写格式,单词之间使用下划线。

在模块中 使用两个空行来分割类

第十章 文件和异常

读取文件

with open(‘pi_gigits.txt’) as file_object:

    contents = file_object.read()

    print(contents)

//with  关键字 , 在不需要访问文件后将其关闭;当然也可以 调用 open() 和 close() 来打开和关闭文件

逐行读取

filename=‘pi_digits.txt’

with open(filename) as file_object:

    for line in file_object:

         print(line)   //print(lline.rstrip())   去除 换行符

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

with open(filename) as file_object:

    lines = file_object.readlines()

for line in lines:

    print(line.rstrip())

写入文件

with open(filename, ‘w’) as file_object:

    file_object.write(“i love programming”)

    file_object.write(“i love creating new games.”)

追加到 文件

open(filename, ‘a’)

异常:

没有捕获异常,;出现异常时 程序会崩溃

try  except

try:

     print(5/0)

except  ZeroDivisionError:

     print(“you can’t divide by zero!”)

try except else

try:

    answer = int(first_number) /int(second_number)

except ZeroDivisionError:

    print(“you can’t divide by 0!”)

else:

    print(answer)

处理FileNotFoundError 异常

try:

    with open(filename) as f_obj:

        contents = f_obj.read()

except FileNotFoundError:

    msg = “ sorrry the file does not exists”

    print(msg)

失败时 一声不吭;  使用 pass

def count_words(filename):

       try:

            —snip—

       except FIleNotFoundError:

           pass

        else:

           —snip—

存储数据:

json.dump()    和 json.load()

remember_me.py

import json

username = input(“what is your name”)

filename = ‘username.json’

with open(filename, ‘w’) as f_obj:

        json.dump(username, f_obj)

        print(“we’ll remember you when youcom back”)

greet_user.py

import json

filename = ‘username.json’

with open(filename) as f_obj:

       username= json.load(f_obj)

       print(“welocme “+ username+”!”)

第十一章 测试代码

单元测试

测试函数

test_name_function.py

import unittest

from name_function  import_get_formatted_name

class NamesTestCase(unittest.TestCase):

       def test_frist_last_name(self):

                formatted_name = get_formatted_name(‘janis’, ‘joplin’)

                self.assertEqual(formatted_name, ‘Janis Joplin’)

unittest.main()

各种断言方法 unittest.TestCase 

assertEqual(a, b)      核实 a== b

assertNotEqual(a, b)      核实 a != b

assertTrue(x)                 核实 x  为true

assertFalse(x)               核实x 为 false

assertIn                        核实 item 在 list 中

assertNotIn( item, list)        核实item 不在 list 中

测试类

测试类 中的 setUp()

如果在 TestCase类中包含了 setUp() ,python 将先运行它, 再运行 各个以 test_打头的方法。

猜你喜欢

转载自blog.csdn.net/u013862108/article/details/86004564