<strong>函數function</strong>有返回值
過程procedure簡單的特殊的沒有返回值
python嚴格來說只有函數沒有過程
>>> def hello():
print("hello")
>>> temp = hello()
hello
>>> temp
>>> print(temp)
None #就算hello()沒有寫return語句 python也返回至None
>>> type(temp)
<class 'NoneType'>
返回值
在許多編程語言中,說函數是一個整型的函數 意思是函數會返回一個整型的返回值
python不是 python是動態的確定類型 賦值時編語器自動判斷變量是什麼類型
python沒有變量 只有名字
python可以返回多個值
>>> def back():
return[1, "fish", 3.14] #返回多個類型的值>>列表
>>> back()
[1, 'fish', 3.14]
>>> def back():
return 1, "fish", 3.14 #元組 只需逗號隔開,可以不加()
>>> back()
(1, 'fish', 3.14) #利用一個元組打包多個值
變量的作用域 變量的可見性
一般編成語言分 局部變量 和 全局變量
def discounts(price, rate):
final_price = price * rate
return final_price
old_price = float(input("請輸入原價:"))
rate = float(input("請輸入折扣率:"))
new_price = discounts(old_price, rate)
print("打折後價格是:", new_price)
print("這裡試圖打印局部變量final_price的值", final_price)
print("這裡試圖打印局部變量final_price的值", final_price)
報錯!!
#price rate final_price是局部變量 >>只在discounts函數中起作用
請輸入原價:100
請輸入折扣率:0.8
打折後價格是: 80.0
Traceback (most recent call last):
File "D:/python/practice/L19class.py", line 9, in <module>
print("這裡試圖打印局部變量final_price的值", final_price)
NameError: name 'final_price' is not defined
總結:
在函數裡面的變量>>局部變量
old_price, new_price, rate 都在函數外定義 >>全局變量 作用域是整個模塊
def discounts(price, rate):
final_price = price * rate
print("這裡試圖打印全局變量old_price的值:", old_price)
return final_price
old_price = float(input("請輸入原價:"))
rate = float(input("請輸入折扣率:"))
new_price = discounts(old_price, rate)
print("打折後價格是:", new_price)
>>>
請輸入原價:100
請輸入折扣率:0.9
這裡試圖打印全局變量old_price的值: 100.0
打折後價格是: 90.0
全局變量的作用域是整個範圍 但使用時要非常小心
def discounts(price, rate):
final_price = price * rate
# print("這裡試圖打印全局變量old_price的值:", old_price)
old_price = 50 #局部變量old_price1
print("修改後old_price的值是1:", old_price)
return final_price
old_price = float(input("請輸入原價:")) #全局變量old_price2
rate = float(input("請輸入折扣率:"))
new_price = discounts(old_price, rate)
print("打折後價格是:", new_price)
print("修改後old_price的值是2:", old_price)
>>>
請輸入原價:100
請輸入折扣率:0.9
修改後old_price的值是1: 50
打折後價格是: 90.0
修改後old_price的值是2: 100.0
在discounts 函數中 python會自動創建一個局部變量old_price1 名字跟全局變量old_price2一樣
在不同的存儲空間 不會互相影響
總結: 全局變量作用範圍在整個模塊,但不要試圖在函數中修改他 可以訪問 但修改的話 他就會在函數中創建一個名字一樣的局部變量!