【Python】基础知识-自学笔记

一、输出与输入

1、输出

print("hello python")
输出内容:

name="zhangsan"
print("hello %s,Nice to meet you!" %name)
输出内容:

#%s(string)只能打印字符串
name="Lisi"
print("hello %s,Nice to meet you!" %name)
输入内容:

#%d(data)只能打印数字
age=27
print("You are %d!" %age)
输出内容:

#%r,不知道打印类型时用%r
n=100
print("You print is %r." %n)
输出内容:

n="abc"
print("You print is %r." %n)
输出内容:

name="zhangsan"
age=22
print("student info:%s %d." %(name,age))
输出内容:

#python当中,不区分单引号与双引号,也就是说,单引号和双引号都可以用来表示一个字符串。
print("hello")
print('world')
输出内容:

#单引号与双引号可以交互嵌套使用,但不能交叉使用。
print("你说:'早上你好'")
print('我说:"今天天气不错"')
输出内容:

#交叉使用报错
print("你微笑着'向我道别".')
输出内容:

2、输入

#input输入的例子
n=input("Enter any content:")
print ("Your input is %r" %n)
输入与输出:

3、引号与注释

#单行注释
print("hello world") #打印hello world
#多行注释用三对引号表示,同样不区分单、双引号
输出内容:


"""
    我们实现一个伟大的程序
    那么是
    print一行数据^_^
"""
'''
    This is a 
    Multi line comment
'''

二、分支与循环

1、if语句

#if语句  对a与b赋值,通过if语句判断a与b的大小,如果a大于b则输出a max!,否则输出b max! Python未使用{}表示语句体,所以使用缩进判断语句体,默认4个空格
a=2
b=1
if a>b:
    print("a max!")
else:
    print("b max!")
输出结果:

#if语句通过==运算符判断相等
student="xiaoming"
if student!="xiaoming":
    print("xiaoming,You are on duty today.")
else:
    print("Please call xiaoming to duty")
输出结果:

#如果不相等,则用!=运算符表示。也可以使用in和not in表示包含的关系。
hi="hello world"
if "hello" not in hi:
    print("Contain")
else:
    print("Not Contain")
输出结果:

#if语句进行布尔类型的判断
a=False
if a:
    print("a is True")
else:
    print("a is not True")
输出结果:

#多重条件判断
results=72
if results>=90:
    print('优秀')
elif results>=70:
    print('良好')
elif results>=60:
    print('及格')
else:
    print('不及格')
输出结果:

2、for语句

for i in "hello world":
    print(i)
输出结果:

fruits=['banana','apple','mango']
for fruit in fruits:
    print(fruit)
输出结果:

#如果需要进行一定次数的循环,则需要借助range()函数。默认从零开始循环。
for i in range(5):
    print(i)
输出结果:

#range()函数,设置起始位置和步长
for i in range(1,10,2):
    print(i)
输出结果:

#range(start,end[,step])
#range()函数,start表示开始位置,end表示结束位置,step表示每一次循环的步长。

三、数组与字典

1、数组

#数组用方括号([])表示,里面的每一项用逗号(,)隔开
lists=[1,2,3,'a',5]
print(lists)
输出结果:

print(lists[0])
输出结果:

print(lists[4])
输出结果:

lists[4]='b'
print(lists[4])
输出结果:

lists.append('c')
print(lists)
输出结果:

#python允许在数组里面任意地放置数字或字符串。需要注意的是,数组下标是从0开始的,所以,lists[0]会输出数组中的第一项。append()函数可以向数组末尾追加新的项。

2、字典

#字典用花括号({})表示,里面的项成对出现,一个key对应一个value;key与value之间用冒号(:)分隔;不同的项之间用逗号(,)分隔。
dicts={"username":"zhangsan",'password':123456}
print(dicts.keys())
输出结果:

print(dicts.values())
输出结果:

print(dicts.items())
输出结果:

for k,v,in dicts.items():
    print("dicts keys is %r" %k)
    print("dicts values is %r" %v)
输出结果:

#python规定一个字典中的key必须独一无二,value可以相同
'''
keys()函数返回字典key的列表,values()函数返回字典value的列表,items()函数将所有的字典项以列表方式返回,这列列中的每一项都包含key和value,但是项在返回时并不会按照它们在字典中的存放顺序。
则可以通过下面的方法。
通过zip方法合并两个List为Dictionary
遍历会按原先的顺序
'''
keys=["b","a","c","e","d"]
values=["2","1","3","5","4"]
for key,value in zip(keys,values):
    print(key,value)
输出结果:

四、函数、类和方法

1、函数

#在Python中通过def关键字来定义函数。 def add(a,b): print(a+b) add(3,5)
输出内容:


#创建一个add()函数,此函数接收两个参数a、b,通过print()打印a+b的结果。调用add()函数,并且传两个参数3、5给add()函数。 #通常add()函数不会直接打印结果,而是将处理结果通过return关键字返回。 def add(a=1,b=2): return a+b print(add()) print(add(3,5))
输出内容:

#如果调用时不传参,那么add()函数就使用默认参数进行计算;如果传参则计算参数的值。

2、类和方法

#在面向对象编程的世界里,一切皆为对象,抽象的一组对象就是类。例如,汽车是一个类,而张三家的奇瑞汽车就是一个具体的对象。在Python中用class关键字来创建类。
class A(object):
    def add(self,a,b):
        return a+b
count=A()
print(count.add(4,6))
输出结果:

"""
上面创建了一个A类(在python3中object为所有类的基类,所有类在创建时默认继承object,所以不声明继承object也可以),在类下面创建了一个add()方法。方法的创建同样使用关键字def,唯一不同的是,
方法的第一个参数必须是存在的,一般习惯命名为"self",但是在调用这个方法时不需要为这个参数传值。
一般在创建类时会首先声明初始化方法__init__().
注意:init的两侧是双下划线,当我们在调用该类时,可以用来进行一些初始化工作。
"""
class A():
    def __init__(self,a,b):
        self.a=int(a)
        self.b=int(b)
    def add(self):
        return self.a+self.b
count=A('4',5)
print(count.add())
输出结果:

"""
当我们调用A类时首先会执行的它的__init__()方法,所以需要对其进行传参。初始化所做的事情就是将输入的参数转化为int类型,这样可以在一定程度上保证程序的容错性。而add()方法可以直接拿初始化方法
__init__()的self.a和self.b两个数进行计算。所以,我们在调用A类下面的add()方法时,不需要再进行传参。
"""
#下面再来了解一下Python中类的继承。
class A():
    def add(self,a,b):
        return a+b
class B(A):
    def sub(self,a,b):
        return a-b
print(B().add(4,9))
print(B().sub(8,3))
输出结果:

"""
首先,我们创建了一个A类,在其下面创建add()方法用于计算两个参数相加;接着创建B类,继承A类,并且又继续创建了sub()方法用于计算两个参数相减。因为B类继承了A类,所以B类自然也拥有了add()方法,
从而可以直接通过B类调用add()方法。
"""

五、模组

"""
模组更通俗地叫类库或模块。前面的练习中我们没有用到的模块,但这也只是在练习的时候,在实际开发中我们不可能不用到系统的标准模块,或第三方模块。
如果想实现与时间有关的功能,就需要调用系统的time模块。如果想实现与文件和文件夹有关的操作,就需要用到os模块。再例如我们通过Selenium实现的Web
自动化测试,那么Selenium对于Python来说就是一个第三方扩展模块。
"""
1、引用模块
#在Python中,通过import...或from...import...的方法引用模块,下面引用time模块。
import time
print(time.ctime())
输出结果:

#在time模块下面有一个ctime()方法用于获得当前时间,通过print()将当前时间打印出来。当然,如果确定了只会用到time下面的ctime()方法,也可以这样引入。
from time import ctime
print(ctime())
输出结果:

#现在使用就不必告诉python,ctime()方法是time模块所提供的了。但是有时候我们可能还会用到time模块下面的sleep()休眠方法,当然,我们也可以把sleep()方法引入进来。或许还会用到其他方法,这时可以一次性把time模块下的所有方法都引入进来。

from time import *
print(ctime())
print("休眠两秒")
sleep(2)
print(ctime())
'''
输出结果:

星号"*"用于表示模块下面的所有方法。你一定很好奇,time到底在哪儿?为什么import进来就可以用了?这时python语言提供的核心方法,而且经过了编译,
所以我们无法看到ctime()是如何取到系统的当前时间的,不过,可以通过help()方法查看time的帮助说明。
'''
import time
help(time)
输出结果:
-----------------------------------------------------------------------------------------
Help on built-in module time:

NAME
    time - This module provides various functions to manipulate time values.

DESCRIPTION
    There are two standard representations of time.  One is the number
    of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
    or a floating point number (to represent fractions of seconds).
    The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
    The actual value can be retrieved by calling gmtime(0).
    
    The other representation is a tuple of 9 integers giving local time.
    The tuple items are:
      year (including century, e.g. 1998)
      month (1-12)
      day (1-31)
      hours (0-23)
      minutes (0-59)
      seconds (0-59)
      weekday (0-6, Monday is 0)
      Julian day (day in the year, 1-366)
      DST (Daylight Savings Time) flag (-1, 0 or 1)
    If the DST flag is 0, the time is given in the regular time zone;
    if it is 1, the time is given in the DST time zone;
    if it is -1, mktime() should guess based on the date and time.
    
    Variables:
    
    timezone -- difference in seconds between UTC and local standard time
    altzone -- difference in  seconds between UTC and local DST time
    daylight -- whether local time should reflect DST
    tzname -- tuple of (standard time zone name, DST time zone name)
    
    Functions:
    
    time() -- return current time in seconds since the Epoch as a float
    clock() -- return CPU time since process start as a float
    sleep() -- delay for a number of seconds given as a float
    gmtime() -- convert seconds since Epoch to UTC tuple
    localtime() -- convert seconds since Epoch to local time tuple
    asctime() -- convert time tuple to string
    ctime() -- convert time in seconds to string
    mktime() -- convert local time tuple to seconds since Epoch
    strftime() -- convert time tuple to string according to format specification
    strptime() -- parse string to time tuple according to format specification
    tzset() -- change the local timezone

CLASSES
    builtins.tuple(builtins.object)
        struct_time
    
    class struct_time(builtins.tuple)
     |  The time value as returned by gmtime(), localtime(), and strptime(), and
     |  accepted by asctime(), mktime() and strftime().  May be considered as a
     |  sequence of 9 integers.
     |  
     |  Note that several fields' values are not the same as those defined by
     |  the C language standard for struct tm.  For example, the value of the
     |  field tm_year is the actual year, not year - 1900.  See individual
     |  fields' descriptions for details.
     |  
     |  Method resolution order:
     |      struct_time
     |      builtins.tuple
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  __reduce__(...)
     |      helper for pickle
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  tm_hour
     |      hours, range [0, 23]
     |  
     |  tm_isdst
     |      1 if summer time is in effect, 0 if not, and -1 if unknown
     |  
     |  tm_mday
     |      day of month, range [1, 31]
     |  
     |  tm_min
     |      minutes, range [0, 59]
     |  
     |  tm_mon
     |      month of year, range [1, 12]
     |  
     |  tm_sec
     |      seconds, range [0, 61])
     |  
     |  tm_wday
     |      day of week, range [0, 6], Monday is 0
     |  
     |  tm_yday
     |      day of year, range [1, 366]
     |  
     |  tm_year
     |      year, for example, 1993
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  n_fields = 9
     |  
     |  n_sequence_fields = 9
     |  
     |  n_unnamed_fields = 0
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.tuple:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __getitem__(self, key, /)
     |      Return self[key].
     |  
     |  __getnewargs__(...)
     |  
     |  __gt__(self, value, /)
     |      Return self>value.
     |  
     |  __hash__(self, /)
     |      Return hash(self).
     |  
     |  __iter__(self, /)
     |      Implement iter(self).
     |  
     |  __le__(self, value, /)
     |      Return self<=value.
     |  
     |  __len__(self, /)
     |      Return len(self).
     |  
     |  __lt__(self, value, /)
     |      Return self<value.
     |  
     |  __mul__(self, value, /)
     |      Return self*value.n
     |  
     |  __ne__(self, value, /)
     |      Return self!=value.
     |  
     |  __rmul__(self, value, /)
     |      Return self*value.
     |  
     |  count(...)
     |      T.count(value) -> integer -- return number of occurrences of value
     |  
     |  index(...)
     |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
     |      Raises ValueError if the value is not present.

