Introduction to Python – Chapter 9 – Dictionaries and Sets

In this video, we’ll talk about dictionaries and sets.

For strings, lists, and tuples, we have been using integers as the indices and position numbers in order to get their values.

Dictionaries are similar to lists except that instead of using integers as the indices, dictionaries can use any string or number or immutable type as the index.

Let’s create a dictionary to demonstrate how it works.

We will create a dictionary called states.

Instead of using number indices, we will use the state’s abbreviation as the index, and the state’s full name as the value.

An index in a dictionary is called a key.

The values in a dictionary are still called values.

As a result, we call the individual elements of a dictionary, key-value pairs.

First way to create a dictionary is by creating an empty dictionary.

After creating the empty dictionary, we can assign new keys to new values.

Here I created an empty dictionary, using a pair of curly braces.

Every key points to a specific value.

We can print this dictionary.

When we run the program, we see how a dictionary is formatted.

A dictionary is enclosed by a couple of curly braces.

Each element of a dictionary has the key followed by a colon followed by the key’s value.

Each element is separated by a comma like a list.

Every key has a value.

Another way to create a dictionary is to assign a variable to a dictionary with a few key-value pairs.

For example, let’s delete this snippet of code.

Now, we’ll write the same dictionary that we deleted except we’ll pre-populate the dictionary instead of assigning separate keys to values.

When we run the program, we get the same dictionary that we printed out with our first method of creating a dictionary.

All you have to remember is a pair of curly braces, and then, the keys are followed by a colon and a value.

Before Python 3.6, key-value pairs of dictionaries were not stored in order.

I’m using Python 3.6, but you might be using a different version of Python, which means that the key-value pairs might not be in order.

From Python 3.6 and onward, a dictionary maintains insertion order by default.

To access a value in a dictionary, you use a pair of brackets like you would with a list.

If I wanted to get the full state name for California, I would write:

When I run the program, I get “California” because “California” is the value for the “CA” key.

You can delete key-value pairs like how you would delete values of a list.

Let’s try to delete the “MA”: “Massachusetts” element.

When we run the program, the “MA”: “Massachusetts” element is deleted.

We can also get the length of a dictionary too.

When we run the program, we get the length of the states, which is now 2.

Just like lists, dictionaries are passed by reference.

A variable that is assigned a dictionary variable changes the actual dictionary.

Let’s first delete the del statement.

If I set b = states, changes to b will affect states.

When I run the program, I can see that the assignment of “CA” for b changed the states dictionary.

Dictionaries are passed and assigned by reference. Not by value.

We can use for loops with dictionaries.

If you use the for loop like you would with a list, i will be the keys of the dictionary.

When we run the program, we get the keys from states.

You can get the values separately. If you want just the values, you can use the .values() function on a dictionary.

When we run this program, we’ll get the values of states.

Most of the time though, we want both the keys and the values.

To get both the keys and values of a dictionary, we use the .items() function on a dictionary.

When we run the program, we get both the key and value from states.

You can see each state abbreviation followed by the full state name.

Most of the time, I need to grab both the key and value, so I normally format my dictionary for loops using the .items() function.

We can check if a dictionary has a particular key. Like in a list, we can check for membership in a dictionary.

For example, we can check if states has the “MA” key.

When we run the program, we see the print statement, “MA is in states dictionary.”, because “MA” is a key of the states dictionary.

You might be thinking what makes a dictionary so different from lists?

Is the only difference between a dictionary and a list the fact that a dictionary can have different types like strings for the indices?

Let’s review the main differences between a dictionary and a list.

First, we’ve talked how a dictionary can have different types for its keys.

On the other hand, a list is ordered with numeric indices, starting from 0.

Second, you may have noticed already that dictionary keys are unique.

We can reassign and delete existing key-value pairs like what we did for states, but a dictionary always forbids duplicate keys.

Dictionaries are good data structures for holding unique data.

In our example, we created a dictionary to hold the abbreviations of states because we know that every state has a unique abbreviation.

In contrast, a list can hold duplicate values.

Technically, a dictionary can also have duplicate values, but since a dictionary can only have unique keys, we use dictionaries whenever we have data with unique identifiers.

Third, checking for membership in a dictionary is much faster than checking for membership in a list.

Checking for membership in a dictionary takes about a constant, fast amount of time whereas checking for membership in a list takes time proportional to the list’s length.

I emphasize performance speed in these videos.

When talking about Computer Science in Chapter 1, I said that Computer Science is about figuring out:

“What can be computed? How can we compute it? and especially How fast can we compute it?”

Paying attention to performance speeds of every data structure you use is important to being an efficient problem solver in Computer Science.

Let’s talk about sets. A set is like a dictionary except it only contains keys.

A set is just a unique collection of values.

Let’s make a set of fruits.

You will notice that a set looks very much like a list except it uses curly braces like a dictionary.

You can add new values to a set with the set.add() function.

When we run the program, you will notice that adding new values in a set does not put them in order.

Sets are not about order. If you want to keep an ordered sequence, then use a list.

You can remove values from a set, but you can only remove that value from a set if it is already in the set.

If the value you want to remove is not in the set, then you will get an error.

Let’s check for membership in the set, and if “pears” is in the set, then we’ll use the .remove() function.

When we run the program, since “pears” is in the fruits set, we remove “pears”.

We can see that fruits no longer has “pears.””

You can use a for loop with a set.

When we run the program, we will get every fruit string in the fruits set.

Let’s review the aspects of sets.

Sets cannot have duplicate values, so sets are good data structures for holding unique data.

Accessing elements of a set is a pain since sets don’t support access by index.

Checking for membership in a set is as fast as dictionaries.

The big question is when should you use lists, dictionaries, and sets?

Ask yourself:

Do you just need an ordered sequence of items? Use a list.

Do you need to associate values with keys, so you can check for membership efficiently and find the values (by key) later on? Use a dictionary.

Do you just need to know whether or not you already have a particular value but without ordering (and you don’t need to store duplicates)? Use a set.

Most of the time, you’ll be focusing on lists for ordered sequence of items and dictionaries for unique key-value pairs of data because accessing values in a set is just not very flexible.

When you know that you have to search your data for membership or you don’t want any duplicate data, think about using dictionaries or sets.


Video Demonstration

Introduction to Python – Chapter 8 – Lists, Matrices, and Tuples

In the last video, we talked about lists.

There are a couple of more things that we need to talk about lists including matrices.

Let’s say that we had two lists:

With lists, a and b are the same thing. If I change b, then a is also changed.

Let’s test changing b.

When we run the program, we can see that even though a was a list with 1, 2, 3, 4, and 5, and we didn’t change a, a’s value at index 0 is now 0.

We assigned b at index 0 to 0.

What we find out is that changing b also changes a.

With lists, b = a is an assignment by reference.

Assignment by reference is a fancy way of saying that there’s an assignment pointing b to a.

b = a is not a copy of a. b and a are the same variable.

The variable b points to where a was created, so changes to b affect a.

Instead of doing this example with lists, if I were to use integers or strings, assigning b to a would be an assignment by value.

Assignment by value means that there is a copy of the variable, which makes b independent to a.

Remember that assigning b to a with lists is an assignment by reference. b and a are the same variable.

This aspect of lists affects how we use lists in functions.

Let’s make a function to delete the end of a list.

This function will delete the last value of a list.

When you use a list as an argument in a function, the list is passed by reference.

Passed by reference means that whatever we do to the variable will change the original.

