Python自学笔记(一)之Python特色及开发环境的搭建

一、关于Python

       Python是一款容易学习而且功能强大的面向对象的解释型计算机程序设计语言。由荷兰人Guido van Rossum于1989年发明。由于Python简单易读,而且有内置丰富的高效库,使得Python越来越多的用于科学计算。

       Python在执行时,首先会将.py文件中的源代码编译成Python的byte code(字节码),然后再由Python Virtual Machine(Python虚拟机)来执行byte code。这种机制的基本思想跟Java相似。

1.IDE

PyCharm

商业软件,不过使用edu邮箱可以注册证书,从而免费使用教育版。百度给出的功能有调试、语法高亮、项目管理、代码跳转、智能提示、自动完成、单元测试、版本控制等。个人认为:英文单词拼写检查、不严谨写法的提示、代码颜色、自动缩进这几个方面是比较好的。此外,与Android Studio、Visual Studio等软件的布局、常用功能使用类似。

Eclipse with PyDev

允许开发者创建有用和交互式的 Web 应用。PyDev 是 Eclipse 开发 Python 的 IDE,支持 Python,Jython和 IronPython 的开发。

2.命令行

3.Python自带的idle

4.文本编辑器

Sublime TextNotepad++Vim Emacs

使用文本编辑器编写程序的话需要编辑结束保存成相应格式的文件,例如网页的.html .css,python的.py,然后到相应的环境下运行,对于python的话,可以在命令行或者自带idle下执行。

二、前期准备

(一) 搭建开发环境

1.官网下载:https://www.python.org/downloads/windows/

2.下载完成后运行.exe文件,勾选“Add Python 3.7 to PATH”

如果不修改安装路径,选择“Install Now”而且不需要修改环境变量

3.安装完成后,dos下输入python,显示Python版本则表明安装成功

4.通过Python命令,运行Python程序

(二)安装Python IDE——pycharm

  1. 使用edu邮箱注册https://account.jetbrains.com的账号并申请证书
  2. 下载pycharm教育版的安装包

  1. 下载完成后运行.exe文件,选择安装路径。
  2. 创建桌面快捷方式

Create Desktop Shortcut创建桌面快捷方式,一个32位,一个64位,

选Create Associations是否关联文件,选择以后打开.py文件就会用PyCharm打开

  1. 安装过程

  1. 安装完成,点击“Finish”按钮

  1. 双击桌面图标,进行配置,点击“OK”

  1. 点击“Accept”

  1. 跳过设置环节,输入证书ID的网址或者登录账号,进行激活

  1. 激活成功

 

11 运行Pycharm

 

学习基础:

注释

存在于#右部的内容

单引号、双引号

括起来的字符串没区别 print(‘HelloWorld!’) 和print(“HelloWorld!”)等价

格式化方法 format

age=20
name='yangyuying'

print('{0} was {1} years old when he wrote this book'.format(name, age))
print('why is {0} playing with that python'.format(name))

python 0开始,索引的第一位是0,

print('{0:.3f}'.format(1.0/3)) #使用format表示0.333

print('{0:_^11}'.format('hello')) #使用format表示___hello___ 字符串长度为11

print('{name} wrote {book}'.format(name='Swaroop',book='A Byte of Python')) #使用format输出指定的字符串

print默认以’\n’结尾,若结果希望在一行出现

print('a',end='')

