Python学习笔记(十二)

来源:互联网 发布:影响因素分析模型知乎 编辑:程序博客网 时间:2024/06/07 17:07

1.语法错误和异常错误

while True print("Hello Python")

Error Message:
File “C:\Programming\eclipse\project\PythonStudy\Exception.py”, line 9
while True print(“Hello Python”)
^
SyntaxError: invalid syntax

2.Exception

print(8/0)

Error Message:
Traceback (most recent call last):
File “C:\Programming\eclipse\project\PythonStudy\Exception.py”, line 12, in
print(8/0)
ZeroDivisionError: division by zero

3.Not defined

print(hello * 4)

Traceback (most recent call last):
File “C:\Programming\eclipse\project\PythonStudy\Exception.py”, line 14, in
print(hello * 4)
NameError: name ‘hello’ is not defined

4.Can’t convert ‘int’ object to str implicitly

num = 6print("Hello Python!" + num)

Traceback (most recent call last):
File “C:\Programming\eclipse\project\PythonStudy\Exception.py”, line 17, in
print(“Hello Python!” + num)
TypeError: Can’t convert ‘int’ object to str implicitly

    5.
while True:    try:        x = int(input("Please enter a number: "))        break    except ValueError:        print("Not vaild input, try again...")
    6.
try:    f = open("setence.txt")    s = f.readline()    i = int(s.strip())except OSError as err:    print("OS Error : {}".format(err))except ValueError as err:print("Could not convert data to an integer.")f = open("setences.txt")while True:    try:        s = f.readline()        i = int(s.strip())        print(i)           if i == 5:            break    except OSError as err:        print("OS Error : {}".format(err))    except ValueError as err:        print("Could not convert data to an integer.")f.close

7.面向对象和装饰器
面向对象编程:
类(Class):现实中一类食物的封装(比如:学生)
类:属性(比如:名字,成绩)
类对象
实例对象
引用:通过引用对类的属性和方法进行操作
实例化:创建一个类的具体实例对象(比如:张三)

#object-Oriented and decoratorclass Student:    def __init__(self, name, grade):        self.name = name        self.grade = grade    def introduce(self):        print("Hi, I am " + self.name)        print("My grade is " + str(self.grade))    def improve(self,amount):        self.grade = self.grade + amount        print("According to the help from my teacher, my grade is " + str(self.grade)+" now")jim = Student("Jim", 86)jim.introduce()jim.improve(14)

8.装饰器

# decoratordef add_candles(cake_func):    def insert_candels():        return cake_func() + " candles"    return insert_candels()def make_cake():    return "cake"gift_func = add_candles(make_cake)print(make_cake())print(gift_func)
def add_candles(cake_func):    def insert_candels():        return cake_func() + " candles"    return insert_candels()def make_cake():    return "cake"make_cake = add_candles(make_cake)print(make_cake)
def add_candles(cake_func):    def insert_candels():        return cake_func() + " candles"    return insert_candels()@add_candlesdef make_cake():    return "cake"#make_cake = add_candles(make_cake)print(make_cake)