Even though the parameter has a different variable name, the list_parameter and list_argument are in fact the same variable.

list_parameter is not a copy of list_argument. There is only 1 variable. They are the same variable.

Any change that happens to list_parameter affects list_argument.

We can add a print(list_argument) to see if the deletion of the last value in the list_parameter affects list_argument.

When we run the program, we will see that list_argument has 1, 2, 3, and 4. 5, which was the last value was deleted.

If we were using integer or string parameters with functions, those arguments are passed by value.

Passed by value means that there is a copy of the variable. The variables will be independent.

Remember that using a list as an argument will be a pass by reference. The argument and parameter will be the same variable.

We didn’t talk too much about using a list in a list.

A list in a list is used to create a matrix.

A matrix is a fancy way of saying a table of data.

Just think about a Microsoft Excel spreadsheet.

If we think about a list, it’s just a row of comma separated values.

The difference between a matrix and a list is that a matrix has multiple rows and columns.

A 3 by 3 matrix would be a 3 by 3 table with data:

Each row is a separate list, meaning that each row is enclosed in brackets.

Then, the entire matrix is contained in a list.

We can write this matrix in a single line like:

The matrix is a list. Then, each row is a list element in the list.

How we access a value in a matrix is we use the index from the row, followed by the index of the column.

For example, if I wanted to get the first value in the matrix, which would be row, 0, and column, 0, I would write.

You can extract any matrix value this way. Just think of using the double brackets, get the row first, then the column second.

When we run the program, we get 1, because 1 is at row, 0, column, 0, of the matrix.

You can use for loops with matrices.

When we run the program, we’ll get all the values of the matrix.

In this for loop, the first for loop traverses the rows.

Then, the second for loop looks at the length of the current row in order to traverse the columns.

Inside the column for loop, we’re accessing the cell at the row column index.

The last thing that we’ll talk about lists is that strings can be converted into lists, and lists can be converted into strings.

To convert a string into a list, you can use the .split() function.

The .split function works well with comma separated values.

The csv files that you’d normally use with Microsoft Excel or a different spreadsheet program.

Let’s say that we had a string:

We can see that there are words in the string separated by commas.

This string would be much more useful to us as a list.

Inside the parentheses, you put the character or string that you want to separate the string by.

I want to separate the string by its commas. Every time, there is a comma, it creates a new value in the list.

When we run the program, we can see that fruit_list is a list where each value is the fruit string before a comma appeared.

We have apples, bananas, mangos, oranges, and strawberries each as a value in the list.

Next, we can change a list to a string.

Let’s say that we had a list that looked like a sentence, so it’d be more useful to us as a string.

We can use the .join() function to join each value of the list together to make a string.

Before the .join(), we put the string that we want to use to separate the values of the list.

I want to put a space between each value of the list to make a proper sentence.

Inside the parentheses, we put the list.

I can print out sentence, and I’ll get, “Are you learning Python?” as a string.

Let’s talk about tuples. Tuples are very similar to lists.

They contain an ordered set of values like a shopping list or a checklist just like a regular list.

The big difference between tuples and lists is that tuples are immutable, meaning that its values cannot be changed.

Lists are mutable, meaning that list values can be reassigned and changed.

You can create a tuple with the same setup as a list, but instead of square brackets, you use parentheses:

However, even though you use parentheses to create a tuple, you use square brackets to access elements of a tuple.

Let’s say that we wanted to get the first element of this tuple_example.

When we run the program, we get 1, which is the first value of the tuple_example variable.

Now, you might be thinking, why would we use tuples? You can’t change the values in tuples!

Tuples also lack many of the functions that we demonstrated that lists had in the last video.

The main benefit of a tuple is that tuples are faster for constructing a list of values.

If you need to create a list of values that you won’t need to access and manipulate later, using tuples might be for you.

For example, let’s say that we wanted to create a function that swaps two values.

In the function, we are creating a new tuple with x and y swapped with each other.

Tuples are good for quick construction and usage. Tuple construction is faster than list construction.

When we run the program, swapped_values variable will have a tuple with 2, 1.

Tuples, being immutable, are a tad more memory efficient, but it’s almost negligible.

Most of the time, I use lists because there are many situations where I need to manipulate the values of a list.

I would only use tuples whenever I have a simple function where I knew that I would not have to manipulate the values of the tuple beforehand.

If you want a function to return a few values that won’t be changed, feel free to use tuples.


Video Demonstration

Introduction to Python – Chapter 7 – Lists

In this video, we’ll talk about lists.

List is the term used for an ordered sequence of values where each value has an index.

Before we continue to talk about lists, there is also a term called arrays from other programming languages that you might have heard about.

Arrays are almost exactly like lists in Python. There’s an array module in Python for using arrays.

In Python, arrays can only hold data of the same type. Lists can hold multiple data types.

Python arrays are better than lists memory-wise. But in Python, lists are better performance-wise than arrays.

If you know about arrays from a different programming language, use lists in Python because lists in Python are faster than arrays.

Most of the time, speed is more important than memory when talking about these data structures.

Usually when people say “array” when talking about Python, they mean “list” because lists are fundamental to Python the same way arrays are fundamental to other programming languages.

When we talk about a list, just think of any list of values like a shopping list or a checklist.

Every value inside a list has an index.

An index is the numbered position of a value in a list.

The first value in a list starts at index, 0. The second value has index, 1, and so on.

The actual values in a list are called elements.

Lists are like strings in the way that they can be broken up into their individual parts.

The difference between a list and a string is that the values in a list can be of any type.

Let’s make a list to demonstrate. To make a list, you use a couple of brackets.

In those brackets, you include each value and separate each value by a comma.

In Python, the values of a list don’t have to have the same type.

We can mix values of different types in a list like:

When you put a list in a list, the list inside the list is called a nested list.

We can print out the lists.

When we run the program, the lists are printed with their values.

We can make a list without any elements. This type of list is called an empty list.

Let’s talk about how you can access a list.

You can access each element of a list with its index.

If I wanted the first element of example_list, which is 1, I would write:

When I run the program, I get the 1, because the first value of a list starts at index, 0.

You simply write a pair of brackets and put the index in between the brackets.

You can use the len() function on a list the same way that you could use the len() function with a string.

The last value in a list has the index, len(list_name) – 1.

We will get the value, 4, because it’s the last value in the list.

You can also use -1 to represent the last index in the list, but most people don’t prefer to use the negative numbers to represent the indices.

Like with strings, if we were to access an index of a list that does not exist, we’d get an IndexError.

There is no index that is the length of the list, example_list, so when we run the program, we get an IndexError.

Let’s talk about using iteration and loops with lists.

The while loops and for loops that we talked about in previous videos can be used with lists to visit and get the values of a list.

You might want to visit every value in a list.

If you’re visiting every value in the list, then you should use a for loop because there’s a counting process where you have a start position progressing toward an end position.

I’ll repeat the most popular for loop concepts that we talked about in the last video.

The most popular way of using a for loop with a list is visiting every value of the list.

This for loop is the simplest to make. It uses the for keyword followed by a variable that you name.

I used i in example_list, which means i will take the value of each value of the list at each step.

When you want to create this type of for loop, the general setup is always:

If you read the for loop in English, it becomes easier to understand.

for every variable in list, do something to the variable.

When I run the program, I get the contents of the list printed out line by line like how we printed out the characters of a string in the last video.

The second popular way of traversing a list with a for loop is using enumerate keyword.

Using enumerate keyword allows you to not only get the value of each position in the list, but also get the index.

For example, we can write:

We use the for keyword followed by two variables this time around. I named the variables index and value. Then, in enumerate the list.

enumerate allows you to retrieve both the index and value in that order, which is why I used the variables, index comma value.

When we run the program, we’ll get the index followed by the value printed out.

Let’s talking about checking if a value is in a list. Checking for membership.

Let’s say we wanted to check if “microwave” was in this list.

When we run the program, since “microwave” is inside appliances, we get “microwave in appliances”.

You can use operators on lists.

Let’s say that I wanted to combine two lists.

c becomes a new list with the contents of a and b.

The list will be [1, 2, 3, 4].

When I run the program, I get the new list with a and b’s list values.

The multiply operator can repeat the contents of a list.

For example, let’s say that I wanted to multiply a’s contents by 3 times.

When I run the program, I get [1, 2, 1, 2, 1, 2]

The values inside a, which were originally 1, 2 are tripled because I multiplied a by 3.

We call using operators on lists, list operations.

In the last video, we talked about string slicing, which was the ability to grab a subsection of a string without using a for loop.

Lists can also use slicing.

If I wanted to get a list with a, b, and c, I would use list slicing.

How list slicing works is you have a start position followed by a colon followed by the end position + 1.

The start position 0 in list slicing is inclusive. example_list at index 0, which is “a” is included in the new list.

Then, the list slicing visits every value in between start position until end position.

The end position 3 is non-inclusive, which means that example_list at index 2, which is “c” is included in the new list, but example_list at index 3 is not included. 0 is inclusive. 3 is non-inclusive.

When we run the program, I’ll get the half_list, which is a new list with “a”, “b”, and “c”.

In the last video, we talked about how strings were immutable, meaning that we could not change the characters of a string with different characters.

Lists are mutable in Python. We can change the elements of a list.

The first value of the list is changed to a “b”.

You can also do fancy things like use list slicing to assign new values.

For example, I could use list slicing to change the first three values of the list.

example_list[0:3] = [“x”, “y”, “z”]

Now, when I print example_list, the first three values will get the x, y, z because I used string slicing to get the first three values then I reassigned them with x, y, z.

I can run the program, and I’ll see that the program has the “x”, “y”, “z”, “d”, “e”, “f”.

Let’s say that we wanted to add new values to the list.

There’s a very useful append function that lists can use to add new values to the end of a list.

When I run the program, we can see that the last three values of the list are g, h, and i, which were added with the .append function.

Let’s say that we wanted to sort the values in a list.

example_list = [“b”, “a”, “e”, “c”, “f”, “d”]

You can use the list’s sort function.

Sorting a list can be very useful. All you need to do is add a .sort().

When we run the program, we can see that the values in the list have been sorted in alphabetical order.

Another very useful list function is reversing a list.

Let’s take that sorted_list and reverse it.

All you need to do is add a .reverse() to the list. When we run the program, we get the reversed list.

The last thing that we’ll talk about is list deletion, which means that I can delete values in a list.

Let’s say that I wanted to delete the last value in the list.

First, I’ll get rid of example_list.reverse().

When I print example_list, “f”, which used to be the last value of the sorted list has been deleted.

There are more functions that you can use with lists, but we’ve talked about the most useful ones so far.

Google is your friend, so if you ever can’t figure out how to get a specific value from a list, Python might already have a built-in function that does exactly what you’re looking for.


Video Demonstration

Introduction to Python – Chapter 6 – Strings and For Loops

In this video, we’ll talk more about strings and explain the for loop.

A string is a data type created when we use a pair of quotation marks.

is an example of a string.

Let’s say that I wanted to get the “m” character in “microwavesam”.

A character is the term used for a single symbol in Python.

In Python and programming languages, we also use the term, element.

An element is a term for any individual part of a string.

To get a character in a string, you grab its index.

An index is a fancy term for a member of a set of parts.

For example, to get “m”, I could write,

bracket 0 bracket is the index.

The index is just a fancy term for a position in the string.

In Python and programming languages, the position of the first character starts at 0.

The reason why position starts at 0 is because an index represents the offset from the first character.

At the first character, I am 0 positions away from the starting position.

The first character is m. At the starting position, I am 0 positions away from the first character.

If I print first_letter, I will get an “m”.

When I run the program, I get the first_letter, which was at index 0.

I can get the second letter by assigning:

When I run the program, I also get the second letter, i, which was at index 1.

Just remember when getting a single character from a string while using an index, the first character’s index starts at 0.

Next thing that we’ll talk about is length of a string.

Python strings have a len function that allows you to get the length of a string measured in the number of characters.

If I write,

I will get the number of characters that make up “microwavesam”, which is 12.

The len function is very useful for getting the last character of the string.

If I wanted the last “m” in “microwavesam”, then use len_username – 1.

The last character’s index is 11 since the first chracter’s start position was 0, which means that the last character’s index is len_username – 1.

If I try to get the character at an index out of range, then I’ll get an IndexError.

For example,

I can try to get the index of username at length of username.

When I run the program, I get the IndexError, because there is no character at that index.

The last character’s index is len_username – 1. Not len_username.

Instead of using len_username – 1 to get the last character, we can use index, -1.

To get the second last character, -2. Keep decreasing the negative number index, to get the characters in reverse.

In the last video, we mainly talked about how iteration could be much easier with while loops since while loops can perform repetitive steps until its condition is false.

There’s another type of iteration called for loops.

A for loop visits each character of a string one at a time, and you can do something at each index or position that you visit.

Using for loops and while loops is called a traversal.

In a while loop, we have a variable that progresses, which eventually makes the while statement condition false.

Let’s say that we wanted to print each character of the username, “microwavesam”, 1 at a time.

index starts at 0 because the starting position is 0 elements away from the first character.

Now, I want to visit every element of microwavesam, so the condition that I want to end my function is when my index is greater than or equal to the length of microwavesam.

When the index is less than len(username), I can print the character at the current index.

Now, I need the index variable to progress, so that it eventually makes the condition false.

This while loop is visiting each character of the username variable.

At each index, we print the character until index is greater than or equal to the length of microwavesam since the last index would be len(username) – 1.

Remember that the last character of a string is len(username) – 1.

This while loop is an example of how a for loop works.

We can do visit every character in “microwavesam” with the for loop.

In this usage of a for loop, the for loop begins with the for keyword.

Then, I left the name of a variable, letter.

in is a keyword that means exactly what it implies.

Using letter in means at each step of the for loop, we are visiting the username’s characters 1 by 1.

In this for loop example, you don’t have to keep track of the condition of stopping at last character.

This for loop automatically will stop after visiting the last character of “microwavesam”.

The second way to do a for loop is by range. Sometimes, you only want to visit a certain number of characters like the first three characters.

Let’s say that I only wanted to visit “mic” from “microwavesam”

We use the for keyword and the in keyword again.

This time I use i as the variable name, short for index.

Then, after the in keyword, I use range(0, 3).

With range, you put the starting number. What will i be at the first step?

Then, each step will by default increase i by 1.

When, the i becomes 3, don’t do the steps in the for loop. The for loop is done.

In this for loop, we start at 0.

Increase i by 1. i = 1.

Increase i by 1. i = 2.

Increase i by 3. When i is 3, exit the for loop.

When we run the program, we will get “m”, “i”, and “c” each on a new line as expected.

If we wanted to print every character of the “microwavesam” with this way of writing a for loop.

We can easily change 3 to len(username).

When we run the program, we get every letter printed out in “microwavesam”.

You would use this type of for loop whenever you want to have more control over each step of your for loop.

For a better example on this for loop’s control, we can print out every other letter.

When you put an additional number inside the parentheses, that number is added to the variable at every step.

i will be increased by 2 at each step, which will allow us to visit every other number.

When we run the program, the for loop will visit every other letter in “microwavesam”.

You can make the range be flexible. We can go in reverse.

For example, we can start at the last index of the string. The last letter of the string.

When we run the program, we visit every character backwards. We start at the last “m”.

len(username) – 1 is the start position.

We are adding -1 to i each step.

When i is -1, we don’t run the statement in the for loop, and the for loop ends.

The third way you can use a for loop is with enumerate. enumerate allows you to get the index and the value as two usable variables.

For example, there are many situations where you’ll need both the index and the value, which is why you would use range.

But sometimes, typing the range may be bothersome, so you can use enumerate like this:

Let’s say that we wanted to print out both the index and value at the index.

You can place two variables that will get the index and value from that index when you use enumerate(username).

These three ways of using for loops provide you with the control to get exactly what you want from every step in the loop.

Now, you might be thinking, why should I use a for loop?

After all, a while loop can do the same thing as any for loop. Why not just remember how to do while loops?

The two main advantages of a for loop are locality and readability.

First, locality.

When we were creating a while loop, we created an index variable in the outside of the while loop.

When we create a for loop the variable is declared inside the for statement.

What happens to the variable declared in the for statement stays within the for loop.

If the variable was created in the outside of the loop like in a while loop, you or someone else might make a mistake in the future and use that variable by accident and cause problems.

Second, being specific. for loops are more readable.

You have a start position and an end position. The start and end positions are clearly defined in the for statement.

We’ve seen that the for statement does initialization, step, and completion condition all in one line.

In a while loop, the while statement has an end condition or completion condition.

The initialization and what to do at each step are located elsewhere.

A while loop is not as quickly readable as a for loop.

A for loop is great for counting up and down like going through each character in “microwavesam” or counting down to the New Year.

A while loop is better for conditions that do not involve counting like the difference between these two doubles must be less than 0.02.

I’m not counting up or down. I’m checking a difference, and I want to keep on tweaking the two numbers until the difference is less than 0.02.

A while loop would be better for that situation.

When you’re counting up and down, visiting through a step by step process that involves incrementing or decrementing numbers, think for loops.

When you have a condition that you must check, and you’re not necessarily counting up or counting down, think while loops.

Now that you understand for loops pretty well, let’s talk about string slicing.

A string slice is a term for a part of a string.

Instead of using a for loop to get the first 3 characters of a string, Python has an abbreviated form using the index numbers.

For example, to get the first 3 characters with string slicing:

Inside the brackets, you put the starting index position, then a colon, then 1 + ending position.

I don’t want to visit the character at index 3 because the character at index 3 is the 4th character.

The first number is inclusive. The second number is non inclusive.

When I run the program, I get “mic” all in one word. String slicing is great for getting entire segments of a string.

It makes getting a continuous part of a string much easier than using a for loop.

Let’s talk about how string are immutable.

Immutable is the term used when something cannot be changed.

In a previous video, we talked about how we could use the addition operator, +, to add two strings together.

A term for adding two strings together is concatenate.

For a string, you cannot change individual letters, which means if I wanted to assign a new letter for a word, I would get an error.

Instead of “microwavesam”, I want “microwavefam”.

When I run the program, I get an error about how the string or object doesn’t support item assignment.

Strings are immutable, which means that portions of a string cannot be reassigned and changed.

A little bit ago, I talked about how for loops are great for counting up and down.

Let’s do a for loop example with a counter.

A counter is a term used often in programming. It’s just a word used for variable that keeps count of something.

We can count the number of “m”‘s in “microwavesam”

We can use variables assigned outside of the for loop inside the for loop.

We can use conditionals like normally inside the for loop.

In this for loop, we check if the current character is equal to “m”.

If the char is equal to “m”, then we increase the count by 1.

When we run the program, we print out the number of “m”‘s, which is 2.

counters are useful variables that keep track of the number of anything inside a loop.

Searching. You can find a segment of a string by using the “in” keyword.

For example,

Using if string in a string can find whether a string is in another string.

“microwave” is inside “microwavesam”, so when we run the program,

“microwave in microwavesam” is printed out.

Instead of just finding a string in a string, we can also see if a string starts or ends with a certain string.

This is very useful if you expect a certain prefix and suffix.

With the .startswith(“”) and .endswith(“”), you can check whether a string starts with or ends with a certain string.

When I run the program, two Trues are printed out because username does start with “microwave”, and it does end with “sam”.

You can check a count of a letter in a string without using a for loop.

When I run the program I get a 2 like we did when using a for loop.

Using .count with a string finds how many of that string is inside “microwavesam”.

There are 2 m’s in “microwavesam”.

There are functions that can change the case like uppercase and lowercase.

Using .lower() makes the string all lowercase.
Using .upper() makes the string all uppercase.
Using .capitalize() makes the first letter capitalized.

Last but not least, there are functions for strings that allow you to replace substrings or take out white space.

You can replace a part of a string with something else. Think of the find and replace feature in most text editors.

When we run the program, “sam” is replaced with “bob”.

Occasionally, you’ll have a string with a lot of whitespace at the end of a string or in the beginning of a string.

You can take out all whitespace by using the .strip function.

When I run the program, all the white space has been stripped from the username variable, and I get “microwavesam”.

Those functions are the main functions that I would use when I have a string.


Video Demonstration

Introduction to Python – Chapter 5 – Iteration and While Loops

We talked about recursion and iteration in the last tutorial.

Recursion is the term used when you call the same function inside a function, which causes repetition since you’re repeating the function.

Iteration is the term used when you repeat steps without using recursion.

This video will be about making iteration or repeating steps easier!

In tutorial #2, we talked about most recent assignment because we talked about how you can assign a variable multiple times.

A variable takes the value of its most recent assignment.

When we’re repeating the assignment of a variable, we are iterating.

When you hear iteration, think repetition.

Let’s say that we set:

Here, we set b = a, and since a’s most recent assignment is 2.

b is equal to 2.

Even though b is equal to a, b is unaffected when we add 1 to a.

b is completely separate from a.

When we add 2 to b’s most recent assignment, we get 2 + 2.

In that example, we were iterating the assignment of a variable.

Instead of writing each repetitive step 1 by 1, Python has statements that make writing iterations or repetitions easy.

We’ll start with the while statement or also called while loop.

The while statement works like a conditional.

When the condition is true, the statements underneath are run, but the difference is that the while statement is checked again, and if the condition is still true, then the statements underneath are run again.

As long as the condition stays true, the statements underneath are repeated.

We use the term while loop because the while statement loops in a circle, repeating its statements.

We can write the same function that did the countdown to New Year’s like we did last video.

The while statement is like an if statements that continually checks the condition after running all the statements underneath.

We start at 10.

num must be greater than 0.

The condition is True, so all the statements underneath are run.

num is equal to 10 – 1.

Now, num is 9.

All the statements tabbed once to the right have been completed.

The while statement checks its condition again.

9 is greater than 0, so the condition stays True.

Repeat all the statements underneath.

Keep on repeating until the condition is false.

The condition is false, when num is 0 because 0 is not greater than 0.

The while statement is similar to recursion, but it doesn’t reuse a function.

There are two main parts.

1. The condition

A while statement is triggered by a True condition like an if statement.

2. Progress

You need to make sure that the condition is eventually False or else, you’ll have an infinite repetition or loop.

For the while loop that we have written, we are constantly decreasing num by 1.

num is decreasing every time we repeat the contents of the while loop.

10 becomes 9, 9 becomes 8, and so on until num is 0. When num is 0, it is not greater than 0, so the while statement ends there.

Then, print(“New Year’s”) happens and afterwards, we’re at the end of the function.

Using iteration with the while statement makes repeating steps much easier than recursion in most cases.

Instead of manually writing print(10) print(9) and so on 1 by 1, the while loop allows us to repeat a series of steps until the condition is False.

In the last video, I told you that if iteration seems easier, then you should use iteration.

But when iteration seems complex, try to think out the solution with recursion to see if recursion will make solving the problem easier.

Let’s do another example,

Let’s make a while loop that prints a number of lines.

First, the function should take in a parameter for the number of lines that we want.

Next, we want to use the while loop. We want to think of a base case. The moment when we are done with the while loop.

We can use num being equal to 0 as a means of ending the while loop.

Step 1 is figuring out our condition. Our condition should be (num != 0) because when num is 0, we are done.

while loops always have the keyword, while, followed by a condition and a colon after the condition.

We want the while loop to print out a line when num is not 0. num starts at 3.

Step 2 is progress. We want num to be decreasing at each step or iteration.

We can subtract num by 1 with each step to make sure that we’re making progress to make the condition eventually false.

The condition will be false when num is equal to 0, so decreasing num by 1 each step makes sense!

We want to print out an empty line at each step because that’s the purpose of our function.

Let’s call out function with the argument 3.

When we run the function, 3 lines are printed out.

Let’s take a closer look at our function.

The argument is 3, so num = 3.

while loop always looks at the while statement and checks if it’s true.

Step 1) the condition. The condition is true because 3 != 0. Do the statements underneath.

3 – 1 = 2

Check condition

2 != 0 is True

2 – 1 = 1

Check condition

1 != 0 is True

1 – 1 = 0

Check condition

0 != 0 is False, so while loop ends here.

While loops make repetitive steps much easier. If you are using repetition, think while loops.

There’s something called infinite while loops. Let’s talk about infinite while loops.

If you forget step 2, progress, then you’ll come out with a while loop that never stops.

If we delete the line, num = num – 1, the while loop will never stop because the condition will always be true.

3 != 0 is always true. num != 0 is always true because num always stays the same. There’s no progress.

The while loops continues forever! On a Windows computer, you can use CTRL-C to end the program.

We want the while loop to end, so always remember that you need progress that will make your condition be false eventually.


Video Demonstration

Introduction to Python – Chapter 4 – Return and Recursion

In this video, we’ll talk about return statements and recursion.

In a previous video, we talked about how the value that you get from a function is the return value.

If I call type(4), I get the return value of int.

How does the type() function return the type int value?

Let’s write a function that adds two numbers and returns the result the same way how the type() function gets a result.

Notice how the function uses the same format that we’ve learned in the last video, but there’s a new line that we haven’t seen before.

What return result does is that it gives the value, result, to where the function called.

The return statement also ends the function.

The reason why I bring up return statements here is that you can use the return keyword inside a conditional, and it ends the function.

Let’s change our function a little bit.

If I were to call add_two_positive_numbers with:

I get the print message, num1 is negative.

I also get a return value of None because return stopped the program after the print(“num1 is negative”).

return can be used to exit the function. If there is no return value, you get a None, which means like it implies: nothingness.

Using returns with conditionals will help you limit your function to a specific behavior like what we did: adding only two positive numbers.

In a previous video, we used a function that we created inside another function.

Whenever we used the print function inside of our functions, we are using a function inside of a function.

Let’s talk about recursion. What is recursion? Recursion is the term used when a function calls itself.

Instead of a function calling a different function, the function calls itself.

A function triggering itself inside the function?

You might be thinking that triggering the function in itself would lead to an infinite loop of the function triggering itself.

You use a conditional that stops the function when you’re ready. A conditional that stops a function calling itself is called the base case.

The base case is the way that a function calling itself can stop.

For example, let’s say that we wanted to make a countdown function celebrating the new year.

We are making a countdown from 10 to 0 for New Year’s!

10, 9, 8, and so on until we get to 0.

When we hit 0, it’s New Year’s, so when num is 0, we stop the function.

If num is not 0, we countdown again bring the num down 1 number.

We start at 10, 10 is not 0, so display the current num, and go to the next num, which is 9.

We are calling countdown function again, but with one less num.

You can notice that there are two main parts to recursion.

The first part is progress.

We make sure that there is some sort of progress every time we use the function again.

In the example, we decrease the number that we’re using by 1.

The number is perpetually decreasing, which means that there is progression towards an end.

The second part is base case.

We make sure that the a base case occurs at our goal. When we countdown from 10, we want to countdown to 0 eventually.

The number 0 is our end goal.

We use a if statement to check if our number is 0 yet, so that we can just stop calling the function over again.

If we don’t call the function, countdown again, the function stops because there is nothing else in that if statement to do except for displaying “New Years!”

Any recursion can be done iteratively. What is iteratively?

Iteratively means repeating a process one at a time. Doing things manually one at a time.

For example,

We are using the print function manually or iteratively one at a time to print three empty lines.

Any iteration can be done recursively and use recursion.

Recursion takes a moment to think about.

Remember that there are two parts.

Part 1) Progress.

Part 2) Base case. The end point.

Decreasing a number or increasing a number is usually a good way to make progress.

The function calling the function must make progress.

A usual base case is checking for 0.

We want to print 3 new lines, so let’s use the number 3 as our argument to act as our starting point.

To make progress, let’s decrease the number 3 each time we use the function.

To end the function, let’s check if the countdown reaches to 0, because if we count from 3 to 0, we should have printed 3 new lines.

Checking if the number is 0 will be our base case, the end point.

3 is greater than 0, print a new line.
3 – 1 = 2

2 is greater than 0, print a new line.
2 – 1 = 1

1 is greater than 0, print a new line.
1 – 1 = 0

0 is not greater than 0, do nothing, which stops the function because there is nothing left to do.

You might be thinking: When do I use recursion and when do I use iteration, writing each line one by one? Why even use recursion?

Recursion is an important concept to understand because some very specific problems are much easier to solve with recursion.

For example, the Fibonacci sequence. Fibonacci numbers are a sequence of numbers in which each number is the sum of the two preceding numbers.

This problem is easier to solve with recursion than iteration. It’s a very specific problem, which happens to be easier to solve with recursion.

The majority of the time if you’re not dealing with a specific type of problem that works well with recursion, you should use iteration instead and write the repeated lines of what you want to do like how we printed 3 new lines by writing print() function 3 times.

Let’s talk about the cons of recursion.

Number 1) For Python, recursion is slower than iteration.

Speed is a huge turn off when using recursion. Think about speed.

Number 2) You may get confused in making your recursive function because often times, you might think hmmmm at step 5,

I am expecting the number to be this, and I think that if the progress keeps happening, the number will be what I expected.

It’s harder to write a good recursive function.

Number 3) Recursion uses more memory.

With all those cons, why would you even use recursion?

The main advantage of recursion is when you have a very specific problem that has a point A and a point B, and you need to get to point B, but to get to point B requires a large number of complex repetitive steps.

Recursion might be for you. In this very specific situation like Fibonacci numbers, recursion is absolutely the choice to use.

I would recommend to Google for some advice to see if recursion would be great for your very specific problem.

The ultimate rule to is if you ever think that writing your steps iteratively is hard, see if recursion will be easier.

If writing your steps iteratively is easy, then use iteration.

For example, in our countdown problem, counting down from 10 to 0, it’s easy to make.

We can easily print the countdown from 10 to 0. Since it’s easy to make, we should use iteration.

We learn recursion because you will encounter those very specific problems where recursion is the best or only way to solve the problem!

The last topic that we’ll talk in this video is infinite recursion.

Infinite recursion is the term used whenever the function keeps calling itself and never stops.

There’s no base case. There’s no end point.

For example,

We can write a new function:

There is no if statement base case that stops the program. All this program does is call itself again and again and again.

Python has an error called Maximum recursion depth exceeded that stops the function from calling itself infinite times.

If there was no Python error to stop the recursive function, the function would call itself until we wouldn’t have any more memory.


Video Demonstration

Introduction to Python – Chapter 3 – Conditionals

In this video, we’ll talk about more operators you can use, conditionals, and recursion.

We’ve talked about the basic operators in the previous videos.

Operators like plus, minus, multiply, and division. A very commonly used operator is modulus or also called modulo.

What’s modulus?

Modulus works on integers and finds the remainder when dividing two numbers.

The modulus operator is the percent sign (%).

For example,

Think of dividing 7 by 3, but what gets returned is the remainder, which is 1.

Why would you need to know about the modulus operator?

The modulus operator is great for checking divisibility!

We can check if a number is an even number by using modulus.


Whenever using modulus against 2, if the remainder is 0, we know that the number is even since modulus checks for divisibility!

Any number divisible by 2 is an even number.

Let’s talk about booleans. What are boolean expressions?

booleans are the term used for True or False values.

It’s our way of telling whether a statement is True or False.

For example, we can compare two values.

5 == 5 is True

Notice that we used two equal symbols.

Two equal operators means that we want to see if the statement is True or False.

5 == 5 returns True.

In the previous video, we used one equal, but that was for assignment.

We call these types of operators, comparison operators, because we’re comparing two values.

Putting an exclamation point before the equal sign means not equal like:

5 != 5 would be False

There is support for greater than, less than, greater than or equal, and less than or equal.

6 > 5 would be True
6 < 5 would be False
6 >= 6 would be True
4 <= 4 would be True

For greater than or equal or less than or equal, the equal symbol goes after the greater than or less than sign.

Let’s talk about conditionals. What are conditionals?

Conditionals derive from the word, condition. Only do something based on a requirement.

Conditionals trigger a certain behavior based on the requirement of the boolean values, True or False.

If statements are the most used conditional. They look like English.

Which can be translated to:

x should be 6 since the if statement is True.

x is equal to 5, so we do the something, which is adding 1 to x, which makes x to 6.

x should now equal to 7. Since x was 6, it is True that x is less than 7, so we do the thing, which was add 1 to x.

You can notice that the format of the if statements always follows:

Like making a function definition, you start with the keyword. In this case, if.

Then, you space, put in the parentheses, the condition that compares values, then there’s a colon just like how defining functions works.

Most importantly, on the new lines, everything that you want the if statement to do, is tabbed once to the right, so that Python knows oh the conditional is true, do everything below the conditional that is tabbed once to the right.

The next thing that we’ll talk about are logical operators.

What are logical operators?

Logical operators is the fancy term for operators like and, or, and not for using multiple conditions or changing the condition’s meaning.

You can put and, or, and not in Python, and they have the same meaning as they do in English.

For example, think of a range of numbers. How do I check if a number is greater than 0 but less than 10? I can use the and operator! Because I need two conditions!

If I use and I can check for multiple conditions simultaneously. The conditional will be true if and only if both conditions are true.

If x was = to 11, then the condition is False since and requires both conditions to be True.

Nothing is printed out.

Let’s say that instead of wanting x to be between 0 and 10.

Let’s say that we wanted x to be outside of 0 and 10.

We can do this two ways.

First way, we can use the not operator:

By adding a simple not, we can read the condition as it would read in English.

if (x is not greater than 0 and x not less than 10)

Well, -5 is not in between the range of 0 and 10, so the conditional is true.

The other way we could trigger the conditional when x is outside of the range of 0 to 10 is with the or operator:

We read the conditional like English. If x is less than 0 or x is greater than 10, then do the statements below the conditional.

With the or operator, if either of the conditions is true, then, the statements are triggered because like how or means in English or means the same thing in Python.

Whenever you want to combine conditions in a conditional, think of the logical operators, and, or, and not, and what they can change your conditional meaning if it were English.

We’ve talked about the if statement.

When the conditional is True do something, but when False, do nothing.

What if I want to do something else when the conditional is False?

There’s something called the else statement!

Trigger different behavior when the if statement is False.

The else statement depends on an if statement. The format is as follows:

If the condition is true, do something. If the condition is not true, do something else.

Let’s say that we wanted to do something when x is an even number. And do something else when x is an odd number.

In the beginning of the video, we talked about the modulus operator that could check the remainder of a number divided by another number. Divisibility.

We can use the modulus operator with the comparison operator at the same time.

We know that if there is no remainder when x cleanly divides by 2, then x has to be even because even numbers are always divisible by 2.

But if x does not cleanly divide by 2, then we know that it has to be an odd number.

Since x is equal to 1, that means that the conditional is False, so the else statement is triggered.

When the if statement is False, do the else statement, so

1 is odd is printed out.

Let’s move on to chained conditionals, which is a fancy term for putting multiple conditionals in between the if and else statements.

Earlier in the video, we talked about the and operator for multiple conditions in the same if statement. Sometimes, you want multiple conditions for completely separate actions.

Think of a multiple choice exam. Who want’s to be a millionaire?

You have choices, A, B, C, and D.

An and operator in an if statement won’t be enough.

You need multiple if statements.

Luckily, there’s the elif statement, which is short for else if. elif allows you to use multiple if statement statements.

For example,

You can put any number of elif statements.

If two of these if statements are true, the first one will run instead.

For example,

Both if statements are true, but only the first if statement gets executed, so we see “x is greater than 0”

You can put if statements underneath if statements.
We call putting conditionals like if statements underneath other if statements nested conditionals.

Nested conditionals is a fancy term for putting conditionals underneath other conditionals.

For example,

x is positive because it’s greater than 0. Then, we encounter the if else statement underneath.

10 is cleanly divisible by 2 because it’s an even number, so x is even.

Notice how the we also tab once to the right from the relative positive underneath the if statement (x % 2 == 0)

Underneath (x % 2 == 0), we put one tab to the right from the relative position of the if statement.

Just remember that you have to put a tab underneath conditionals relative to where the conditional started.

Nested conditionals don’t always look the best way. Sometimes, instead of nested conditionals, you can use the logical operators like: and.

Our nested conditional example checks if x is greater than 0 and is even. We can put these two conditions in one line.

The main lesson that I want you to get out of conditionals is that they allow you control exactly what your program will do based on your set of requirements.

You need your program to do something based on requirements. Use conditionals.


Video Demonstration

Introduction to Python – Chapter 2 – Types and Functions

This video will expand on the basic concepts that we talked about in the previous video. In the first video, we talked about a terminology called assignment.