FUNCTIONS
    asctime(...)
        asctime([tuple]) -> string
        
        Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
        When the time tuple is not present, current time as returned by localtime()
        is used.
    
    clock(...)
        clock() -> floating point number
        
        Return the CPU time or real time since the start of the process or since
        the first call to clock().  This has as much precision as the system
        records.
    
    ctime(...)
        ctime(seconds) -> string
        
        Convert a time in seconds since the Epoch to a string in local time.
        This is equivalent to asctime(localtime(seconds)). When the time tuple is
        not present, current time as returned by localtime() is used.
    
    get_clock_info(...)
        get_clock_info(name: str) -> dict
        
        Get information of the specified clock.
    
    gmtime(...)
        gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
                               tm_sec, tm_wday, tm_yday, tm_isdst)
        
        Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
        GMT).  When 'seconds' is not passed in, convert the current time instead.
        
        If the platform supports the tm_gmtoff and tm_zone, they are available as
        attributes only.
    
    localtime(...)
        localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                                  tm_sec,tm_wday,tm_yday,tm_isdst)
        
        Convert seconds since the Epoch to a time tuple expressing local time.
        When 'seconds' is not passed in, convert the current time instead.
    
    mktime(...)
        mktime(tuple) -> floating point number
        
        Convert a time tuple in local time to seconds since the Epoch.
        Note that mktime(gmtime(0)) will not generally return zero for most
        time zones; instead the returned value will either be equal to that
        of the timezone or altzone attributes on the time module.
    
    monotonic(...)
        monotonic() -> float
        
        Monotonic clock, cannot go backward.
    
    perf_counter(...)
        perf_counter() -> float
        
        Performance counter for benchmarking.
    
    process_time(...)
        process_time() -> float
        
        Process time for profiling: sum of the kernel and user-space CPU time.
    
    sleep(...)
        sleep(seconds)
        
        Delay execution for a given number of seconds.  The argument may be
        a floating point number for subsecond precision.
    
    strftime(...)
        strftime(format[, tuple]) -> string
        
        Convert a time tuple to a string according to a format specification.
        See the library reference manual for formatting codes. When the time tuple
        is not present, current time as returned by localtime() is used.
        
        Commonly used format codes:
        
        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.
        
        Other codes may be available on your platform.  See documentation for
        the C library strftime function.
    
    strptime(...)
        strptime(string, format) -> struct_time
        
        Parse a string to a time tuple according to a format specification.
        See the library reference manual for formatting codes (same as
        strftime()).
        
        Commonly used format codes:
        
        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.
        
        Other codes may be available on your platform.  See documentation for
        the C library strftime function.
    
    time(...)
        time() -> floating point number
        
        Return the current time in seconds since the Epoch.
        Fractions of a second may be present if the system clock provides them.

