简体   繁体   中英

Calling a function inside a function

this is a simple thing and I have no idea why this doesn't work as I've done this many times before in other languages, maybe I'm missing something. Anyway I have a function that does something and I try to call that function when I call a different function.

Context : puzzle is literally a puzzle made by rows and columns of strings and word is the word we're looking for in the puzzle

First function

def lr_occurrences(puzzle, word):    
    return puzzle.count(word)

Second function

def do_tasks(puzzle, name):    
    print('Number of times', name, 'occurs left-to-right: ', end='')       
    lr_occurrences(puzzle, name)

Yet when I call

do_tasks(PUZZLE1,'whatever') 

in the shell, the only thing that pops up is the "Number of times..." thing, however if I call

lr_occurences(PUZZLE1,'whatever')

it works perfectly fine returning the value.

Any ideas?

You are calling lr_occurrences(puzzle, name) and then discarding the result. Either print it like you do earlier in that function, or return it.

def do_tasks(puzzle, name):    
    print('Number of times', name, 'occurs left-to-right: ', end='')       
    print(lr_occurrences(puzzle, name))

Or:

def do_tasks(puzzle, name):    
    print('Number of times', name, 'occurs left-to-right: ', end='')       
    return lr_occurrences(puzzle, name)

If you return it, you will have to print the call to do_tasks , eg print(do_tasks(PUZZLE1,'whatever')) , for it to show up.

You never do anything with the return value. Either return it or print it.

Your do_tasks function should look like this:

def do_tasks(puzzle, name):    
    print('Number of times', name, 'occurs left-to-right: ', end='')       
    return lr_occurrences(puzzle, name)

Note the added return so that the value returned by lr_occurrences to do_tasks is then returned by do_tasks to its caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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