Nicholas Evans Nicholas Evans - 1 month ago 9
Python Question

Function Calling Python basic

I'm trying to enter values from the tuple

('a',1), ('b',2),('c',3)
into the function
dostuff
but i always get a return of
None
or
False
. i'm new to this to i'm sorry if this question is basic. I would appreciate any help.

I expect the result of this to be:

a1---8
b2---8
c3---8


Code:

def dostuff(stri,numb,char):
cal = stri+str(numb)+'---'+str(char)
return cal

def callit (tups,char):
for x in range(len(tups)):
dostuff(tups[x][0],tups[x][1],char)

print(callit([('a',1), ('b',2),('c',3)],8))

Answer

I think you're misunderstanding the return value of the functions: unless otherwise specified, all functions will return None at completion. Your code:

print(callit([('a',1), ('b',2),('c',3)],8))`

is telling the Python interpreter "print the return value of this function call." This isn't working because the callit function doesn't have a return value specified. You could either change the return in your dostuff function like so:

 def dostuff(stri,numb,char):
    cal = stri+str(numb)+'---'+str(char)
    print cal

def callit (tups,char):
    for x in range(len(tups)):
        dostuff(tups[x][0],tups[x][1],char)

callit([('a',1), ('b',2),('c',3)],8)

This changes the return on the third line into a print command, and removes the print command from the callit call. Another option would be:

 def dostuff(stri,numb,char):
    cal = stri+str(numb)+'---'+str(char)
    return cal

def callit (tups,char):
    for x in range(len(tups)):
        cal = dostuff(tups[x][0],tups[x][1],char)
        print(cal)


callit([('a',1), ('b',2),('c',3)],8)

This takes the return value from the dostuff function and stores it in a variable named cal, which could then be printed or written to a file on disk.