top of page

Mission 2 - If Statements, For/While Loops, Arrays, Dictionaries, and Tuples

Introduction:

Conditionals and loops are very necessary and powerful tools in programming. They allow us to execute a useful block of code a certain number of times. There are two types of loops in Python, for loops and while loops.

 

Let us first learn about conditionals.

Conditionals:

 

Within programs, we need the ability to check conditions and have the program change accordingly. The simplest form is an if statement. The structure of an if statement is as follows:

 

if (BOOLEAN EXPRESSION):

STATEMENTS

 

The colon is significant and required.

The line after the colon, must be indented. Python considers 4 spaces an indentation or if you press tab.

All lines indented to the same extent will execute whenever the boolean expression is true. A boolean expression can be a  simple expression of yes or no, 0 or 1.


 

If-Else

Often times, you may want one thing to happen when a condition is true and another thing to happen when a condition is false.

 

To help you understand, here is an analogy. Let’s say you have head phones on. If you hear a high pitched sound you are supposed to  raise your right hand, otherwise you raise your left hand. The pseudo code (simplified programming language) for that would look as follows:

 

if (high-pitched sound):

raise your right hand;

else:

raise your left hand;

 

Chained Conditionals

Sometimes there are more than two possibilities so we need more than two branches. As a result, we have what we call chained conditionals. If we continue based on the example from above, we could add a condition that states if you hear a flat tone, stand up. Then the pseudo code would look as follows:

 

if (high-pitched sound):

raise your right hand;

elif (flat noise):

stand up;

else:

raise your left hand;

 

Elif is an abbreviation for else if. You can have an unlimited number of elif statements follow your if statement but only one will be executed. Also, only one else statement is needed and it must be the last statement of the block. However, it is not required.

 

Each condition will be checked in order. If the condition being checked fails, the program will check the next one, and so on until it reaches the branch that is true. If there is more than one branch that is true, the first one that is true will execute.

 

Nested Conditionals

 

One conditional can be nested inside another. An example is as followed:

 

if (x == y):

STATEMENT A

else:

if (x > y) :

STATEMENT B

else:

STATEMENT C

 

The above example shows an outer conditional which has two branches. The else branch of the outer conditional contains another if-else statement.

 

Nested conditionals tend to get a bit confusing so they are not typically recommended.

 


 

For Loops:

For loops are used to iterate a set number of times. These loops should be used when you know exactly how many times that you want to execute the code in your loop.

 

For loops have the following syntax: “for all elements in a list, do this”

 

The loop below has the syntax stated above and will print out all of the elements in the list

 

computer_brands = ["Apple", "Asus", "Dell", "Samsung"]
for brands in computer_brands:
   print brands

This for loop is perfect to use to traverse this list because we know exactly how many times that we want to loop through the list and print out the elements. The code block reads for every element that we assign the variable brands, in the list computer_brands, print out the variable brands.

In addition to looping through a list, you can also loop through a range of numbers.

for i in range(1,10):
   print i

This can be used to iterate through a sequence of code a specific number of times

Keyword “Break”:

To break out of a loop, you can use the keyword “break”

for i in range(1,10):
   if i == 3:
break
   print i

Keyword “Continue”:

The continue statement can be used to tell the Python interpreter to skip the rest of the statements in the current loop block and continue to the next iteration of the loop

for i in range(1,10):
   if i == 3:
continue
   print i

While Loops:

While loops tell the Python to execute a code block as long as a certain condition is met. This is useful for executing a sequence of code until a certain condition changes.

While loops effectively say: “While this is true, do this”

computer_brands = ["Apple", "Asus", "Dell", "Samsung"]
i = 0
while i < len(computer_brands):
   print computer_brands(i)
   i = i + 1

This code block tells Python that as long as the value of the variable “i” is less than the length of the list (computer_brands) print out the variable name.

​

The primitive data types you learned in Level one are not the only data types you use when coding. Python has 4 collection data types that have varying properties so you can choose which one is the best to be used for your code.

 

The first collection is a list, which is ordered and changeable.

You can create a list by placing one or more items in square brackets separated by a comma.

 

For example, if I started to create a list of names of students in my class.  I would make each name a string and place it in the square brackets like this:

[“Amy”, “Bob”, “Carol”]

I could even assign this list to a variable like this:

names = [“Amy”, “Bob”, “Carol”]

 

Since a list is ordered, you can access items in the list by referring to the index number. An index number is the order of the items in the list. In computing, we start counting from 0, 1, 2, 3, instead of just 1,2,3, etc. So the first item in the list, has the index number 0.

To access the items in the list, you take the variable you’ve assigned the list to, then place the index of the item you want to access inside square brackets.

For example, if you want to get “Bob” out of our names list you would type:

names[1]

>>> “Bob”

 

