Introduction to Python Part 3

Conditional Statements, Functions, Sequences, and Iterations

Welcome to part three and my final blog post in this Introduction to Python series. If you are brand new to Python and have not read parts one and two of this series, please read those first.

This post will cover conditional statements, functions, sequences and iterations, specifically in Python 3. If you prefer to follow along with the source code, the headline for each section links to the repository on my Github. Following along there will give a better idea of what the Jupyter notebook interface looks like.

Conditional Statements:

Conditional statements are commands that compute different results depending on conditions set by the programmer. This section covers If, Else, and Else If statements in addition to the importance of boolean values to determining conditional results.

If Statements

“If statements” are commands that if proven to be true, the machine will output your designated result. If that statement is not true, then machine will provide no result. Let’s look at an example:

if 5 == 10/2:
    print("Yay")
Output: Yay

You will notice that the first line of the command is “if condition:” (what your condition is), followed by the actual conditional code (what you want the machine to do if that condition is true) on an indented line below – this keeps the command in its own block.

In this case, the condition was if “5 equals 10 divided 2,” which is true. Therefore, the machine executed the conditional code which was to print “Yay.” When the condition is not true, the machine will not provide any output. Let’s look at an example:

if 5 == 12/2:
    print("Yay")

Else Statements

The next statement we will look at is the “Else statement.” The “Else Statement” is used as an alternative to the “If Statement”, if the “If Statement” evaluates to “False.” Meaning that if the “If Statement” is false, the “Else Statement” tells the machine what to do next. Let’s look at an example:

x = 7 

if x > 5:
   print("x is greater than 5")
else:
   print("x is less than 5")
Output: x is greater than 5

You’ll notice that while the “If Statement” will only compute a result if the statement is “True,” the “Else Statement” will always provide a result. Because we provide the machine with another option if that “If Statement” evaluates to false. Let’s look at the same example, but change the value of x to 3:

x = 3

if x > 5:
   print("x is greater than 5")
else:
   print("x is less than 5")
Output: x is less than 5

Else If Statements

Elif, short for “Else If” is a statement that allows you to add multiple “Ifs” to your conditional code. Let’s say we wanted to add another statement to the example above to evaluate if x is negative; we can add this with Elif:

x = -3

if x > 5:
   print("x is greater than 5")
elif x < 0:
   print("x is negative")
else:
   print("x is less than 5")
Output: x is negative

Something important to note about Python is that it evaluates code from top to bottom, therefore the order you program your commands in is critical to getting the correct result. In the example above, the statement to evaluate if “x is less than zero” is before the else statement, because otherwise it would give the result that “x is less than 5.” This is not wrong as -3 is less than 5, but in this case we were looking for the result that “x is negative.” Let’s see the incorrect way to do this for learning purposes:

x = -3 

if x > 5:
   print("x is greater than 5")
elif x < 5:
   print("x less than 5")
elif x < 0:
   print("x is negative")
Output: x less than 5

Boolean Values and Conditional Statements

You have probably noticed by now, but the boolean values “True” and “False” are integral to conditional statements. When you write an “If Statement,” the machine attaches boolean values to it and computes results based on your conditional code commands. This is just something to think about when coding to help understand the computational logic of the programming language.

Functions:

A function is a block of reusable code that can be used to perform a specific action. To tell the computer that you are going to make a function, start the line with “def,” short for define, and start defining your function. Let’s look at an example to have a better idea of a function’s structure:

def hello():  
   print("Hello")

hello()
Output: Hello

The example above starts with “def” to define the function, followed by the function name “hello,” a set of parenthesis, and a colon. The next line is the function body, or where you define what the function will do. In the case, the function “hello” prints “Hello,” which we can see when we called the function.

The above example was a simple function that only returns one output. What if you want to create a more complex function that accepts different inputs to compute different outputs? For example, you want to create a function that takes in a value, multiplies it by 10, and the outputs the result. This is possible by adding “parameters” when defining the function. Let’s see this in the example below:

