为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的 Python 函数没有返回任何值?

为什么我的 Python 函数没有返回任何值?

料青山看我应如是 2023-09-12 17:35:32
我正在尝试使用“python”构建一个非 GUI 应用程序,但由于某种原因,我的“main_menu()”函数没有返回我需要的变量import pandas as pd#list for containing telephone numbertelephone = []#list containing contact namecontact_name=[]def main_menu():    intro = """ ----------------------WElCOME to MyPhone-----------------------    To select the task please type the number corrosponding to it    1)Add New Number    2)Remove Contact    3)Access old contact    ----> """    main = int(input(intro))    return mainmain_menu()def clean():    print("--------------------------------------------------------------------------------------")if main ==1:    def add_number():        clean()        try:            print("How many number(s) you want to add. Remeber if you don't want to add any number just click enter",end="")            number = int(input("----->"))            for i in number:                c_n = int(input("Name -->"))                t_n = int(input("Number-->"))                contact_name.append(c_n)                telephone.append(t_n)            else:                print("Contacts are Saved!👍")        except SyntaxError:            main_menu()
查看完整描述

5 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

正如前面的答案所指出的,您没有将函数的返回值保存main_menu()在任何地方。但是您的代码中还存在一些其他错误,因此让我们首先解决这些错误。


您需要先定义函数,然后才能使用它。您似乎试图add_number同时调用该函数并定义它。首先定义你的函数,然后像这样调用它:

# Define the add_number() function

def add_number():

    clean()

    ...


if main == 1:

    # call the add_number() function

    add_number()

    

您正在尝试迭代一个数字,这将引发错误。您可以尝试使用range该函数来代替。

number = int(input("----->"))

for i in range(number): # using range function

   ...

您正在尝试将名称转换为 int,但我假设您可能希望它是一个字符串。

# this will throw an ValueError if you type a name like "John"

c_n = int(input("Name-->")) 


# This will not throw an error because you are not converting a string into an int

c_n = input("Name-->")

您的 try 块正在捕获SyntaxErrors,但您可能想要捕获ValueErrors。语法错误是代码语法中的错误,例如忘记了 a:或其他内容。而值错误是当某些日期的值错误时产生的错误,例如当您尝试将字符串转换为 int 时。

# replace SyntaxError with ValueError

except ValueError:

    print("Oops something went wrong!")

最后,如果您想在输入联系号码后返回菜单,则需要某种循环。

while(True):

    # here we are saving the return value main_menu() function

    choice = main_menu()

    if choice == 1:

        add_number()


    # add other options here


    else:

      print("Sorry that option is not available")

此循环将显示 main_menu 并询问用户一个选项。然后,如果用户选择 1,它将运行该add_number()函数。一旦该功能完成,循环将重新开始并显示菜单。


总而言之,看起来像这样:


import pandas as pd

#list for containing telephone number

telephone = []

#list containing contact name

contact_name = []


def main_menu():

    intro = """ ----------------------WElCOME to MyPhone-----------------------

    To select the task please type the number corrosponding to it

    1)Add New Number

    2)Remove Contact

    3)Access old contact

    ----> """

    main = int(input(intro))

    return main


def clean():

    print("--------------------------------------------------------------------------------------")


def add_number():

    clean()

    try:

        print("How many number(s) you want to add. Remember if you don't want to add any number just click enter",end="")

        number = int(input("----->"))

        for i in range(number):

            c_n = input("Name-->")

            t_n = int(input("Number-->"))

            contact_name.append(c_n)

            telephone.append(t_n)

        else:

            print("Contacts are Saved!👍")

    except ValueError:

        print("Oops something went wrong!")


while(True):

    choice = main_menu()

    if choice == 1:

        add_number()

    # add other options here


    # catch any other options input

    else:

      print("Sorry that option is not available")


查看完整回答
反对 回复 2023-09-12
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

变量main仅在函数内有效main_menu。您需要将 的结果分配main_menu()给某些东西才能使用它。

main = main_menu()
if main == 1:
    ...


查看完整回答
反对 回复 2023-09-12
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

当您调用该函数时,您需要将结果放入变量中(或以其他方式使用它)。

例如:

selection = main_menu()

函数内部定义的变量在函数结束后消失;该return语句仅返回值,而不是整个变量。


查看完整回答
反对 回复 2023-09-12
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

当您调用该函数时,它会返回 main,但是,必须将其分配给某个对象才能使用它执行某些操作。仅调用该函数不会创建变量 main。这是因为函数的范围。

main = main_menu()


查看完整回答
反对 回复 2023-09-12
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

你的代码中有很多错误。def = 只声明函数但不调用它。

首先,如前所述,您在调用 main_menu() 时需要执行以下操作:

main = main_menu()

其次,在 if 中您应该调用 adD_number 函数:

if main ==1:
    add_number()

但请确保在调用之前声明 add_number() (使用 def)。

祝你好运!


查看完整回答
反对 回复 2023-09-12
  • 5 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信