Chat 9 ImportAndException
Python can write to py files and run files directly
%%writefile ex1.py
PI = 3.1416
def sum(lst):
tot = lst[0]
for value in lst[1:]:
tot = tot + value
return tot
w = [0, 1, 2, 3]
print sum(w), PI
%run ex1.py
Of course I can also import this file directly
import ex1
print ex1.PI
reload(ex1)
# 重新载入ex1,这样可以重新
import os
os.remove('ex1.py')
# 删除这个文件
Sometimes we want to use a .py
file as both a script and a module, and __name__
this property can be used at this time.
__name__
The value will only be if the file is being executed as a script '__main__'
, so we can:
if __name__ == '__main__':
Suppose we have a folder like this:
foo/
__init__.py
bar.py
(defines func)baz.py
(defines zap)
Import package requirements:
- folder
foo
in Python 's search path __init__.py
Indicates thatfoo
is a package, which can be an empty file.
It seems that there is no need to write something in python3
python2 needs to write import bar, baz
Introduce the exception
If the following function is negative, there will be a bug
import math
while True:
text = raw_input('> ')
if text[0] == 'q':
break
x = float(text)
y = math.log10(x)
print "log10({0}) = {1}".format(x, y)
we can use try
import math
while True:
try:
text = raw_input('> ')
if text[0] == 'q':
break
x = float(text)
y = math.log10(x)
print "log10({0}) = {1}".format(x, y)
except ValueError:
print "the value must be greater than 0"
import math
while True:
try:
text = raw_input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print "1 / log10({0}) = {1}".format(x, y)
except Exception:
print "invalid value"
import math
while True:
try:
text = raw_input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print "1 / log10({0}) = {1}".format(x, y)
except (ValueError, ZeroDivisionError):
print "invalid value"
import math
while True:
try:
text = raw_input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print "1 / log10({0}) = {1}".format(x, y)
except ValueError:
print "the value must be greater than 0"
except ZeroDivisionError:
print "the value must not be 1"
# 这样就可以像if elif一样
import math
while True:
try:
text = raw_input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print "1 / log10({0}) = {1}".format(x, y)
except ValueError as exc:
if exc.message == "math domain error":
print "the value must be greater than 0"
else:
print "could not convert '%s' to float" % text
except ZeroDivisionError:
print "the value must not be 1"
except Exception as exc:
print "unexpected error:", exc.message
When we except Exception
use , all Exception
and its derived subclasses are captured, but not all exceptions are derived from the Exception
class , and there may be some situations that cannot be captured. Therefore, a more general approach is to use this form :
try:
pass
except:
pass
Such unspecified exception type will catch all exceptions, but this form is not recommended.
We can also use finally, that is, no matter what, it will be executed
try:
print 1 / 0
except ZeroDivisionError:
print 'divide by 0.'
finally:
print 'finally was called.'
Chat10 Warning and IO
There are cases where I want the program to keep running, and then I need the user to know the following things
import warnings
def month_warning(m):
if not 1<= m <= 12:
msg = "month (%d) is not between 1 and 12" % m
warnings.warn(msg, RuntimeWarning)
month_warning(13)
warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)
month_warning(13)
The following describes the IO operation
Write the test file:
%%writefile test.txt
this is a test file.
hello world!
python is good!
today is a good day.
read file
f = open('test.txt')
f = file('test.txt')
text = f.read()
print text
f = open('test.txt')
lines = f.readlines()
print lines
# readlines 方法返回一个列表,每个元素代表文件中每一行的内容:
f.close()
write file
f = open('myfile.txt', 'w')
f.write('hello world!')
f.close()
print open('myfile.txt').read()
f = open('myfile.txt', 'w+')
f.write('hello world!')
f.seek(6)
print f.read()
f.close()
# seek就是移动到第4个字符