DATA
    altzone = -32400
    daylight = 0
    timezone = -28800
    tzname = ('Öйú±ê׼ʱ¼ä', 'ÖйúÏÄÁîʱ')

FILE
    (built-in)
------------------------------------------------------------------------------------------------------------
#pip所安装的Python的第三方类库或框架可以查看其类方法的实现。例如我们做Web自动化所用到的Selenium类库。
# Python所安装的第三方类库或框架模块默认存放在C:\Users\yww\AppData\Local\Programs\Python\Python35\Lib\site-package\目录下面,如果安装了selenium,那么就会在这个目录下找到Selenium目录。

2、模块调用
#既然可调用系统模块,那么可不可以自己创建一个模块,然后通过另一个程序调用?当然可以,对于一个软件项目来说不可能把所以代码都放在一个文件中实现,它们一般会按照一定规则在不同的目录和文件中实现。
#下面创建一个目录project,并在目录下创建两个文件,结构如下:
'''
project/
|-----pub.py
|-----count.py
在pub.py文件中创建add函数。
#pub.py
def add(a,b):
    return a+b
#count.py
from pub import add
print(add(11,5))
输出结果:

这样就实现了跨文件的函数调用。
知识延伸:如果你细心,一定会发现在project目录下多了一个__pycache__/pub.cpython-35.pyc文件,那么它的作用是什么呢?
为了提高模块加载的速度,每个模块都会在__pycache__文件夹中放置该模块的预编译模块,命名为module,version.pyc,version是模块的预编译版本编码,通常会包含Python的版本号。例如在CPython发行版3.5中,pub.py文件的预编译文件就是:__pycache__/pub.cpython-35.pyc。
'''
3、跨目录模块调用
'''
project1/
|-----model/
    |---pub.py
|-----count.py
在pub.py文件中创建add函数。
'''
#count.py
from model.pub import add
print(add(11,56))
输出结果:

4、进一步讨论跨目录模块调用
'''
project2/
|-----model/
    |---count.py
    |---new_count.py
|-----test.py
在pub.py文件中创建add函数。
#count.py
class A():
    def add(self,a,b):
        return a+b
#new_count.py
        from count import A
        class B(A):
            def sub(self, a, b):
                return a - b

        resule = B().add(2, 5)
        print(resule)

#test.py
from model import new_count
test=new_count.B()
test.add(2,5)
输出结果:

通过提示信息,在new_count.py文件中,找不到"count"模块,可刚刚才在执行new_count.py时是可以正常运行的。那么,要想弄清楚错误的原因,首先需要知道当Python执行"import"时到底做了哪些操作?
知识延伸 当Python在执行import语句时,到底进行了什么操作。按照Python的文档,它执行了如下操作:
第1步,创建一个新的module对象(它可能包含多个module);
第2步,把这个module对象插到sys.module中;
第3步,装载module的代码(如果需要,则必须先编译);
第4步,执行新的module中对应的代码。
在执行第3步时,首先需要找到module程序所在的位置,搜索的顺序是:
当前路径(以及从当前目录指定的sys.path),pythonPATH,再后是Python安装时设置的相关的默认路径。正因为存在这样的顺序,所以如果当前路径或PythonPATH中存在与标准module同样的module,则会覆盖标准module。
也就是说,如果当前目录下存在xml.py,那么在执行import xml时,导入的是当前目录下的module,而不是系统标准的xml。
了解了这些后,我们就可以先构建一个package,以普通module的方式导入,这样既可直接访问此package中的各个module。
理解了上面的过程,就很好理解报错原因了。站在new_count.py的位置,执行"from count import A",可查看当前目录下是否存"count"名字的文件或目录,当然是可以找到的:但是,站在test.py的位置执行"from count import A"时,
同样会在当前目录下找"count"名字的文件或目录,这个时候就找不到了。那么如何解决这个问题呢?
简单的做法是将导入方法修改为"from .count import A"在count前面加个点(.),用来告诉调用程序(test.py)count是相对于new_count.py的一个引入。读者可以尝试这样修改后再次运行test.py看是否还会报错?
不过这样的修改有副作用,当我们再次执行new_count.py时会引起新的错误。
new_count.py
from .count import A
class B(A):
    def sub(self,a,b):
        return a-b
resule=B().add(2,5)
print(resule)
输出结果:
Traceback (most recent call last):
  File "D:/Test/project2/model/new_count.py", line 1, in <module>
    from .count import A
SystemError: Parent module '' not loaded, cannot perform relative import
Python3提示:未加载父模块,不能执行相对导入。如果你认真阅读了Python的import规则,就知道我们将导入模块所在目录(.../model/目录)添加到系统环境变量path下,这样Python就可以找到了。
下面还原对new_count.py的修改,修改test.py文件如下。
import sys
sys.path.append("./model")    #将model目录添加到系统环境变量path下
from model import new_count
test=new_count.B()
test.add(2,5)
输出结果:

如果读者使用的是python2的话还需要在.../model/目录下创建一个__init__.py文件(文件内容可以为空),用来标识这是一个标准的包含了python模块的目录。
'''

六、异常

'''
python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,则程序就会用所谓的回溯(Traceback,一种错误信息)来终止执行。
在实际脚本开发中,有时程序并不像我们设计它时那样工作,他也有“生病”的时候,这时我们就可以通过异常处理机制,有预见性地获得这些病症,并开出药方。例如一个普通人,大冬天洗冷水澡,那么就有可能感冒,我们可以事先在冷水澡时准备好感冒药,
假如真感冒了,就立刻吃药。
open("abc.txt",'r')
'''
open("abc.txt",'r')
输出结果:

'''
我们通过open()方法以读"r"的方式打开一个abc.txt的文件。然后Python抛出一个FileNotFoundError类型的异常,它告诉我们:No such file or directory: 'abc.txt'(没有abc.txt这样的文件或目录)。当然找不到了,因为我们根本就没有创建这个文件。
既然知道执行open()一个不存在的文件时会抛FileNotFoundError异常,那么我们就可以通过python所提供的try...except语句来接收并处理这个异常。
'''
try:
    open("abc.txt", 'r')
except FileNotFoundError:
    print("异常了!")
输出结果:

try:
    print(aa)
except FileNotFoundError:
    print("异常了!")
输出结果:

'''
不是已经通过except去接收异常了么,为什么错误又出现了?如果细心查看错误信息就会发现,这次抛出的是个NameError类型的错误,而except FileNotFoundError只能接收到找不到文件的错误。就好像小明是肚子疼,但我们拿感冒药给他吃,当然解决不了问题。
这时我们需要换一个接收异常的类型就可以了。
'''

