简体   繁体   English

Python函数参数作为全局变量

[英]Python function parameter as a global variable

I have written the following function, it takes in a variable input_name . 我编写了以下函数,它接受一个变量input_name The user then inputs some value which is assigned to input_name . 然后,用户输入一些分配给input_name值。 I want to know the best way to make input_name accessible outside of the function. 我想知道在函数外部访问input_name的最佳方法。 I know that defining a variable as global, inside a function, means that is can be used outside of the function. 我知道在函数内部将变量定义为全局变量意味着可以在函数外部使用它。 However, in this case the variable as actually a parameter of the function so I am not sure how to define it as a global variable. 但是,在这种情况下,变量实际上是函数的一个参数,所以我不确定如何将它定义为全局变量。 I appreciate any help with this, please find the code in question below: 感谢您对此有任何帮助,请在下面找到相关代码:

def input(input_name, prompt):
    while True:
        data = raw_input(prompt)
        if data:
            try:
                input_name = int(data)
            except ValueError:
                print 'Invalid input...'
            else:
                if input_name >= 0 and input_name < 100:
                    print 'Congratulations'
                    break
                input_name = 'Please try again: '
        else:
            print 'Goodbye!'
            break

month = 0
day = 0
year = 0
century = 0

input(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ")
input(day, "Please enter the day (from 1-31): ")
input(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ")
input(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ")

A = month
B = day
C = year
D = century

The simplest thing would be to return the value, and assign it outside the function: 最简单的方法是返回值,并将其分配给函数外部:

def my_input(prompt):
    #.. blah blah..
    return the_value

month = my_input("Please enter the month")
# etc.

Other people are saying something like this: 其他人都说这样的话:

def input(prompt):
    return value

value = input(param1,param2, ...)

And that's what you really want to be doing, but just so you know, you can use globals() for changing global variables: 这就是你真正想要做的事情,但是你知道,你可以使用globals()来改变全局变量:

def input(input_name, prompt):
    globals()[input_name] = value

What you want to do is probably a bad practice. 你想做什么可能是一个不好的做法。 Just return input_name from the input function. 只需从input函数返回input_name

def input(param1,param2):
   return value

value = input(param1,param2, ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM