Return Statement
return 陳述句
我們來看看以下的範例:
def whichArea(area):
if area == 'Taiwan':
return area + '! , we are from same area.'
else:
return area + ', I am from Taiwan.'
print('Hi, my name is Jason. I am from Taiwan.')
print('Where are you from?')
userInput = input()
response = whichArea(userInput)
print(response)
print('Nice to meet you~')
函式是可以回傳值的,當我們要函式回傳值,我們必須使用retrun
這個關鍵字。
這個範例說明著函式whichArea(area)
回傳一個值,並將回傳的值指派給變數response
,這樣的方式你可以重複使用變數response
。
None
我們來看看以下的範例:
def hello1():
print('Hello, World!')
userInput = hello1()
print(userInput)
print(type(userInput))
print(None == userInput)
print('value is ' + userInput)
當函式沒有return
這個關鍵字時,回傳的值是一個NoneType
型別的東西,值是None
。
當我們執行以上的程式碼時,5~8行可以正常的執行,我們可以觀察看看執行結果,來理解None是什麼東西。
而第9行,則會執行錯誤,說明著None雖然可以被印出來,但是當它與'value is '
字串是不能直接相接的, 因為userInput是一個NoneType
型別的值,我們必須將它轉型str(userInput)
,我們才能將它與字串相接。
利用return中斷函式
我們來看看以下的範例:
def helloWay(country):
if country == 'TW':
return '你好~'
if country == 'US':
return 'How are you~'
if country == 'JP':
return 'Konichiwa~'
return 'Hi~'
userInput = input('您的國家是?')
print(helloWay(userInput))
當函式第一次遇到return
關鍵字時,就會直接return你給定的值或是表達式,接下來的程式碼,皆不會執行。
Last updated
Was this helpful?