We can work with Python as a procedural programming language. This means that we can give (sequential) commands as well as organize behaviors into repeatable procedures or functions. We can think of a function as a pattern of behavior that we can execute when desired. When we want the behavior to be executed, we say we are invoking or calling a function.
We're used to this in every day life, often repeating actions and customizing them in the moment. For example, I could ask you to perform a find behavior, and you would need to know what it is you are trying to find. I might say:
find an umbrella
or
find a flashlight
Notice that the find behavior would be executed twice here, but with different objects. These objects (umbrella, flashlight) customize the behavior of the function when it’s called, even though the pattern is the same. For me, my find procedure essentially means a walk through my house visually scanning for the target item. So, the pattern of behavior is the same, even though the item itself may change. In code, any additional data that is required for a function is called a parameter. The find function takes in one parameter, which is the item to locate.
Some functions may not require any additional data. For example, the behaviors sleep and wake up are ones we can execute, but do not depend on additional information.
Finally, some functions could require more than one parameter. When you order a drink, you provide several pieces of information:
order a bubble tea with taro flavor and red beans
When we invoke a function, we must pass any required parameters. This will take some getting used to, so for now it’s mostly to start getting familiar with the terminology and concepts.
Python syntax
The syntax for invoking a function in python is to write the function name, followed by parentheses containing the parameter list:
*functionName* ( *parameter1*, *parameter2*, ... )
If the real-life examples above were “translated” into Python, it would be:
find( "umbrella" )
find( "flashlight" )
sleep()
wakeUp()
order( "bubble tea", "taro", "red beans" )
Note: I tend to put spaces after/before the parentheses for readability; they are not required.
The first built-in function we’ll use in Python is the print function, which helps us understand what our code is doing. Note invoking print will (generally) not change the outcome of your program; it is typically used to help interact with a user or to debug while we’re developing our code.
Here are some examples:
print( "hello" ) // invoke the print function to print out hello
ouputs:
hello
Notice that we tell Python what to print by passing this information as a parameter within the parentheses. Python will accept both string and int types as a parameter.
print( 4 )
outputs:
4