def multiply_by_five(x):
   return x * 5

multiply_by_five(2) 
Output: 10

As the example above shows, adding a parameter, x, to the function definition allows you to use the function with different inputs, instead of having to create a new function every time you want to perform the same task with different inputs. You will notice that when referring to the input in the definition, it is referred to as a “parameter,” but when calling the function on an input, it is referred to as an “argument.” It is important to remember this.

You also probably noticed that in the first example, we used the print() function at the end, but used “return” in the function example above. This is because print() simply displays information, while “return” outputs the value based on what the function is supposed to give back and ends the function. Therefore, “return” can only be used in a function once, at the end.

You can also create functions with multiple parameters. This involves identifying the appropriate number of parameters when defining the function, and adding the same number of arguments when calling the function:

def subtract(x,y):
   result = x - y 
   return result

subtract(5,2)
Output: 3

In the example above, the function was defined a bit differently. Instead of having “return x – y” on the second line, I assigned the subtraction to the variable “result” and then returned the result. There is no pro or con to defining a function this way, but it is an alternative.

Functions are neat because of the amount of things you can do with them. You can call a previously defined function in a new one:

def add(x,y):
   return x + y

def average(x,y):
   return add(x,y) / 2

add(6,3), average(6,3)
Output: (9, 4.5)

The example above shows how the add() function was defined, and then uses it in the average() function. Just make sure that the number of parameters match in both functions, or else it won’t work.

Another thing that functions can do is contain conditional statements:

def above_fifty(x):
   if x > 50:
        print("Yes")
   else:
        print("No")

above_fifty(25)
Output: No
above_fifty(60)
Output: Yes

If you are now starting out with Python, there are some built-in functions available to get you started.

These include: type() to determine type of an object, int() to convert number or string to an integer, float() to convert a number or string to a float, and str() to convert a value to a string. There is also min() and max() which finds the min and max of a list of valies, abs() to find the absolute value, sum() to sum values, round() to round a value, pow(x,y) to find the power, and len() to find the length of the input.

Sequences:

A sequence in Python is a set of values bounded together in a container. This can include lists, tuples and dictionaries.

Lists:

A list is a type of sequence of data points like integers, floats etc. Understanding how lists work is an important factor to organizing data.

To make a list, create a new variable assigned to your list of data points. You can indicate your list by putting the data points in brackets([]), with the elements separated by commas. Let’s take a look at the list of names below to understand this better:

Names = ["Natalie", "John", "Sami", "Jameel", "Clara"]
Names
Output: ['Natalie', 'John', 'Sami', 'Jameel', 'Clara']

When working with lists, you can select one element from the list using indexing. If you remember from Introduction to Python Part 2, in order to index you have to call the name of the variable followed by the index of the element in brackets where the count starts from 0. In this case, we would use the name of the list. Let’s extract the name “Sami” from list of names:

Names[2]
Output: 'Sami'

A neat trick to remember when indexing, is that you can also index or select elements by counting from the end of a list. To do this, you would just use the negative number, however, since we start from end, we start counting with “-1” not “0”. So, if we wanted to select “Sami” in this way, it would look like this:

Names[-3]
Output: 'Sami'

Let’s say we needed to update one of the names in list, specifically change “Jameel” to “Chris”. We can do this by assigning the index for “Jameel” to “Chris”:

Names[3] = "Chris"
Name
Output: ['Natalie', 'John', 'Sami', 'Chris', 'Clara']

What if we needed to remove a name from this list? We can do this with the “del” keyword followed by the index of the name. Let’s remove “John” from the list:

del Names[1]
Names
Output: ['Natalie', 'Sami', 'Chris', 'Clara']

It’s important to note, that since we removed an element from the list, and the list is shorter, the index for all of the names after “John” has no changed. For example, while “Sami” used to be 2, it is now 1:

Names[1]
Output:'Sami'

What if we want to add a brand new name to the list? We can do this with the append method. To append an item to a list, call the name of the list follow by “.append(new_element)”. Let’s add the name “Greg” to the list:

Names.append("Greg")
Names
Output: ['Natalie', 'Sami', 'Chris', 'Clara', 'Greg']

It is also possible to add new elements to a list with the extend method, which involves adding “.extend()” to the end of the list name. Let’s try adding multiple names this time, which involves using brackets and listing the names:

Names.extend(["Alana", "Timothy"])
Names
Output: ['Natalie', 'Sami', 'Chris', 'Clara', 'Greg', 'Alana', 'Timothy']

If you ever want to know how many elements you have in a list, you can use the len() function:

len(Names)
Output: 7

Slicing is helpful for working with a small section of a large list of data. Let’s say we wanted a smaller list of names from our whole list above. Specifically, we want the list of “Clara” and “Greg”. We can do this with indexing:

Names[3:5] 
Output: ['Clara', 'Greg']

You’ll notice that since we are selecting multiple elements, we have to [index_of_first_element : index_after_last_element]. If you want just the first two elements, you can leave the first index blank, followed by 2:

Names[ :2]
Output: ['Natalie', 'Sami']

And to get the last two elements, you would do the index of the first elements, colon, bracket:

Names[5: ]
Output: ['Alana', 'Timothy']

Let’s say you were working with a really huge list of data, and you couldn’t possibly count the elements by hand to find the index of a specific data point (or even find that data point). For a case like this, you could used the index method. Let’s use the index method to find the index of “Alana” in the Names list:

Names.index("Alana") 
Output: 5

It’s also possible to make a list of lists. Let’s make a new list called “New_Names” and add it to a larger list called “All_Names”:

New_Names = ["Ellis", "Lola"]
New_Names
Output: ['Ellis', 'Lola']
All_Names = [Names, New_Names]
All_Names
Output: [['Natalie', 'Sami', 'Chris', 'Clara', 'Greg', 'Alana', 'Timothy'],
['Ellis', 'Lola']]

If you want to order your list alphabetically, you can do this with the sort method:

Names.sort()
Names
Output: ['Alana', 'Chris', 'Clara', 'Greg', 'Natalie', 'Sami', 'Timothy']

Or you can sort them in the reverse order with setting “reverse=True” in the parenthesis (Note: the sort method can be used on lists of number as well):

Names.sort(reverse=True)
Names
Output: ['Timothy', 'Sami', 'Natalie', 'Greg', 'Clara', 'Chris', 'Alana']

Tubles:

Tubles are another kind of sequence that cannot be changed. This difference between a list and a tuple is that in a tuple, the list’s elements are placed within parenthesis and not brackets:

x = (1,2,3)
x
Output: (1, 2, 3)

Tuples are the automatic sequence type in Python, so even if you didn’t use parenthesis, Python would create a tuple:

y = 4,5,6
y
Output: (4, 5, 6)

Similar to lists, you can use indexing to select one element. Let’s select “2” from the list x:

x[1]
Output: 2

And you can create lists that are made up of multiples tuples. Let’s add tuples x and y to one list:

List = [x,y]
List
Output: [(1, 2, 3), (4, 5, 6)]

Tuples are also useful for assigning comma-seperated values to variables. Let’s assign values to both “age” and “years_of_work”:

(age, years_of_work) = "33,11".split(',')
print(age)
print(years_of_work)
Output:
33
11

Dictionaries:

Dictionaries are another way of storing data. Our knowledge of lists and tuples will make understanding dictionaries easier. In a dictionary, a value is assigned to a key for what is called a key-value pair like this – ‘key’:”value”. To indicate that you are making a dictionary, you need a use curly brackets ({}). Let’s take a look at simple dictionary below:

dictionary = {'k1':"apple", 'k2':"banana", 'k3':"orange"}
dictionary
Output: {'k1': 'apple', 'k2': 'banana', 'k3': 'orange'}

Unlike lists and tuples, in a dictionary, an item can be accessed by its key instead of its index:

dictionary['k1']
Output: 'apple'

Similar to lists, you can add news keys to a dictionary by calling the dictionary_name[new_key_name] = new_value_name. Let’s add another key to this dictionary:

dictionary['k4'] = "mango"
dictionary
Output: {'k1': 'apple', 'k2': 'banana', 'k3': 'orange', 'k4': 'mango'}

You can also change current key value, by assigning a new value to that key. Let’s replace “banana” with “strawberry” in key 2:

dictionary['k2'] = "strawberry"
dictionary
Output: {'k1': 'apple', 'k2': 'strawberry', 'k3': 'orange', 'k4': 'mango'}

There is another way to fill in dictionary. Create a new variable assigned to empty curly brackets, and assign the keys and the values one by one below:

Vegetables = {}
Vegetables['k1'] = 'cauliflower'
Vegetables['k2'] = 'potato'
Vegetables['k3'] = 'carrot'

print(Vegetables)
Output: {'k1': 'cauliflower', 'k2': 'potato', 'k3': 'carrot'}

Iterations:

Iterations provide the ability to execute a set of code repeatedly and is fundamental to more advanced Python programming.

One way to do iteration is with a for loop. You can apply a for loop on a list of elements to execute some kind of computation on each element in that list. This is considered a loop because the computation is done on the first element, then the second one, and so forth. An easy way to think about this is: “For every number in list x, add 1”. Let’s demonstrate this to understand further:

numbers = [0,2,4,6,8,10]

for n in numbers:
   print(n + 1)
Output:
1
4
7
10
12
16
18

If you want to print out the results in a single line instead of separate ones, you can do this by adding a “, end ‘ ‘” after “n + 1” in the print function:

for n in numbers: 
   print(n + 1, end = " ")
Output: 1 3 5 7 9 11 

Another way to achieve what we did above is with the while loop, but the structure will be slightly different. Instead of providing the while loop with a list to compute on, you will give it a start value and instructions that will let it know when to stop. Otherwise it will be caught in an infinite loop and may cause your computer to crash.

x = 0

while x <= 20:
   print (x, end = " ")
   x = x + 2
Output: 0 2 4 6 8 10 12 14 16 18 20 

As you can see from the code above we set x equal to zero, and told the machine that until the value of x hits 20, keep printing the value of x. To ensure that there would be no infinite loop, we then told the machine to add two to x on each loop, so that it can hit 20 and stop executing the while loop.

A neat Python trick to know for when working lists and loops is that you can generate lists with the range() function, which is a lot better than making lists manually. The range() function generates your list based on a start value, a stop value (1 value above the value you want to be last in the list,) and a step value (jump from one value to the next.) Let’s create a list with the range() function:

list(range(0,21,2))
Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Let’s try using the range() function in a for loop:

for n in range(10,100,5):
   print(2*n, end = " ")
Output: 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 

Last, but not least, we need to take a look at how to iterate over dictionaries. Let’s say you went grocery shopping on several occasions, picked up the same items and wanted to know the total you spent on them. Let’s first create a dictionary for the price of each item and one for the quantity:

prices = {"bananas": 1, "bread": 3, "milk": 2}
quantity = {"bananas": 4, "bread": 2, "milk": 1}

Now, let’s create a money spent variable set equal to zero, and create a for loop so that when we multiply each element in both dictionaries to get the total price for each item, we can add that value to money spent:

money_spent = 0

for i in prices:
   money_spent = money_spent + (prices[i]* quantity[i])

print(money_spent)
Output: 12

The for loop above basically says that for every element in prices, add money spent (which starts at 0) to the price of the item times the quanitity of the item. When we print money spent, we got the total.

While this may seem complicated at first, it is actually quite intuitive. You’ll find that a lot of programming just requires thinking about what the end result needs to be, and what steps are required to achieve that result.

Thank you for following along in this Introduction to Python series, I hope this has been helpful to getting you started on your Python journey!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s