首页 > 解决方案 > 为什么我的代码打印不同,然后在函数中返回?

问题描述

代码:

Encode_Decode = input("Would you like to Encode, or Decode your text?")


def encode_decode_retry():
    an = input('Sorry, I didn\'t understand. Would you like to Encode, or Decode your text?')
    if an != "Encode" and an != "Decode":
        an = ""
        encode_decode_retry()
    else:
        print(an)
        return an


if Encode_Decode != "Encode" and Encode_Decode != "Decode":
    x = (encode_decode_retry())
    print(x)

它打印“解码”或“编码”,但是当我返回它时,它返回“无”。我的版本是3.7

标签: pythonpython-3.x

解决方案


您在 if 子句中缺少 return 语句。只需在调用函数之前添加 return

def encode_decode_retry():
    an = input('Sorry, I didn\'t understand. Would you like to Encode, or Decode your text?')
    if an != "Encode" and an != "Decode":
        an = ""
        return encode_decode_retry()
    else:
        print(an)
        return an


推荐阅读