Since the list is changeable, you can change the value of one of the items in the list. In our example, let’s say we misspelled one of the students name. Carol is actually supposed to be Caroline. We could access “Carol” and set that value of that item equal to “Caroline”. Like this:

Names[2] = “Caroline”

Now if we print names we should get:

print(names)

>>> “Amy” “ Bob” “Caroline”

Python also has built-in keywords and methods to be used with the collection data types. “In” is a keyword used to determine if an item exists in a list.

This is frequently used with conditionals, which we’ll go over later.

 

A built in python method is the “length” method. This method can tell you how many items are in a list

 

To find out how many names are in our list, we would type len(names).

len(names)

>>> 3

 

The append method is used to add new items to the end of the list. If we met a new classmate and wanted to add him to our list, we would type:

names.append(“Zach”)

print(names)

>>> [“Amy”, “Bob”, “Caroline”, “Zach”]

 

Or if we wanted to place an item at a specific location within our list we could use the insert method. This method is used similar to a function because it takes in two parameters. The first parameter is the index you want your added item to be placed at in the list. The second is the item you actually want to place in the list.

In our example, let’s add the name “Tyler”, but we want to keep the list in alphabetical order. Since the append method only adds to the end of the list, and Zach is currently the last name in the list, we will use the insert method to place the new name at a different location within the list.

names.insert(3, “Tyler”)

print(names)

>>> [“Amy”, “Bob”, “Caroline”, “Tyler”, “Zach”]

 

These are ways to add names to lists, but there are also ways to remove items with the remove and pop methods, or the “del” keyword.

The remove method removes a specific item from the list.

names.remove(“Bob”)

print(names)

>>> [“Amy”, “Caroline”, “Tyler”, “Zach”]

 

Pop can remove an item at a specified index or the last item if you don’t specify the index in the parentheses.

names.pop()

>>>  [“Amy”, “Caroline”, “Tyler”]

 

The del keyword will remove the value at a specific index.

Del names[0]

print (names)

>>>  [“Caroline”, “Tyler”]

 

The clear method will empty a list, so there are no longer items in it.

names.clear()

print(names)

>>> [ ]

 

You can also use the del keyword to delete the list completely. This will prevent you from ever being able to access the list because it no longer exists.

del names

 

Tuples

The next type of collection is a tuple. Tuples are also ordered, but they are unchangeable. Another word for this is immutable. This means that once you have a tuple, then you cannot change its order or what information it contains. You can create a tuple by using parentheses and can separate the items inside with a comma.

Let us create a tuple of cities.

Cities = (“Atlanta”, “Boston”, “Charlotte”, “Denver”, “El Paso”)

You can access items in a tuple the same way as in a list. To access “Boston” out of our tuple we would type:

Cities[1]

>>> “Boston”

 

You can also check the length of the tuple like the list.

Print (len(cities))

>>> 5

 

Remember: since a tuple is immutable, you cannot, add, change, or delete any of the items of the tuple.

 

The del keyword still applies because you can delete the whole tuple using this keyword like you can a list, just not individual items.

Del cities

 

The last collection type you will learn about in this lesson is a dictionary. Unlike the Merriam-Webster dictionary, Python dictionaries are unordered, changeable and indexed. A dictionary has a key and value set.

As an example let us create a dictionary of a book. That stores its title, author and genre.

Book = {

“Title”: “Catcher in the Rye”

“Author”: “Salinger”

“Genre”: “Fiction”

}


 

Similar to a regular dictionary, you can access the definition of a word by looking up the word. This would mean, the word is your key and the definition is your value. In Python dictionaries, you can access the items of a dictionary by referring to its key name placed inside square brackets.

X = book[“title”]

You can also use the get() method to access values

Y = book.get(“title)

print( x)

Print (y)

 

You can also change the value of a specific item by referring to its key name:

Book[author] = “J. D. Salinger”

You can also use the values() function to return the values of a dictionary.

Using the items() function will return a list of key-value pairs from the dictionary.

 

Similar to a list, using the in keyword will return a boolean of if a key is inside the dictionary.

You can also use the len method to return the number of items inside the dictionary.

 

To add items to the dictionary, you type the name of the dictionary and the key with the key placed inside square brackets. Then set this equal to the value want to be accessed by the key.

Book[“year”] = 1951

Print (book)

>>> {

“Title”: “Catcher in the Rye”

“Author”: “Salinger”

“Genre”: “Fiction”

“Year”: 1951

}

 

The pop method and del keyword will remove the item from the dictionary with the specified key name:

book.pop(“Genre”)

print(book)

>>>{

“Title”: “Catcher in the Rye”

“Author”: “Salinger”

“Year”: 1951

}

Del book[“Year”]

>>>{

“Title”: “Catcher in the Rye”

“Author”: “Salinger”

}

You can also, delete the dictionary completely with the del keyword.

Del book

 

This will mean the dictionary no longer exists and cannot be accessed.

​

​

​

This is the end of Level 2. 

bottom of page