try:
    print(aa)
except NameError:
    print("这是一个name异常!")
输出结果:

'''
那么问题来了,我们的程序是怎么抛出不同类型错误的呢?
知识延伸 异常的抛出机制:
1.如果在运行时发生异常,则解释器会查找相应的处理语句(称为handler)。
2.如果在当前函数里没有找到的话,则它会将异常传递给上层的调用函数,看看那里能不能处理。
3.如果在最外层(全局"main")还是没有找到的话,那么解释器就会退出,同时打印出TraceBack,以便让用户找到错误产生的原因。
注意:虽然大多数错误会导致异常,但异常不一定代表错误,有时候它们只是一个警告,有时候是一个终止信号,例如退出循环等。
在Python中所有的异常类都继承Exception,所以可以使用它来接收所有类型的异常。
'''
try:
    open("abc.txt",'r')
except Exception:
    print("异常了----!")
输出结果:

#从python2.5版本之后,所有的异常类都有了新的基类BaseException。Exception同样也继承自BaseException,所以我们也可以使用BaseException来接收所有类型的异常。
try:
    open("abc.txt",'r')
    print(aa)
except BaseException:
    print("异常了========!")
输出结果:

#对于上面的例子,只要其中一行出现了异常就会print()异常信息,但是当打印异常时,我们并不能准确地知道到底是哪一行代码引起了异常,那么如何让Python直接告诉我们异常的原因呢?
try:
    open("abc.txt", 'r')
    print(aa)
except BaseException as msg:
    print(msg)
输出结果:

'''
我们在BaseException后面定义了msg变量用于接收异常信息,并通过print将其打印出来。
Python2中用逗号“,”代替“as”。
Python中的常见异常
BaseException:新的所有异常类的基类
Exception:所有异常类的基类,但继承BaseException类
AssertionError:assert语句失败
FileNotFoundError:试图打开一个不存在的文件或目录
AttributeError:试图访问的对象没有属性
OSError:当系统函数返回一个系统相关的错误,包括I/O故障,如“找不到文件”或“磁盘已满”时,引发此异常
NameError:使用一个还未赋值对象的变量
IndexError:当一个序列超出了范围
SyntaxError:当解析器遇到一个语法错误时引发
KeyBoardInterrupt:Ctrl+C被按下,程序被强行终止
TypeError:传入的对象类型与要求不符
'''

try:
    aa="异常测试:"
    print(aa)
except Exception as msg:
    print(msg)
else:
    print("没有异常!")
输出结果:

'''
这里我们对aa变量进行了赋值,所以没有异常将会执行else语句后面的内容。通常else语句只有在没有异常的情况下才会被执行,但有些情况下不管是否出现异常,这些操作都希望能被执行,例如文件的关闭、锁的释放、把数据库连接返还给连接池等操作。我们可以使用
try...except...finally...语句来实现这样的需求。
'''

try:
    print(aa)
except Exception as e:
    print(e)
finally:
    print("不管是否异常,我都会被执行。")
输出结果:

try:
    aa="异常测试:"
    print(aa)
except Exception as e:
    print(e)
finally:
    print("不管是否异常,我都会被执行。")
输出结果:

#对比两次的执行结果,就可以理解了finally语句的作用了。

'''
抛出异常
print()方法只能打印错误信息,Python中提供了raise方法来抛出一个异常信息。下面的例子演示了raise的用法。
'''
from random import randint
#生成一个1到9之间的随机整数
number=randint(1,9)
if number % 2==0:
    raise NameError("%d is even" %number)
else:
    raise NameError("%d is odd" %number)
输出结果:

'''
通过randint()方法随机生成1到9之间的整数,然后判断这个数字是奇数还是偶数,最后通过raise抛出NameError异常。其实,判断奇偶数与NameError之间没有任何关系,这里只是为了演示如何通过raise抛出各种类型的异常。
需要注意的是,raise只能使用Python中所提供的异常类,如果自定义一个abcError的异常,则Python会告诉你abcError没有定义。

注意事项:
1.项目不要创建在Python的安装目录中,初学者的心态是只有把程序建在Python的安装目录下才能运行,其实不然。例如你在C盘安装了音乐播放器,则只要把音乐文件设置为该播放器打开,那么在硬盘任何一个角落的音乐文件都能由该播放器打开。Python程序也是如此,
只要正确地把Python目录配置到环境变量path下,任何目录下Python程序都可以被执行。
2.项目的路径中不要出现中文或空格。例如,D:\自动化测试\xx项目\testcase\list\test.py,这可能会导致有些IDE打开该程序后无法执行,例如Sublime Text就无法运行这种目录下的文件。
3.项目的目录与文件名不要与引用类库同名。例如,D:\selenium\webdriver.py,这里会存在一个大坑,在创建目录与文件夹时一定要避免。如果不知道为什么,请回头去看一下Python的引包机制。
'''
发布了23 篇原创文章 · 获赞 6 · 访问量 4759

猜你喜欢

转载自blog.csdn.net/w68688686/article/details/103287042