简体   繁体   中英

Is it possible to call a function that needs a parameter, without it? On python

I'm learning to code on Python 3.x using Exercism. I have to code a conditional (on a secondary file) to return a string depending on a word sent from a main function:

User function:

def two_fer(name):
    if name:
        string = "One for " + name + ", one for me."
    else:
        string = "One for you, one for me."
    return string

Main function:

class TwoFerTest(unittest.TestCase):
    def test_no_name_given(self):
        self.assertEqual(two_fer(), 'One for you, one for me.')

    def test_a_name_given(self):
        self.assertEqual(two_fer("Alice"), "One for Alice, one for me.")

    def test_another_name_given(self):
        self.assertEqual(two_fer("Bob"), "One for Bob, one for me.")

The problem is that , for the first condition in the main function, it calls two_fer() with no conditional, which results on a fail.

Main function is supposed to not be modified, is it any way to solve the problem only by the user function?

Thanks in advance.

You can change:

def two_fer(name):

to:

def two_fer(name=None):

which will make name None by default

If you give name a default value of "you" , you can call the function without an explicit argument and get rid of the if statement altogether.

def two_fer(name="you"):
    return "One for " + name + ", one for me"

or better yet,

def two_fer(name="you"):
    return "One for {}, one for me".format(name)

You can use a default parameter ie None and check whether the function received any parameter or not.

User Function:

def two_fer(name = None):
    if name != None:
        string = "One for " + name + ", one for me."
    else:
        string = "One for you, one for me."
    return string

The above code will execute the else part if the method two_fer is called without any parameters.

Use a default parameter like following

def two_fer(name=None):
    if name:
        s = "One for " + name + ", one for me."
    else:
        s = "One for you, one for me."
return s

Also a tip, avoid assigning variable names as keywords for eg string in your case as it is a standard library and it is just a good practice to avoid it.

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