Greg
Greg

Reputation: 257

Returning variables to use in other functions in python

I am running into an issue with returning the month and day variables to use in other functions.

def date():
    date = raw_input("Date (ex. Jun 19): ")
    date = date.split(' ')
    month = date[0]
    month = month[:3].title()
    day = date[1]
    return (month, day)

def clone(month,day):
    print month day

Here is the output for the script:

Date (ex. Jun 19): june 19
Traceback (most recent call last):
  File "./manualVirt.py", line 26, in <module>
    main()
  File "./manualVirt.py", line 12, in main
    clone(agent,month,day)
NameError: global name 'month' is not defined

Upvotes: 0

Views: 124

Answers (4)

oleg
oleg

Reputation: 4182

Is it possible that You want to pass result of one function into another ?

month, day = date()
clone(month, day)

or You can unpack function result during passing it into second one

result = date()
clone(*result)

or even

clone(*date())

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47172

Since you're returning a tuple from date() I will be assuming that this would be the thing you want to do

month_day = date()
clone(month_day[0], month_day[1])

And also the following line in clone()

print month day

should be

print month, day

Upvotes: 1

anana
anana

Reputation: 1501

I think the problem comes from here: print month day.

You need to separate the arguments by commas if you want to print multiple things:

print month, day

Upvotes: 0

TerryA
TerryA

Reputation: 59974

You're probably wondering how to use a variable in the global space when it is declared in a local space. use global:

def myfunc():
    global a
    a = 5

print a
# NameError: name 'a' is not defined
myfunc()
print a
# 5

Upvotes: 0

Related Questions