x = 5 is an assignment.

You assign values to variables. A variable can be assigned many times, and it always keeps the value of its most recent assignment.

If I do, x = 7, it replaces x = 5.

You can do x = x + 1, which adds 1 to its most recent assignment.

If we print(x), we would get 8 because 7 was its most recent assignment, and we add 1 to 7.

In the previous video, we also briefly talked about functions. We used the print() function and the type function().

A reminder of what functions are. Functions are fancy terms for defining commands that we can use in Python, and Python comes with a lot of preconfigured functions like print() and type().

When we use a specific function, it is called a function call.

When I write type(4), I am calling the function type with a value 4.

When calling a function, the value inside the parentheses is called an argument. 4 is an argument of the function.

All you need to know is that values inside the parentheses of functions are called arguments. That’s the name that they’re given.

When I print(type(4)), type(4) gives us the value, <type ‘int’>, which we print and display.

Whenever a function call gives us a value, we call it the return value.

Using the type function, we expect the function to give us back the type of the value, and if the function gives us anything back, that value given back is just called the return value.

We’ve talked a bit about types so far. Sometimes, you don’t have the type that you want.

For example, you could have a string like fruits = ” apples”

Before the word, apples, you want to put a number like 5 to get 5 apples.

We talked about how you could use the + operator to combine strings together.

However, you cannot combine an integer with a string because they’re not the same type.

Python has built-in functions that convert values from one type to another type.

There’s a function called str() that converts a value to string type. I can use str on the number 5 and add the str(5) to fruits because a string and be combined with another string.

There is a function called int() that converts a type to an integer if possible.

int parentheses with a value inside them. For example,

4 has quotation marks, so it’s a string, but since the string is also a valid number, we can convert the string into an integer with the int function
However, if we were to put a word in the int() function like int(“microwavesam”), there’s an error because int() cannot convert strings that aren’t numbers into integers.

You can also use int() with a float. A float has a decimal point value like 1.5. When you use int() with a float, every number after the decimal point is deleted. So int(1.5) is 1.

The numbers in this case, 5, are removed.

int(1.58). 58 are removed. Integers are whole numbers, so when a float is converted to an integer. There’s no rounding. The integer just deletes every number after the decimal point.

There’s a function called float() and str() for converting types to floats and strings.

float(4) becomes 4.0 because floats always have numbers after the decimal point, so an integer and whole number like 4 gets a decimal point and an automatic 0.

str(4) becomes “4” with quotation marks since strings always have a pair of quotation marks.

We’ve talked quite a bit about numeric types so far. Integers and floats.

You might be thinking why not just have a type called number and make classifying numbers easier?

Why do we have integers for exact whole numbers and floats for values with decimal point numbers? One reason is because of different behavior.

Depending on your version of Python, the division operator works differently for float and integers.

If you’re using Python 3.6 like me, you can write the expression 1 / 2 and get 0.5. Python 3.6 automatically gives the result of type float when expected.

Let’s say that you were using Python 2.7, another popular version of Python.

If I divide, 1 / 2, the result is 0 because when you divide 2 integers, you get an integer in Python 2.7 and below.

When an integer will have numbers after the decimal point, it will automatically delete every number after the decimal point.

What was supposed to be 0.5 became 0 in Python 2. Python 3 automatically converts the result to a float keeping the 0.5.

To fix this problem for Python 2, if we use 1.0 / 2.0 (two floats because we put a 0 after the decimal point), then we’ll get a float.

If you wanted to get an integer in Python 3 after dividing two integers, you can use 2 backslashes, and you’ll get 0 when you divide 1 with 2 like 1 // 2.

As we saw with division, integers and floats can have different behaviors, but they also are represented differently too.

I’m not just talking about oh, whole numbers are integers. I’m talking about inside the computer and memory. We need to explain what exactly is a float?

Floats are approximations of any number. What does that mean? For a human being, it’s easy to know that 1 / 10 is 0.1, a tenth.

Python stores floats inside memory only through 1s and 0s. The binary numbers. With binary numbers you can’t represent 0.1 exactly!

0.1 is stored as this gigantic approximation: 0.1000000000000000055511151231257827021181583404541015625
because Python can’t compute 0.1 exactly.

Many decimal point numbers like 0.1 cannot be represented exactly in the language, so we have a specific type, float, that deals with these complications.

When we print(1 / 10), Python rounds that gigantic approximation for us, so we still get 0.1 like we would expect.

We have a type, float, because numbers with decimal points aren’t exact representations, so Python separates whole numbers and decimal numbers with different types to account for their different behaviors.

Every now and then, you get strange behavior when adding two floats because of how floats are represented and stored!

To us, 0.1 + 0.2 is easy. It’s 0.3.

In Python, print(0.1 + 0.2) is 0.30000000000000004.

Next thing that we’ll talk about are imports.

Python has this thing called modules. Modules are just a fancy term for a package of preconfigured functions.

Functions like print() and type() come usable with Python, but Python doesn’t expect everyone to want all the preconfigured functions, so Python expects you to import them and specify oh I want these functions inside this module.

You can import a module by typing:

One such module is math.

We typically put imports at the top of the program.

This module comes with a bunch of preconfigured functions like sqrt().

To use a module’s functions, you type the module name, then a ., and then the function. For example,

math.sqrt(4) computes the square root of 4.

You don’t have to remember about modules and their functions.

Most of the time, I would suggest using Google to find out what a module can do.

For example, we can Google the math module and find all of its preconfigured functions.

Use Google to find out if Python has a preconfigured function for what you want to do or a module with a function.

We’ve talked a lot about these preconfigured functions that come with Python and its modules, but what about adding our own functions?

Specific commands that will do what we want them to do.

We need to define a function. Or in other words, create a function.

The layout of a function in Python goes like this.

def is short for definition.

The function definition starts from the left.

The statements below that function definition must be tabbed once to the right.

The tab is how Python knows that oh, these statements are part of the function, so if the user wants to run the function, do all the things below that are tabbed once right.

You can name the function anything that you want except the same rules for naming variables apply to naming functions.

values inside the definition of a function are called parameters.

Parameters are just another one of those fancy terms used for defining that the function expects variables inside the parentheses.

Earlier in the video we talked about arguments. When we use print(4), 4 is an argument.

However, when we’re making a function definition, the variable would be called a parameter. For example:

Let’s say that we were creating the function called print_number.

The variable, number, is called a parameter. But when we use our function, print_number(4), the 4 inside the parentheses is called an argument because we’re using the function.

The word, parameter, is used for the value in creating the function definition.

The word, argument, is used for the value in using the function.

Create a function vs use a function. Parameter vs argument.

You’ll see all of these terms often in the future, so it’s useful to understand the difference even though they can be confusing.

Whenever you’re writing the first line of a function at the end of the line, you’ll always see a colon.

Let’s make a function that uses no parameters.

Let’s say that we wanted a function, a command, that printed the first 3 letters of the alphabet each on a new line. We’ll call it alphabet

Parameters are optional. Empty parentheses means that there are no parameters.

To use the function that we created, all we have to do is type alphabet(). The same way that we would use the print() or type() function.

We can create functions that call or use other functions. Let’s say that we wanted to print the first three letters of the alphabet three times.

We can write:

When we use print_three_alphabets(), the function uses our alphabet function 3 times, and each time alphabet() function runs, it’s one by one.

The most important reason why we create our own functions is to make a program smaller by reducing repetitions!

