为什么Python函数不返回任何值?

2024-06-08 00:44:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用“python”构建一个非GUI应用程序,但由于某种原因,“main_menu()”函数没有返回我需要的变量

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
main_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()

Tags: tonameaddnumberforinputmaindef
3条回答

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

例如:

selection = main_menu()

函数中定义的变量在函数完成后消失;return语句只返回值,而不是整个变量

变量main仅在main_menu函数中具有作用域。您需要将main_menu()的结果分配给能够使用它的对象

main = main_menu()

if main == 1:
    ...

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

  1. 您需要先定义函数,然后才能使用它。您似乎试图调用add_number函数并同时定义它。首先定义函数,然后像这样调用它:
# Define the add_number() function
def add_number():
    clean()
    ...

if main == 1:
    # call the add_number() function
    add_number()
    
  1. 您正在尝试迭代一个数字,这将抛出一个错误。您可以尝试使用range函数来代替
number = int(input("----->"))
for i in range(number): # using range function
   ...
  1. 您正在尝试将名称转换为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-->")
  1. 您的try块正在捕获SyntaxErrors,但您可能希望捕获ValueErrors。语法错误是代码语法中的一个错误,比如忘记了:之类的东西。而值错误是当某个日期的值错误时产生的错误,例如当您尝试将字符串转换为int时
# replace SyntaxError with ValueError
except ValueError:
    print("Oops something went wrong!")
  1. 最后,如果您想在输入联系人号码后返回菜单,则需要某种循环
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")

此循环将显示主菜单并要求用户提供选项。然后,如果用户选择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")

相关问题 更多 >

    热门问题