Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function parameter as a global variable

I have written the following function, it takes in a variable input_name. The user then inputs some value which is assigned to input_name. I want to know the best way to make input_name accessible outside of the function. 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
like image 489
Tom Kadwill Avatar asked Nov 28 '22 09:11

Tom Kadwill


2 Answers

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.
like image 151
Ned Batchelder Avatar answered Dec 06 '22 02:12

Ned Batchelder


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:

def input(input_name, prompt):
    globals()[input_name] = value
like image 28
elijaheac Avatar answered Dec 06 '22 04:12

elijaheac