We can have a repetitive action in a single line of Python if we create a function!

For the functions that we’ve been using like print() or type(), they only require one value. If you want to display the number, 4, you write print(4).

You can create functions with multiple parameters.

Let’s say that we wanted a function to display the number of animals a person has.

We separate each parameter with a comma.

Since I expect the user to send a number for the first parameter of the function, I’ll change that number to a string.

Earlier in the video, we said that we could convert types, adn the str() function converts the value to the string type.

Then, I’ll combine this string of the number with animal.

In the first video, we said that we could use plus with strings, and what plus with strings does is simply combine the strings.

Now, we can print the new variable we created, which is the number combined with a space and the animal name.

Let’s use the function, print_num_animals. Let’s say that we had 2 dogs.

When we use a function with multiple parameters, we separate the arguments by a comma just like how we made the definition.

The function takes the 2 arguments and uses those variables to print the number of animals.

Let’s talk about the order of execution. What’s the order of things run inside a Python script?

When you see the function definition with def, and a bunch of statements below the definition, the function won’t execute unless you USE the function.

You need to define a function and write that function definition before using it.

If I put alphabet() parentheses, trying to use it, before the function definition, I get an error that says alphabet is not defined.

In Python, statements are executed in order. Starting from line 1 to the end of the program.

Python is computed line by line in order.

If you had a lot of errors in your program, Python would look at your program, compute the first line, keep on going line by line until it finds your first error, and then stop. You’ll only see the first error message.

Then, you fix your program and run it again. Python would start at line 1 and continue until it sees the next error!

The last thing that we’ll talk about in the video is the concept of local variables. What do local variables mean?

When we declare variables we’ve seen that we can use variables the same way that we use values because the variables are equivalent to the values that we’ve assigned.

Like x = 5.

x is equivalent to 5, and we can use x in a function like print(x), and 5 would be displayed.

When variables are assigned inside a function, the variables belong to that function. The variables are local to that function.

They can not be used outside of that function. That’s where we get the term, local variable.

Let’s take a look at our print_num_animals function. We declared and assigned a variable called num_animals.

Can we use that variable? No because since the variable was declared and assigned in that function, the variable belongs to that function.

If we try to, print(num_animals) outside of the function, we get this error.

num_animals is not defined.

num_animals is local to the function where it was declared and assigned, so you have to pay attention where you make your variables.


Video Demonstration

Introduction to Python – Chapter 1 – Intro and Variables


Computer Science is not the study of computers nor is it only about programming. Sometimes, when people hear about Computer Science, they think oh, computers and programming!

In reality, computers are just a tool in computer science, and programming simply executes a sequence of instructions that we create.

Computer Science is all about computation, asking the question: “What exactly can be computed, how can we compute it, and how fast we can compute it?”

Computation is a fancy way of saying any type of calculation that follows rules or list of steps.

Multiplying numbers like 1 times 2 is a computation. There are rules and steps to multiplying two numbers. Likewise, adding 15 + 5 is a computation.

Computer scientists often toss the word algorithms, and that sounds fancy, but algorithms are simply the way that we solve problems.

Algorithms are just the list of steps that we use to solve any type of problem.

The rules and list of steps that apply to addition like remember to carry your 1s to the next column if the current column adds to 10 or above is an algorithm.

When you hear computations, computations are calculations that follow algorithms.

Because Computer Science dives into computations, we also think of problem solving.

“Can we solve this problem? How hard is this problem? How fast can we make the solution?”

Problem solving use computations!

The most important skill of computer science is problem solving.

Learning a programming language like Python is an excellent way to help you practice solving problems because programs are step-by-step instructions that you create in essence to solve your problems!

If algorithms are the ways or the list of steps that we use to solve problems, programming is about taking our algorithms that we have thought and planned and writing them into programming languages like Python.

The reason that we learn programming while learning Computer Science is because programming languages are languages that express computations and also solve problems for you.

Although we’ll be using Python as our language of choice in these lectures, the language is not important.

Understanding the fundamentals of programming and practicing problem solving in your own personal objectives and context is far more important.

Practice makes perfect.


Values, expressions, and statements

Assuming that you have Python already installed on your computer, you can save an empty file as a Python file by making sure that it has a .py extension.

Python has an IDE, integrated development environment, which serves as a program that can run a Python program. I’m using Python 3.6 in this book.

The first thing about Python that we’ll talk about are values. Values are letters or numbers that can be used in the language.

Every value has a type. Numbers like 1 and 2 have the type called: integers.

Words or sentences like “Hello world!” have the type called: strings.

Strings are enclosed in quotation marks.

The next thing that we’ll talk about are functions. Functions are fancy terms defining commands that do something in Python.

The most used function in Python is the: print function. The print function displays values on the screen.

To use print, you write, print and enclose a value inside a pair of parentheses.

You can run the program. What’s displayed is 4 and Hello world!:

You can also check the type of your value with the type function. Python has a bunch of these preconfigured functions like print() and type().

type(value) gives us the type of the value enclosed in the parentheses.

You can put functions within functions. We’ll put the type function inside the print function, so we can tell what type the 4 and “Hello world!” are.

What’s displayed is int, which is short for integer, and str, which is short for string because 4 is of type, integer, and “Hello world” is of type, string.


Now, let’s talk about variables. Variables give a name to our values. We can assign new variables with values. The variable name must be on the left side, and the values must be on the right side.

For example,

question is now the equivalent to the string, “How are you today?” because of our assignment. Likewise, x is the equivalent to 5.

The print and type functions work with variables, so we can use print and type on these variables.

What’s displayed is:

float is the type given when there is a decimal point dividing the integer and fractional part. 2 and a half has a decimal, so it’s a float type.

Variable names can use a combination of letters and numbers, and variable names are case sensitive.

When you use multiple word variable names, typically, you leave an underscore between each word like:

There are illegal characters that you cannot use in variable names like the $ symbol.

There are keywords in Python. You cannot give a variable the same name as a keyword.

For example,

There are twenty-nine keywords in Python:

You can still name variables that contain keywords, but they cannot be exactly the name of a keyword.


class is a keyword, but since it’s used inside a bigger word, the variable name is legal.

Next thing that we’ll talk about are statements. A statement is a fancy way of saying a line that executes in Python.

print(4) was a statement
x=5 was a statement

Next thing that we’ll talk about are expressions. Anything that evaluates something is called an expression.

1 + 1 is an expression.
We can print these expressions.

1 is an expression.

variables are expressions.
We can print all of those.

Next thing that we’ll talk about are operators. Operators are special symbols like addition and multiplication that perform a computation.

You can do simple math like 1 + 2.
3 * 4. The asterisk symbol is used for multiplication.
Two asterisk symbols are used for exponents. 2 ** 2.

Operators in Python follow the order of operations, which you may remember as parentheses takes priority, and then multiplication and division, and then addition and subtraction.

For instance, you can write (1 + 2) * 3, and the result would be 9 because of order of operations. 1 + 2 happens first, which equals to 3. Then, 3 is multiplied by 3 = 9.

You can use the addition operator on strings to combine strings together. For example,

The next thing we’ll talk about are comments.

When programs get more complicated, developers leave comments that are basically notes, so that you or future developers understand what you did.

Comments in Python are prefixed by the # (pound) symbol.

For example,

# (pound) symbol is used for single line comments.

For multi-line comments, where you need to include extra notes, you use a pair of triple quotation marks, one set to start the comment and one set to end the comment.

For example,


Video Demonstration