print('b',end=''#输出结果ab

转义字符

print('This is the first line\nThis is the second line')

This is the first line

This is the second line

print('This is the first line\tThis is the second line')

This is the first line    This is the second line

       标识符命名

   >>第一个字符必须是字母表中字母(大写小写或者Unicode)或者下划线(_)

   >>其余字符可以是字符或者下划线或者是数字

   >>区分大小写

   对象

Python中将程序中的任何内容统称为对象(object),python是强面向对象的

缩进

放置在一起的语句必须拥有相同的缩进。每一组语句称为块。如果放在一起的语句缩进不一致会报错。

    print(i)

    ^

IndentationError: unexpected indent

Python语言官方建议使用四个空格来缩进

运算符

+(加)、-(减)、*(乘)、**(乘方)、/(除)、//(整除)、%(取模)、<<(左移)、>>(右移)、&(按位与)、|(按位或)、^(按位异或)、~(按位取反)、<(小于)、>(大于)、<=(小于等于)、>=(大于等于)、==(等于)、!=(不等于)、not(布尔“非”)、and(布尔“与”)、or(布尔“或”)

print(3**4#乘方
print(18//5#整除
print(18%4#取模
print(2<<2) #左移(乘)
print(100>>2) #右移(除)
print(5&3) #按位与
print(5|3) #按位或
print(5^3) #按位异或
print(~5) #按位取反
print(5==6) #判断等于
x=False;
print(not x)

运行结果:

81

3

2

8

25

1

7

6

-6

False

True

控制流

   if语句

number=23
guess=int(input('Enter an integer:'))
if guess == number :
   
# 新块从这里开始
   
print('Congratulations,you guess it!')
   
print('but you do not win any prizes')
   
# 新块在这里结束
elif guess < number:
  
# 另一个代码块
   
print('No,it is a little higher than that')
  
# ...
else:
   
print('No,it is a little lower than that')

print('Done')

 

Enter an integer:20

No,it is a little higher than that

Done

if-elif-else,注意要加:input()类来获得用户的输入,用户输入默认为字符串形式,使用int来进行转换

Python中不允许使用Switch语句,使用if-elif-else来等价实现

while语句

number=23
running=True
while
running:
   guess=
int(input('Enter an integer:'))
  
if guess == number :
      
# 新块从这里开始
      
print('Congratulations,you guess it!')
       running=
False
      
# 新块在这里结束
  
elif guess < number:
      
# 另一个代码块
      
print('No,it is a little higher than that')
      
# ...
  
else:
       
print('No,it is a little lower than that')
else:
   
print('The while loop is over.')
print('Done')

Enter an integer:50

No,it is a little lower than that

Enter an integer:25

No,it is a little lower than that

Enter an integer:20

No,it is a little higher than that

Enter an integer:23

Congratulations,you guess it!

The while loop is over.

Done

for 循环:

for i in range(1,5):
   
print(i)
else:
   
print('The for loop is over')

1

2

3

4

The for loop is over

range(1,5,2) 会输出1 3

使用list()输出完整的数字列表

print(list(range(1,5)))

[1, 2, 3, 4]

break语句

根据用户输入的字符串来判断什么时候结束,len()函数来计算字符串的长度

while True:
    s=
input('Enter something:')
   
if s=='quit':
          
break
   
print('Length of the string is',len(s))
   
print('Done')

Enter something:hahaha

Length of the string is 6

Done

Enter something:dadadadadadas

Length of the string is 13

Done

Enter something:quit

continue语句

跳过当前循环的剩余语句,继续迭代该循坏的下一次迭代

while True:
    s=
input('Enter something:')
   
if s=='quit':
       
break
    if
len(s)<3:
       
print('Too small')
       
continue
   
print('Input is of sufficient length')

Enter something:yy

Too small

Enter something:yyy

Input is of sufficient length

Enter something:hahahha

Input is of sufficient length

Enter something:quit

 

Process finished with exit code 0

函数

def say_hello():
   
print('Hello world!')

say_hello()

Hello world!

 

Process finished with exit code 0

def print_max(a,b):
   
if a>b:
       
print(a,'is maximum')
   
elif a==b:
       
print(a,'is equal to',b)
   
else:
       
print(b,'is maximum')
print_max(
3,5)
x=
66
y=88
print_max(x,y)
print_max(
input('input the first number:'),input('input the second number:'))

5 is maximum

88 is maximum

input the first number:55

input the second number:66

66 is maximum

 

Process finished with exit code 0

局部变量

x=50
def func(x):
   
print('x is',x)
    x=
2
   
print('changed local x to',x)

func(x)

print('x is still',x)

x is 50

changed local x to 2

x is still 50

global语句(全局)

x=50
def func():
   
global x
   
print('x is',x)
    x=
2
   
print('changed local x to',x)

func()

print('value of x is',x)

x is 50

changed local x to 2

value of x is 2

全局变量,对x赋值时,影响整体

默认参数值(不可变)

def say(message,times=1):
   
print(message*times)

say(
'hello')
say(
'world',5)

hello

worldworldworldworldworld

关键字参数

使用命名(关键字)而非位置来指定函数中的参数

def func(a,b=5,c=10):
   
print('a is',a,'and b is','and c is',c)

func(
3,7)
func(
25,c=24)
func(
c=50,a=100)

a is 3 and b is and c is 10

a is 25 and b is and c is 24

a is 100 and b is and c is 50

可变参数

参数数量可变,有任意数量的变量

def total(a=5,*numbers,**phonebook):
   
print('a',a)

   
#遍历元组中的所有项目
   
for single_item in numbers:
       
print('single_item',single_item)

   
#遍历字典中的所有项目
   
for first_part,second_part in phonebook.items():
       
print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))

a 10

single_item 1

single_item 2

single_item 3

Jack 1123

Inge 1560

John 2231

None

声明一个*param的符号参数时,从此处开始至结束的所有位置参数都将被收集并汇集成一个称为“param”的元组(Tuple

声明一个**param的双星号参数时,从此处开始至结束的所有关键字参数都被收集并汇集成一个名为param的字典(Dictionary

return语句

函数返回,中断函数

def maximum(x,y):
   
if x>y:
       
return x
   
elif x==y:
       
return 'The numbers are equal'
   
else:
       
return y
print(maximum(2,3))

3

DocStrings 文档字符串’’’…’’’  函数名.__doc__  双下划线

def print_max(x,y):
   
'''打印最大值
    '''
   
x=int(x);
    y=
int(y)

   
if x>y:
       
print(x,'is maximum')
   
else:
       
print(y,'is maximum')

print_max(
3,5)
print(print_max.__doc__)

5 is maximum

打印最大值

 

模块Modules

一个模块可以被其他程序导入并运用其功能

import sys

print('The command line arguments are:')
for i in sys.argv:
   
print(i)
print('\n\nThe PYTHONPATH is',sys.path,'\n')

模块的__name__

__name__属性与__main__相同则代表该模块由用户独立运行

 

编写自己的独立模块

mymodule.py:

def say_hello():
   
print('Hello,I am Yangyuying!')
__version__=
'0.1'

在主程序中调用:

import mymodule
mymodule.say_hello()

print('Version',mymodule.__version__)

Hello,I am Yangyuying!

Version 0.1

dir函数

返回由对象所定义的名称列表

dir(sys)给出sys模块的属性名称

dir()给出当前模块的属性名称

del 变量名 功能:删除或者移除一个名称

package

变量位于函数内部,函数与全局变量位于模块内部,而模块由包组织起来

包是一种能够方便地分层组织模块的方式

数据结构

用来存储一系列相关数据的集合

Python有四种内置的数据结构——列表(List)、元组(Tuple)、字典(Dictionary)和集合(Set)

列表(List

保留一系列有序项目的集合,可进行添加、移除或者搜索列表中的项目,列表是可变的(Mutable)数据类型

类和对象

列表是类和对象的一个实例,一个类可以有很多方法,list有append方法,如mylist.append(‘an item’);一个类同时具有字段(Field),只为该类定义且为该类所用的变量mylist.field

#This is my shopping list
shoplist=['apple','mango','carrot','banana']

print('I have',len(shoplist),'items to purchase')

print('These items are:',end=' ')
for item in shoplist:
   
print(item,end=' ')

print('\nI also have to buy rice')
shoplist.append(
'rice')
print('My shopping list is now',shoplist)

print('I will sort my list now')
shoplist.sort()

print('Sorted shopping list is',shoplist)

print('The first item I will buy is',shoplist[0])
olditem=shoplist[
0]
del shoplist[0]
print('I bought the',olditem)
print('My shopping list is now',shoplist)

I have 4 items to purchase

These items are: apple mango carrot banana

I also have to buy rice

My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']

I will sort my list now

Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']

The first item I will buy is apple

I bought the apple

My shopping list is now ['banana', 'carrot', 'mango', 'rice']

元组(Tuple

用于将多个对象保存在一起,可近似看成列表,但元组不能提供列表提供的广泛的功能,元组类似于字符串,是不可变的,不能编辑或者更改元组。

元组是通过特别指定项目来定义的,在指定项目时,可以加上括号,并在括号内部用逗号隔开。用于保证某一语句或某一用户定义的函数可以安全的采用一组数值,数值不会改变

zoo=('python','elephant','penguin')
print('Number of animals in the zoo is',len(zoo))

new_zoo=
'monkey','camel',zoo
print('Number od animals in the new_zoo is',len(new_zoo))
print('All animals in new zoo is',new_zoo)
print('Animals brought from old zoo are',new_zoo[2])
print('Last animal brought from old zoo is',new_zoo[2][2])
print('Number of animals in the new_zoo is',len(new_zoo)-1+len(zoo))

Number of animals in the zoo is 3

Number od animals in the new_zoo is 3

All animals in new zoo is ('monkey', 'camel', ('python', 'elephant', 'penguin'))

Animals brought from old zoo are ('python', 'elephant', 'penguin')

Last animal brought from old zoo is penguin

Number of animals in the new_zoo is 5

字典(Directory

键值(keys&值(values),键值唯一,只能使用简单对象作为键值

d={key:value1,key2:value2},键值和值之间用冒号,每一键值对之间用逗号隔开

字典中的成对的键值-值配对不会以任何方式进行排序,只能在使用它们之前进行排序。字典是dict类下的实例或对象

ab={
   
'S1':'a',
   
'S2':'b',
   
'S3':'c',
   
'S4':'d'
}
print("S1's address is",ab['S1'])

del ab['S2']

print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
for name,address in ab.items():
   
print('Contact {} at {}'.format(name,address))
ab[
'S5']='e'
if 'S5' in ab:
   
print("\nS5's address is",ab['S5'])

S1's address is a

 

There are 3 contacts in the address-book

 

Contact S4 at d

Contact S1 at a

Contact S3 at c

 

S5's address is e

 

ab[‘S1’]即可访问键值对应的值 del ab[‘S2’]即可删除键值对应的值 ab[‘S5’]=….即可添加键值对应的值

序列(Sequence

列表、元组、字符串都可看做序列的某种表现形式,主要功能是资格测试(innot in)和索引操作。

shoplist=['apple','mango','carrot','banana']
name=
'swaroop'

print('Item 0 is',shoplist[0])
print('Item 1 is',shoplist[1])
print('Item -1 is',shoplist[-1])
print('Item -2 is',shoplist[-2])
print('Character 0 is',name[0])

print('Item 1 to 3 is',shoplist[1:3])
print('Item 1 to end is',shoplist[2:])
print('Item 1 to -1 is',shoplist[1:-1])
print('Item start to end is',shoplist[:])

print('Character 1 to 3 is',name[1:3])
print('Character 1 to -1 is',name[1:-1])
print('Character start to end is',name[:])

Item 0 is apple

Item 1 is mango

Item -1 is banana

Item -2 is carrot

Character 0 is s

Item 1 to 3 is ['mango', 'carrot']

Item 1 to end is ['carrot', 'banana']

Item 1 to -1 is ['mango', 'carrot']

Item start to end is ['apple', 'mango', 'carrot', 'banana']

Character 1 to 3 is wa

Character 1 to -1 is waroo

Character start to end is swaroop

查找时,负数表示序列倒着数,-1最后一个

切片操作:第一个数字是开始的位置,第二个数字是结束的位置(不包含本身),第三个数字是步长shoplist[:]表示整个序列

集合(Set

简单对象的无序集合,可测试某些的对象的资格或情况,检查它们是否是其他集合的子集,找到两个集合的交集

bri=set(['Brazil','Russia','India'])
print('India' in bri)
print('USA' in bri)
bric=bri.copy() #
拷贝
bric.add(
'China')#添加
for i in bric:
   
print(i)
print(bric.issuperset(bri))
bri.remove(
'Russia')#删除
for i in bri & bric:
   
print(i)

True

False

Brazil

China

Russia

India

True

Brazil

India

引用

名称绑定给另一对象

shoplist =['apple','banana','mango','carrot']
mylist=shoplist
#引用,完全一样,操作影响彼此

print('Shoplist is',shoplist)
print('mylist is',mylist)

print('Copy by reference')
del shoplist[0]
print('Shoplist is',shoplist)
print('mylist is',mylist)

print('Copy by making a full slice')
mylist=shoplist[:]

del mylist[0]

print('Shoplist is', shoplist)
print('mylist is', mylist)

Shoplist is ['apple', 'banana', 'mango', 'carrot']

mylist is ['apple', 'banana', 'mango', 'carrot']

Copy by reference

Shoplist is ['banana', 'mango', 'carrot']

mylist is ['banana', 'mango', 'carrot']

Copy by making a full slice

Shoplist is ['banana', 'mango', 'carrot']

mylist is ['mango', 'carrot']

str

name='Swaroop'
if name.startswith('Swa'):  #查找字符串是否以该内容开头
   
print('Yes,the string starts with "Swa"')
if 'a' in name:
   
print('Yes,it contains the string "a"')
if name.find('war')!=-1: #用于定位字符串中给定的子字符串的位置
   
print('Yes,it contains the string "war"')
delimiter=
'_*_'
mylist=['Brazil','Russia','India','China']
print(delimiter.join(mylist))  #join将每一项目之间的分隔符,并以此生成并返回一串大的字符串

Yes,the string starts with "Swa"

Yes,it contains the string "a"

Yes,it contains the string "war"

Brazil_*_Russia_*_India_*_China

面向对象编程

 字段(Field)、方法(Method)组成类的属性,分为实例变量和类变量

引用对象本身使用self名称,Python中self相当于C++、Java、C#中的this指针

class Person:
   
pass  #一个空的代码块
p=Person()
print(p)

<__main__.Person object at 0x000002ED560C45C0>

方法

class Person:
   
def say_hi(self):
       
print('Hello,I am Yangyuying')
p=Person()
p.say_hi()
#或者Person().say_hi()

Hello,I am Yangyuying

__init__方法

对象实例化时立即运行

class Person:
   
def __init__(self,name):
       
self.name=name
   
def say_hi(self):
       
print('Hello,I am',self.name)
p=Person(
'S1')
p.say_hi()
#或者Person().say_hi()

Hello,I am S1

建立对象时首先运行__init__方法进行对象的初始化

类变量和对象变量

类变量是共享的,可以被属于该类的所有实例访问

对象变量由类的每一个独立的对象或实例所拥有

class Robot:
    population=
0 #类变量

   
def __init__(self,name):
       
self.name=name
       
print('(Initializing {})'.format(self.name))
        Robot.population+=
1

   
def die(self):
       
print('{} is being destroyed!'.format(self.name))
        Robot.population-=
1
       
if Robot.population==0:
           
print('{} was the last one'.format(self.name))
       
else:
           
print('There are still {:d} robots working.'.format(Robot.population))

   
def say_hi(self):
       
print('Greeting,my masters call me {}'.format(self.name))
   
@classmethod
   
def how_many(cls):
       
print('We have {:d} robots.'.format(Robot.population))

droid1 = Robot(
'R1-D1')
droid1.say_hi()
Robot.how_many()

droid2 = Robot(
'R2-D2')
droid2.say_hi()
Robot.how_many()


print("\nRobots can do some work here.\n")

print("Robots have finished their work.So let's destry them.")
droid1.die()
droid2.die()

Robot.how_many()

(Initializing R1-D1)

Greeting,my masters call me R1-D1

We have 1 robots.

(Initializing R2-D2)

Greeting,my masters call me R2-D2

We have 2 robots.

 

Robots can do some work here.

 

Robots have finished their work.So let's destry them.

R1-D1 is being destroyed!

There are still 1 robots working.

R2-D2 is being destroyed!

R2-D2 was the last one

We have 0 robots.

当一个对象变量和一个类变量名称相同时,类变量将会被隐藏 @classmethod用来修饰类方法。本例当中所有类成员都是公开的,若使用数据成员并在其名字中使用双下划线作为前缀,__privatevar python将会调整为私有变量

继承(Inherit

代码的重用:如学校中,公共类SchoolMember,教师和学生都从中继承,在子类中添加独有的字段

多态性(Polymorphism

父类型可以使用子类型来替换,SchoolMember类称为基类,Teacher和Student类称为派生类

class SchoolMember:
   
def __init__(self,name,age):
       
self.name=name
       
self.age=age
       
print('(Initialized SchoolMember:{})'.format(self.name))
   
def tell(self):
       
print('Name:"{}" Age:"{}"'.format(self.name,self.age),end=' ')

class Teacher:
   
def __init__(self,name,age,salary):
        SchoolMember.
__init__(self,name,age)
       
self.salary=salary
       
print('(Initialized Teacher: {})'.format(self.name))

   
def tell(self):
        SchoolMember.tell(
self)
       
print('Salary: "{:d}"'.format(self.salary))

class Student:
   
def __init__(self,name,age,marks):
        SchoolMember.
__init__(self,name,age)
       
self.marks=marks
       
print('(Initialized Student: {})'.format(self.name))

   
def tell(self):
        SchoolMember.tell(
self)
       
print('Marks: "{:d}"'.format(self.marks))

t=Teacher(
'Mrs 1',40,5000)
s=Student(
'S1',25,95)
print()
members=[t
,s]
for member in members:
    member.tell()

(Initialized SchoolMember:Mrs 1)

(Initialized Teacher: Mrs 1)

(Initialized SchoolMember:S1)

(Initialized Student: S1)

 

Name:"Mrs 1" Age:"40" Salary: "5000"

Name:"S1" Age:"25" Marks: "95"

如果继承元组中超过一个类,则为多重继承

Python高度面向对象

输入与输出

input()与print()函数

在输入时,可使用str类的各种方法,rjust方法用来获得一个右对齐到指定宽度的字符串 下例:判断用户输入的是否为回文

def reverse(text):
   
return text[::-1#以步长为-1翻转文本

def is_palindrome(text):
   
return text==reverse(text)

something =
input('Enter something:')
if is_palindrome(something):
   
print('Yes,it is a palindrome')
else:
   
print("No.it isn't a palindrome")

Enter something:dewqwewq

No.it isn't a palindrome

 

Enter something:dadadad

Yes,it is a palindrome

文件

file类:read、readline、write方法打开使用文件,并读取和写入,close方法完成使用

poem='''
Programming is fun
when the work is done
if you wanna make your work also fun:
     use python!
'''


f=open('poem.txt','w')
f.write(poem)
f.close()

f=
open('poem.txt','r'#默认也是读,可省略'r'
while True:
    line=f.readline()
   
if len(line)==0:
       
break
   
print(line,end=' ')
f.close()

Programming is fun

      when the work is done

      if you wanna make your work also fun:

        use python!

先write写入,再read读出

使用内置open函数并指定文件名以及希望的打开模式打开一个文件,r(读)、w(写)、a(追加)。模式:文本(‘t’)、二进制模式(‘b’)

Pickle标准模块

将任何纯Python对象存储带一个文件当中,并稍后返回,持久地存储对象

import pickle
shoplistfile=
'shoplist.data'
shoplist=['apple','mango','carrot']

#写入文件中
f=open(shoplistfile,'wb') #以二进制形式写入
pickle.dump(shoplist,f)  #封装
f.close()

del shoplist #删除原变量

#从存储中读取

f=open(shoplistfile,'rb')
storedlist=pickle.load(f) 
#拆封
print(storedlist)

['apple', 'mango', 'carrot']

首先需要引入pickle包,将内容以二进制形式写入文件当中,使用pickle的dump函数进行封装。需要读取文件内容时,通过pickle的load函数来进行拆封,load函数用来接收返回的对象。

异常Exception

错误Error

异常

使用Try去读取用户的输入内容,使用ctrl-d查看异常

处理异常

使用try..except来处理异常状况,把通常的语句放在try代码块里,将错误处理器放在except代码块里

try:
    text=
input('Enter something-->')
except EOFError:
   
print('Why did you do an EOF on me?')
else:
   
print('You entered {}'.format(text))

Enter something-->^D

Why did you do an EOF on me?

 

Enter something-->daggdf

You entered daggdf

 

把所有可能引发异常或错误的语句放在try代码块中,并将相应的错误或异常的处理器(Handler)放在except子句或者代码块中,except语句可以处理特定的错误或者异常,或者是一个在括号中列出的错误或者异常,如果没有提供错误或者异常的名称,它将处理所有错误或者异常。所以至少有一句except字句与try相关联

抛出异常

通过raise语句引发异常

class ShortInputException(Exception):  #用户自定义的异常类
   
def __init__(self,length,atleast):
       
Exception.__init__(self)
       
self.length=length
       
self.atleast=atleast

try:
    text=
input('Enter something-->')
   
if len(text)<3:
       
raise ShortInputException(len(text),3)
   
#..... 可正常执行
except EOFError:
   
print('Why did you do an EOF on me?')
except ShortInputException as ex: #ex为该类存储为相应错误或者异常名
   
print(('ShortInputException:The input was '+'{0} long,expected at least {1}').format(ex.length,ex.atleast))
else:
   
print('No exception was raised.')

Enter something-->a

ShortInputException:The input was 1 long,expected at least 3

 

Enter something-->abcd

No exception was raised.

Try…Finally

无论是否发生异常都会执行的代码块在finally

import sys
import time

f=
None
try
:
    f=
open('poem.txt')
   
while True:
        line=f.readline()
       
if len(line)==0:
           
break
       
print(line,end=' ')
        sys.stdout.flush()  #
以便立即打印到屏幕
       
print('Press CTRL+d now.')
        time.sleep(
2)  #每次休眠2秒
except IOError:
   
print("Could not find file poem.text")
except EOFError:
   
print("!!You choose EOF")
finally:
   
if f:
        f.close()
   
print("(Cleaning up:Closed the file)")

Press CTRL+d now.

Programming is fun

 Press CTRL+d now.

when the work is done

 Press CTRL+d now.

if you wanna make your work also fun:

 Press CTRL+d now.

^D

     use python!

 Press CTRL+d now.

(Cleaning up:Closed the file)

with语句

with语句所使用的协议,会获取由open语句返回的对象,会在代码块开始之前调用thefile.__enter__函数,在执行结束之后调用thefile.__exit__

with open("poem.txt") as f:
   
for line in f:
       
print(line,end=' ')

Programming is fun

  when the work is done

if you wanna make your work also fun:

      use python!

标准库

Python标准库中包含了大量有用的模块

sys模块

针对特定系统的功能sys.version_info提供版本信息

import sys
print(sys.version_info)

sys.version_info(major=3, minor=5, micro=4, releaselevel='final', serial=0)

日志模块logging

os模块用于和操作系统交互,platform模块用以获取平台-操作系统的信息,logging模块用来记录信息

import os
import platform
import logging

if platform.platform().startswith('Windows'):
    logging_file=os.path.join(os.getenv(
'HOMEDRIVE'),os.getenv('HOMEPATH'),'test.log')
else:
    logging_file=os.path.join(os.getenv(
'HOME'),'test.log')
print("Logging to",logging_file)

logging.basicConfig(
   
level=logging.DEBUG,
   
format='%(asctime)s : %(levelname)s : %(message)s',
   
filename=logging_file,
   
filemode='w'
)

logging.debug(
"Start of the program")
logging.info(
"Doing something")
logging.warning(
"Dying now")

Logging to C:\Users\yyy\test.log

传递元组

从一个函数中返回两个不同的值,使用元组

Lambda表格

points=[{'x':2,'y':3},{'x':4,'y':1},{'x':9,'y':-3}]
points.sort(
key=lambda i:i['x'])
print(points)

[{'y': 3, 'x': 2}, {'y': 1, 'x': 4}, {'y': -3, 'x': 9}]

使用 lambda中表达式作为排序的依据

列表推导

listone=[2,3,4]
listtwo=[
2*i for i in listone if i>2]
print(listtwo)

[6, 8]

在函数中接收元组和字典

分别使用*或者**作为元组或者字典的前缀

def powersum(power,*args):
    total=
0
   
for i in args:
        total+=
pow(i,power)
   
return total

print(powersum(2,3,4))
print(powersum(2,10))

25

100

assert语句

用以断言某事是真的,如果不是真的就会抛出异常

mylist=['item']
assert len(mylist)<=1

Process finished with exit code 0

mylist=['item']
assert len(mylist)>10

Traceback (most recent call last):

  File "E:/Python_workspace/HelloWorld/HelloWorld.py", line 522, in <module>

    assert len(mylist)>10

AssertionError

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值