7 函数

#! /usr/bin/python
# -*- coding: utf8 -*-
def sum(a,b):
  return a+b
 
func = sum
r = func(5,6)
print (r)
# 提供默认值
def add(a,b=2):
  return a+b
r=add(1)
print (r)
r=add(1,5)
print (r)
# 一个好用的函数
#! /usr/bin/python
# -*- coding: utf8 -*-
# The range() function
a =range (1,10)
for i in a:
  print (i)
  a = range(-2,-11,-3) # The 3rd parameter stands for step
for i in a:
  print (i)
输出:
11
3
6
1
2
3
4
5
6
7
8
9
-2
-5
-8
>>> 
知识点: 
Python 不用{}来控制程序结构,他强迫你用缩进来写程序,使代码清晰. 
定义函数方便简单 
方便好用的range函数

8、异常处理

#! /usr/bin/python
s=input("Input your age:")
if s =="":
  raise Exception("Input must no be empty.")
try:
  i=int(s)
except Exception as err:
  print(err)
finally: # Clean up action
  print("Goodbye!") 
输出:
Input your age:11
Goodbye!
>>> 

9、文件处理

  对比Java,python的文本处理再次让人感动

#! /usr/bin/python
spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r") # Opens file for reading
for line in f:
  print("每一行的数据是:%s"%line)
f.close() 

知识点: 
open的参数:r表示读,w写数据,在写之前先清空文件内容,a打开并附加内容. 
打开文件之后记得关闭

10 类和继

class Base:
def __init__(self):
  self.data = []
def add(self, x):
  self.data.append(x)
def addtwice(self, x):
  self.add(x)
  self.add(x)
# Child extends Base
class Child(Base):
  def plus(self,a,b):
    return a+b
oChild =Child()
oChild.add("str1")
print (oChild.data)
print (oChild.plus(2,3))

知识点: 
* self:类似Java的this参数 
'''

11 包机制

  每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:

# a.py
def add_func(a,b):
return a+b
# b.py
from a import add_func # Also can be : import a
print ("Import add_func from module a")
print ("Result of 1 plus 2 is: ")
print (add_func(1,2)) # If using "import a" , then here should be "a.add_func" 

  module可以定义在包里面.Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示:

parent
--__init_.py<br>--child
-- __init_.py
--a.py
b.py 

  那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:

import sys
print(sys.path) 

  通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:

import sys
import os
sys.path.append(os.getcwd()+'\\parent\\child')
print(sys.path)
from a import add_func
 
print (sys.path)
print ("Import add_func from module a")
print ("Result of 1 plus 2 is: ")
print (add_func(1,2))

知识点:
如何定义模块和包
如何将模块路径添加到系统路径,以便python找到它们
如何得到当前路径
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