2

I am trying to set up a function that records to 2 variables and a dictionary, the dictionar works but the two variables return the wrong things

mydict{}
fname = 0
lname = 0

def enterdetails(fname, lname):
    fname = input ("First Name: ");
    fnamedict = fname
    mydict['FirstName'] = fnamedict;

   lname = input ("Last Name: ");
   lnamedict = lname
   mydict['LastName'] = lnamedict;
   print(fname)
   print(lname)

   return mydict
   return (fname, lname)

fname, lname = enterdetails(fname, lname)
print(fname, lname)
print(mydict)

However the variables of fname and lname come out as FirstName and LastName respectively. How would I fix this?

3 Answers3

4

You have two return statements, but only the first is returned. Instead, return all three variables together as a tuple:

def enterdetails(fname, lname):
    ...
    return mydict, fname, lname

mydict, fname, lname = enterdetails(fname, lname)
print(fname, lname)
print(mydict)
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
1

The dictionary works because you have it set as a global variable. However, the function is actually returning the "dictionary" first, so your unpacking is all messed up.

Remove the return mydict or use return mydict, (fname, lname), so you will end up with:

mydict, (fname, lname) = enterdetails(fname, lname)

But as I mentioned above, mydict is a global variable, so it is unnecessary to return the value.

Maru
  • 11
  • 2
  • I had to read this twice to understand it, but that is a very good point about global variables that the other answers didn't address. – o11c Oct 08 '14 at 08:10
0

You can't put a return under a return like

return mydict
return (fname, lname) #this won't return any thing

One of the ways that you could do is:

  ....
  return [mydict, fname, lname]

data = enterdetails(fname, lname)
mydict = data[0]
fname = data[1]
lname = data[2]
Vizjerei
  • 1,000
  • 8
  • 15