0

It seems like all the functions are executed then one() is being executed. How do i go to function one() without executing all the other functions?

sample.py

#!/usr/bin/python

def zero():
    print("This is func zero")
    return "Test"

def one():
    print("This is func one")
    return True

def two():
    print("This is func two")
    x = 7
    print("%d" % x)
    return False

def numbers_to_strings(argument): 
    switcher = { 
        0: zero(), 
        1: one(), 
        2: two(), 
    } 

    return switcher.get(argument, "nothing") 

# Driver program 
if __name__ == "__main__": 
    argument=1
    print(numbers_to_strings(argument))

Output

This is func zero
This is func one
This is func two
7
True   

Expected

This is func one
True   

Or is there an explanation why it works this way? Thanks in advance! New to Python btw

0

2 Answers 2

6

The parentheses call the function.

So only use parentheses on the function you want to call.

def numbers_to_strings(argument): 
    switcher = { 
        0: zero, 
        1: one, 
        2: two, 
    } 

    f = switcher.get(argument)
    if f:
        return f()
    return "nothing"
Sign up to request clarification or add additional context in comments.

1 Comment

Or: switcher.get(argument, lambda: "nothing"), after which you can simply return f(), since the default will be a function that when called with no arguments produces the expected "nothing".
0

Here's it!

#!/usr/bin/python

def zero():
    print("This is func zero")
    return "Test"

def one():
    print("This is func one")
    return True

def two():
    print("This is func two")
    x = 7
    print("%d" % x)
    return False

def numbers_to_strings(argument): 
    switcher = { 
        0: zero, 
        1: one, 
        2: two, 
    } 

    f = switcher.get(argument)
    if f:
        return f()
    return "nothing"

if __name__ == "__main__": 
    argument=1
    print(numbers_to_strings(argument))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.