亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的遞歸python函數不返回?

為什么我的遞歸python函數不返回?

呼如林 2019-05-30 17:35:38
為什么我的遞歸python函數不返回?我有一個叫做自己的函數:def get_input():     my_var = input('Enter "a" or "b": ')     if my_var != "a" and my_var != "b":         print('You didn\'t type "a" or "b". Try again.')         get_input()     else:         return my_varprint('got input:', get_input())現在,如果我只輸入“a”或“b”,一切正常:Type "a" or "b": a got input: a但是,如果我鍵入其他內容,然后再輸入“a”或“b”,我就會得到以下內容:Type "a" or "b": purple You didn't type "a" or "b". Try again. Type "a" or "b": a got input: None我也不知道原因get_input()正在回歸None,因為它只應該返回my_var。這個在哪里?None我是從哪里來的,我該如何修復我的功能?
查看完整描述

4 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

它又回來了None因為當您遞歸地調用它時:

if my_var != "a" and my_var != "b":
    print('You didn\'t type "a" or "b". Try again.')
    get_input()

.你不歸還價值

因此,當遞歸確實發生時,返回值就會被丟棄,然后從函數的末尾掉下來。從函數末尾掉下來意味著python隱式返回。None就像這樣:

>>> def f(x):...     pass>>> print(f(20))None

所以,而不是僅僅呼叫 get_input()在你的if聲明,您需要return它:

if my_var != "a" and my_var != "b":
    print('You didn\'t type "a" or "b". Try again.')
    return get_input()


查看完整回答
反對 回復 2019-05-30
?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

若要返回除None以外的值,需要使用RETURE語句。

在您的示例中,if塊只在執行一個分支時執行返回。要么將返回移到if/etc塊之外,要么在這兩個選項中都有返回。


查看完整回答
反對 回復 2019-05-30
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

def get_input():
    my_var = input('Enter "a" or "b": ')

    if my_var != "a" and my_var != "b":
        print('You didn\'t type "a" or "b". Try again.')
        return get_input()
    else:
        return my_varprint('got input:', get_input())


查看完整回答
反對 回復 2019-05-30
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

我覺得你應該用同時循環.

if my_var != "a" and my_var != "b":
    print('You didn\'t type "a" or "b". Try again.')
    get_input()

考慮到您鍵入的內容與“a”和“b”不同,當然,它會調用get_input但是它跳過了下一部分。即:

else:
    return my_var

將直接進入:

print('got input:', get_input())

因此,如果您將while循環用作:

while my_var!="a" and my_var!="b":
    print('You didn\'t type "a" or "b". Try again.')
    return get_input()

這樣我覺得你能處理好。


查看完整回答
反對 回復 2019-05-30
  • 4 回答
  • 0 關注
  • 970 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號