Intro to Python Programming (Part 4) - Call Functions and If-Statements
2021-05-26 | By Maker.io Staff
So far in this series, you’ve learned what Python is and how you can create simple variables and collections of values in Python. This article discusses how to call functions and how to use if-statements and various loops when writing programs in Python.
Calling Functions
So far, we’ve used the print()-function in several examples throughout this series. What you’ve seen there is a call to a predefined method that comes with Python:
print(“Hello World!”)
Note that I call the print function with a single parameter (the string “Hello World!”). Other functions might require you to pass different parameters to them for them to work. Remember the pop() function calls from part three of this series:
fruits.pop() # Deletes the last element of fruits fruits.pop(0) # Deletes the first element of fruits
As you can see, it’s possible to call the pop() function without any parameters or with an index that tells the function which element to remove from a list. Having the same function accept different parameter lists is often also referred to as overloading -the function pop() has two overloaded variants.
These were two examples of function calls. In general, you call a function by writing its name followed by parentheses, which may or may not contain parameters. The exact order and number of parameters depend on the method you want to call. Note that Python supports the use of optional parameters, so it might not be necessary to supply all of them. However, you must provide all mandatory parameters in the correct order. Optional arguments are always at the end of the parameter list. We recommend you supply all the parameters (even the optional ones) to prevent unexpected side effects. You can find a list of all built-in functions in Python here.
Some functions return a value when they finish. It's up to you whether you store that value in a variable, use it as the parameter in another function call, or completely ignore it:
# Store the returned value of len(fruits) in a new variable l = len(fruits) # Use the return value as a parameter for the str() function call print("The list contains " + str(len(fruits)) + " entries!") # Ignore the returned value len(fruits)
In most cases, it makes little sense to ignore the return value of a function. Instead, it’s a good idea to inspect it, as some methods might return an error code if an operation fails.
Controlling the Flow of Your Python Programs
So far, you have seen how to create variables, make comparisons, use binary operators, create lists, and call functions. These things are essential for writing programs, but you usually can't write a complete program with these tools alone.
Usually, you expect a program to do more than store values and make comparisons. It also has to react to the results of those comparisons. You can make your Python script do different things depending on the outcome of a comparison operation by using the if-statement:
fruits = ["Apple", "Banana"] if fruits[0] == "Apple": print("The first entry contains the word 'Apple'!")
The code in the example above inspects the first element in the list called fruits. If the first element is equal to the string "Apple", the code calls the print function and tells the user that the first element of the list was, indeed, the word “Apple”.
So, to write an if statement, start with the word "if", followed by a condition and then by a colon. Note that you can chain conditions by using the logical operators, as demonstrated earlier in this series. Also, note how the text below the if-statement is indented by one-tab stop. The indentation lets the Python interpreter know it should only execute every line that follows the if-statement if the supplied statement evaluates to true:
fruits = ["Apple", "Banana", "Kiwi", "Papaya", "Watermelon"] if fruits[0] == "Apple" and fruits[1] == "Banana": # These two lines will only be executed if the if-statement # evaluates to True print("The first entry contains the word 'Apple'!") print("The second entry contains the word 'Banana'!") # This line will be executed regardless of how the if-statement evaluates print("The list contains " + str(len(fruits)) + " entries!")
Once you stop the indentation, you also end the if-statement, and all subsequent lines of code are unaffected by that if-statement. You can use an else-statement right after an if-statement to supply an alternative path if the condition evaluates to false:
fruits = ["Apple", "Banana", "Kiwi", "Papaya", "Watermelon"] if fruits[0] == "Apple": print("The entries are in the right order!") else: print("Something went wrong...")
Besides that, there’s also the option to chain multiple if-else blocks together to create several alternative paths:
fruits = ["Apple", "Banana", "Kiwi", "Papaya", "Watermelon"] if fruits[0] == "Apple": print("The first entry is 'Apple'!") elif fruits[0] == "Banana": print("The first entry is 'Banana'!") elif fruits[1] == "Kiwi": print("The first entry is 'Kiwi'!") else: print("Something went wrong...")
Repeat Code Using Loops
Now let’s suppose you want to execute a certain code snippet multiple times. You could, of course, just duplicate it like this:
fruits = ["Apple", "Banana", "Kiwi", "Papaya", "Watermelon"] print(fruits[0]) print(fruits[1]) print(fruits[2]) print(fruits[3]) print(fruits[4])
This will have the desired effect, and print all the strings contained in the list:
However, there are several problems with this approach. The two most obvious ones are that you repeat code (which is, as a rule, not a good idea) and that your code is not flexible to changes. What if you change the list elements, or what if the list entirely depends on the user’s input? The current code doesn’t allow the list to have an arbitrary number of elements. It relies on the list always having five elements. You can, however, use loops to repeat code several times:
fruits = ["Apple", "Banana", "Kiwi", "Papaya", "Watermelon"] i = 0 while i < len(fruits): print(fruits[i]) i = i + 1
What you see in the code snippet above is a while loop. This simple loop repeats the indented lines of code as long as the condition holds. In this example, the condition is that the variable i is less than the number of elements in the list. The code within the loop prints the list element on position i (which takes all values from 0 to 4 in this case) and it then increments i by one.
Another type of loop is the for loop:
fruits = ["Apple", "Banana", "Kiwi", "Papaya", "Watermelon"] for i in range(0, len(fruits)): print(fruits[i])
As the example demonstrates, the for loop is perfect for working with lists, as it makes it very easy to iterate over all elements of a list. You can, however, use the two loops interchangeably almost all the time.
Because the for loop is ideal for iterating over all elements in a list, there’s a shorthand for defining a for loop that iterates overall values in a list:
for x in fruits: print(x)
In this case, x is a variable that holds the current element of the list. The loop automatically updates this variable with every iteration.
Within loops, you can use two keywords, which are break and continue. Continue will make the loop jump to the next iteration, skipping the rest of the current iteration, and break stops the loop and causes your program to break out of it. Furthermore, Python also allows you to use the else keyword in combination with loops:
for x in fruits: print(x) else: print(“Loop finished!”)
The code inside that else loop gets executed once the loop finishes.
Making Your Own Python Scripts
To call a function, you have to write the function name followed by parenthesis containing the parameters you want to pass to the method. You have to supply the correct number of parameters in the expected order for the method call to succeed. Python, however, also supports optional arguments. A program typically doesn't only consist of variables and function calls. It also needs to make decisions and repeatedly run some lines of code. That's where if-statements and loops come into play. If-statements allow you to run some lines of code if a condition evaluates to true.
You can combine if-statements with optional elif and else-blocks to create alternate paths. The while loop repeats the indented lines of code while the supplied condition holds, and the for loop is perfect for iterating over lists and manipulating each element of the list.
In the next article in this series, we’ll take a look at using custom functions -- a powerful additional tool that you can use to harness the potential of Python in your projects!
Recommended Reading
Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.
Visit TechForum