Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping Raising Exceptions

kelsang sherab
kelsang sherab
749 Points

Code structure : def and variables

Why do we write the code like this:

def split_check(total, number_of_people)

and only after create/assign the variables : total, number_of_people

Why do we not first define the variables and then def split_check(total, number_of_people)

?

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

The function declaration (def) is defining those variables for the local scope of the function. This is where they are created and that's why you need to pass the positional arguments on function call which assigns (passes) the value

# define the function name and the function parameters (local scope variables)
def split_check(total, number_of_people):
    # do stuff with total and number_of_people

# call the function passing values
total_work = 357
people_count = 42
function_return_stuff = split_check(total_work, people_count)

Does that clear it up at all?

kelsang sherab
kelsang sherab
749 Points

Hi and thanks.

Yes the way you put it does seem to make sense.

I am new to programming and so I did not understand that while a function is defined its parameters are also defined. And from your answer I can see that once they are defined in the function def, afterwords they receive a treatment such as assigning value - values that are then used by the function.

So the way you explain it make it clear

Thanks