Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
Python 函數(shù)的返回值
發(fā)布于:2023-09-11 15:24:48

Python 7天快速入門完整視頻教程https://www.bilibili.com/video/BV1o84y1Z7J1

 

Python   函數(shù)的返回值

 

函數(shù)執(zhí)行完畢,可以返回?cái)?shù)據(jù)給方法的調(diào)用者。(可以返回多個(gè)數(shù)據(jù)),通過(guò)return關(guān)鍵字

 

# 定義加方法函數(shù)
def add(x, y):
    result = x + y
    # 通過(guò)return關(guān)鍵字,把x+y的結(jié)果返回給函數(shù)的調(diào)用者
    return result


# 定義變量r,接收函數(shù)的返回值
r = add(1, 2)
print(f"調(diào)用add(1, 2)的返回結(jié)果是{r}")

r2 = add(2, 3)
print(f"調(diào)用add(2, 3)的返回結(jié)果是{r2}")

 

運(yùn)行結(jié)果:

 

調(diào)用add(1, 2)的返回結(jié)果是3
調(diào)用add(2, 3)的返回結(jié)果是5

 

如果程序需要有多個(gè)返回值,則既可將多個(gè)值包裝成列表之后返回,也可直接返回多個(gè)值。如果Python函數(shù)直接返回多個(gè)值,Python會(huì)自動(dòng)將多個(gè)返回值封裝成元組。(后續(xù)講到元組,我們給下實(shí)例講解下)

 

作業(yè):定義減法函數(shù),要有返回值。調(diào)用3次。

 

如果函數(shù)沒有使用return語(yǔ)句返回?cái)?shù)據(jù),則函數(shù)返回的是None值。None是空的意思。

看下案例:

 

# 定義最基礎(chǔ)函數(shù) helloworld
def say_helloworld():
    print("Python大爺你好,學(xué)Python,上www.magnapowered.com")


result = say_helloworld()
print(f"返回結(jié)果{result},類型{type(result)}")

 

輸出結(jié)果:

 

Python大爺你好,學(xué)Python,上www.magnapowered.com
返回結(jié)果None,類型<class 'NoneType'>

 

上面案例等同于return None

 

# 定義最基礎(chǔ)函數(shù) helloworld
def say_helloworld():
    print("Python大爺你好,學(xué)Python,上www.magnapowered.com")
    return None


result = say_helloworld()
print(f"返回結(jié)果{result},類型{type(result)}")

 

 

這個(gè)None值有哪些作用呢?

1,可以用于if判斷

 

def check_user(userName, password):
    if userName == 'python222' and password == '123456':
        return "success"
    else:
        return None


result = check_user('python222', '123')
print(f"返回結(jié)果{result}")
# 1,可以用于if判斷
if not result:
    print("登錄失敗")

 

 

2,可以用于聲明無(wú)初始化內(nèi)容的變量

 

# 2,可以用于聲明無(wú)初始化內(nèi)容的變量
userName = None

 

 

 

轉(zhuǎn)載自: