函數作用
- 降低編程難度
把複雜問題轉化成一系列簡單的小問題 - 代碼重用
可以在一個程序的多個位置使用,也可以在多個程序中使用
函數的定義 ##
通常使用def語句,形式如下:
def 函數名(參數列表): #可以沒有參數
函數體
# 如果函數名含有兩個以上的單詞,第二個單詞的首字母大寫
例如:
def addNum(num1, num2):
print num1+num2
函數的調用
函數名(參數列表)
def addNum(a, b):
print a+b
# 函數調用
addNum(1, 2)
3
函數參數
函數參數:形式參數和實際參數
形式參數:定義函數時,圓括號裏面的變量稱爲形式參數。
實際參數:調用函數時,圓括號裏面的變量就是實際參數。
缺省參數,也稱爲默認參數
注:默認參數在函數定義的時,必須放在函數參數列表的最右邊
#/usr/bin/python
#coding:utf8
import MySQLdb
# x,y 爲形式參數
def fun(x, y):
if x == y:
print x, " = ", y
else :
print x, " != ", y
s1 = raw_input("please input a string: ")
s2 = raw_input("please input a string: ")
#s1和s2爲實際參數
fun(s1, s2)
#在調用函數的時候,因爲在傳參的時候,不指定形式參數的時候,默認的順序是函數定義的時候參數的順序,如果指定的話,可以隨意調換
fun(x = s1, y = s2)
fun(y = s1, x = s2)
host = "localhost"
user = "root"
passwd = "test"
database = "hive"
SQL = "show tables"
#函數有默認參數時,默認參數必須放在參數最右邊,下面的定義是錯誤的
def fun2(host, user, passwd, database = "mysql", SQL):
conn = MySQLdb.connect(host, user, passwd, database)
cur = conn.cursor()
cur.execute(SQL)
tables = cur.fetchall()
for table in tables:
print table[0]
#改爲下面的情況,就可以正常運行了
def fun2(host, user, passwd, SQL, database = "mysql"):
conn = MySQLdb.connect(host, user, passwd, database)
cur = conn.cursor()
cur.execute(SQL)
tables = cur.fetchall()
for table in tables:
print table[0]
fun2(host, user, passwd, SQL, database)
fun2(host, user, passwd, SQL)
#運行的時候,會出現以下錯誤
python 9.py
File "9.py", line 31
def fun2(host, user, passwd, database = "mysql", SQL):
SyntaxError: non-default argument follows default argument