从其他函数调用变量

时间:2013-06-25 21:53:22

标签: python function call

我一直在这里寻找一段时间,但没有任何效果。我试图从一个函数调用输入变量以用于另一个函数。在下面的代码中(特别是number1,number2,name1和name2)。

这是Python 3.3.2。如果这是一个非常基本的问题,我道歉。

import os import sys ##Folder making program. def main(): print("Follow the instructions. The output will be put in the root directory (C:/)") var = input("Press enter to continue") print("What do you want to do?") print("1. Create a folder with a series of numbered subfolders") print("2. Create a folder that contains subfolders with unique names") print("3. Exit the program.") input1 = input(": ") if input1 == '1': program1() elif input1 == '2': program2() elif input1 == '3': sys.exit def program1(): print("Input name of the main folder") name1 = input(": ") if name1 == "": print("The main folder needs a name.") program1() print("Input the name of sub folders") name2 = input(": ") series() def program2(): print("Input name of the main folder") name1 = str(input(": ")) if name1 == "": print("The main folder needs a name.") program2() print("Input the name of sub folders.") name2 = str(input(": ")) creation2() def series(): print("Put STARTING number of subdirectories:") ##code that will repeat this prompt if the user puts in a string. Accepts answer if input is an integer while True: try: number1 = int(input(": ")) break except ValueError: print ("invalid"); print("confirmed") print("Put ENDING number of subdirectories:") ##code that will repeat this prompt if the user puts in a string. Accepts answer if input is an integer while True: try: number2 = int(input(": ")) break except ValueError: print ("invalid"); total = number2 - number1 ##Makes sure the values work, restarts this section of the program program if values are 1 or less than 0 if total < 0: print('be reasonable') series() if total == 0: print('be reasonable') series() if total == 1: print("make the folder yourself") series() print("confirmed") while number1 <= number2: path = "c:\\" name3 = name2 + ' ' + str(number1) ##puts path to root directory ##makes main folder ##makes sub folders in main folder. Subfolders are named "Name2 1", "Name2 2", etc ##os.makedirs(path + name1) os.makedirs(path + name1 + '\\' + name3) number1 = number1 + 1 contains = str('has been created, it contains') containstwo = str('subdirectories that are named') print((name1, contains, total, containstwo, name2)) menu def again(): while True: print("Input the name of a new subfolder") newname = input(": ") os.makedirs(path + name1 + '\\' + newname) if newname == "": again() if newname == "1": main() print("To make another folder, input the name. To return to the menu, input 1 .") def creation2(): path = "c:\\" ##puts path to root directory ##makes main folder ##makes one subfolder in main folder, the subfolder has is name2. os.makedirs(path + name1 + '\\' + name2) contains = str('has been created, it contains') print((name1, contains, name2)) print("Make another named folder within the main folder? (y/n)") another = input(":") while another == "y": again() if restart == "n": menu() main()

2 个答案:

答案 0 :(得分:1)

你不调用变量,你调用函数。

您要做的是从您的函数中返回值。然后,您可以将这些值存储在变量中或将它们传递给另一个函数。

例如:

def get_numbers():
    x = int(input("Enter value of X: "))
    y = int(input("Enter value of Y: "))
    return x, y

def add_numbers(x, y):
    return x+y

x, y = get_numbers()
sum = add_numbers(x, y)
print("The total is:", sum)

因为我们只使用全局变量xy(函数外部的变量)来保存get_numbers()返回的值,直到它们传递给add_numbers() ,我们可以删除这些变量,并将get_numbers()返回的值直接传递给add_numbers()

sum = add_numbers(*get_numbers())

get_numbers()前面的星号告诉Python该函数返回多个值,并且我们希望将它们作为两个单独的参数传递给add_numbers()函数。

现在我们看到sum也是如此 - 它只用于保存数字直到我们打印它。所以我们可以将整个事情合并为一个陈述:

print("The total is:", add_numbers(*get_numbers()))

你已经熟悉了这一点 - 毕竟你的代码中有int(input(": "))input()重新调整字符串,然后传递给int()您编写的函数与Python内置的函数完全相同。

现在,像这样在彼此内部编写函数调用几乎不会引起混淆,因为它们是在最里面的调用get_numbers(),首先是add_numbers(),最后是print() - 执行的 - 与他们写作方式相反!因此,使用临时变量,以便按照实际执行的顺序编写代码是有意义的。

答案 1 :(得分:0)

我会遵循kindall的建议并选择重写;重写可能更具可读性和更短。但是,如果您想使用现有的一些现有代码,请考虑以下事项:

program1()为例。在program1()中,您可以定义name1变量和name2变量。这些变量仅存在于program1()的定义中。如果您希望使用其他函数(具体为series())来使用变量,则需要重新构造series()以接受参数。例如:

def program1():
    print("Input name of the main folder")
    name1 = input(": ")
    if name1 == "":
        print("The main folder needs a name.")
        program1()
    print("Input the name of sub folders")
    name2 = input(": ")
 -->series(name1, name2)

def series(name1, name2):
    ...

这样,您可以将一个函数中定义的变量传递给另一个函数。为所有方法执行此操作可能有助于缓解您遇到的一些问题。