Python from beginner to intermediate.

Here's my take on python from beginner to intermediate.

PROGRAMMING

Paul Armstrong

7/12/202419 min read

Introduction

So you want to learn python? That's Awesome! Python is one of the most popular languages at the time of writing this and offers many advantages. Before we get started though I'll cover a bit of background information on the language for those interested. If you want to just jump into learning the language feel free to skip to here. Also do note I am not a teacher just someone sharing my knowledge. There may be more efficient ways to do things then the examples I give.

Downloads

To start with we'll need to download a couple things.

First if you don't already have it you'll need to download Python.

Next you'll need something to code in. You can of course always use your operating system's default text editor but I would recommend using Visual Studio Code. Visual studio highlights key word in your code and provides fill in options for you code.

If you installed VS Code then I recommend looking at the extensions section of the code editor and searching for python extensions to see if anything catches your fancy.

Terminology

  • Function: A function is a block of commands that can be reused later.

  • Class: In object oriented programming (OOP), a class defines the structure and initial values of an object.

  • Object:

  • Method: A function associated with a class.

  • Variable: A keyword that is then assigned a value (ex. x = 4)

  • Data Type: An attribute that tells a computer system how to interpret it's value.

Syntax & Semantics

The Syntax & Semantics of python is relatively unique since it uses an almost written English style. What I mean by that is that a lot of it's functions and methods, and even it's structure is almost sentence like. Using not as an example, other languages like Java assign not a symbol; in Java's case they use ! as the symbol. Python on the other hand, not is spelled out rather then assigned a symbol. This makes the language easier to understand for those who have not programmed before. This English style structure also allows for a bit more freedom when writing certain pieces of code. For example if not x in y could also be written as if x not in y and it would produce the same results. Python also has a uniqueness to it being an indentation language. Where most languages use indentation for readability python uses it to indicate a new block of code. A for loop for example has it's condition written something like for i in x: where the next line down would be indented to indicate it as part of the for loop. This is somewhat dangerous though, since with no brackets to indicate the start and end of the code block, you need to pay special attention to your indentation to insure that you are not writing in the wrong block.

Data Structures and Libraries

Getting Started

First thing to mention before we truly get started is naming conversions. While these are not enforced by any means you'll find a lot of people follow these conventions to help keep a standard for the language. I'll only cover file names, variable names and function names here. When creating a new Python file it is generally expected that every new word is capitalized and there are no spaces. So if I wanted to name a file "super cool file" it would look like SuperCoolFile.py. Variables and functions both follow the same naming convention, namely all lowercase with spaces denoted by underscores. So if I wanted to create a variable called "my name" it would look like my_name. For the full list of naming conventions check here.

Now to really get started we'll do everyone's favorite exercise "Hello World"!

I recommend that you create a python folder somewhere on your computer to store all your code. Even if you don't think it's worth keeping you never know when you'll need to go back over the basics again.

Now create a file called HelloWorld.py and open it in your code editor of choice.

Now type print("Hello World!") in the file. I'll explain the basics of this in one moment but first let's run it to see the output. To do this we'll need to open a console to run the command. If you're using VS Code you can go to View>Terminal. If not then it depends on your operating system. For windows go to your start menu and type either cmd for Command Prompt or PowerShell for PowerShell either should work. For Linux and Mac go to your application search and search for terminal.

Now that you have a terminal of some sort open you'll need to move into the folder that your program is stored in. To do this type cd "Path to file" replacing Path to file with the actual file path and then hit enter.

Once you're in the right folder you can type python HelloWorld.py to run the program. It should look something like the image below.

Nice your very first program all done! Good Job!

Now like I said I would here's the breakdown of how this code actually works. First print is a reserved word in python. It is a function that prints anything in the brackets to the right of it out to the screen (by default). The quotations around Hello World! define that it is a String data type. What this basically means is that the program reads it like a sentence rather then trying to find a value associated with that variable.

On the topic of variables let's next look at how we could do the same thing but using a variable. To start with we're going to remove the "Hello World!" in the brackets and replace it with hello. Your program should now look something like...

print(hello)

Next above the print statement we'll write hello = "Hello World!". Together it should look something like...

hello = "Hello World!"
print(hello)

Now when you type python HelloWorld.py into you console you should see the same thing. Do you understand why? It's ok if you don't you're just starting to learn after all. For those who are unsure or just plain don't get it let me explain. What we've done is told the code that we want to make hello a reserved word or variable with the value of "Hello World!". This means that when it gets to the print statement and doesn't see any quotations it looks for any variables with the name hello. Since we said that hello has a value of "Hello World!" it substitutes the variable with it value and prints it out to the screen. Now what happens reuse hello and give it a different value? Let give it a try by doing something like...

hello = "Hello World!"
print(hello)
hello = "Hello my name is Paul"
print(hello)

As you can see the output changed to match the latest String.

The last thing I'll mention before we move on is comments. Comments are bits of code that the computer skips over allowing you to leave notes both for yourself and for any others that may read your code later. You can start a single line comment by using #.

# This is a single line comment

To write a multiline comment you'll use 3 quotations at the start of the comment and 3 quotations at the end of the comment.

"""
This
is a
multiline
comment
"""

Now let's get the various operations that python supports out of the way. I won't cover them all since some of them don't get used that often but if you're interested in the full list I recommend checking out the W3Schools resource in resources at the bottle of this page. They have a section on python operators that is very well done. For now though let's start the basic math operators

Operators

Moving on let's talk about assignment operators. These are used to assign values to variables.

Next we'll look at comparison operators...

For now I'll leave it at that. If I use any new operators I'll do my best to explain about that then.

So they're different but the question now is why. Well to answer that we need to know the difference between a number and a String. A String as far as the program is concerned is just a line of text. Even when we put + or = or any other operator in a string it just reads it like text not something to be evaluated. A number on the other hand is something that the program will evaluate. For example in our last program we had x = 2 + 2. When the computer comes across this statement and sees that contains numbers and not Strings it evaluates the equation and then stores the answer in the variable x. This difference in data types is why we get 2 different answers. Now what would happen if we mixed the data types? Let's try adding another variable and print statement and see what happens.

x = 2+2
print(x)
y = "2+2"
print(y)
z = 2 + "2"
print(z)

Take a guess now and then try running the program again to see what happens. If you guessed that the computer would be very confused then congrats you were right! You should have seen something along the lines of...

Essentially Python sees 2 different data types that shouldn't usually interact and so it creates an error to let you know that something is wrong. Now let's talk about another data types that can be assigned to a variable. The Boolean data type. This is basically just a true of false variable but is the backbone to a lot of programs. It's very easy to assign a bool value in Python as you just type your variable name equals True of False like this...

var = True
var2 = False

The one thing to be careful of is that in Python the True and False needs to be capitalized like above. In some other languages it will be all lowercase. Now that we know what a Boolean is let's look at how they're used!

Let's start a new file now and call it variables.py now lets play around with some variables and figure out how they work. Starting small let's try writing the code...

x = "2"
print(x)

As you might imagine when we run the command python variables.py in the terminal it will output 2. But what if we removed the quotations? Give it a try! Assuming nothing went wrong it should still output 2 to the terminal. These are not truly the same however. With the quotes python will treat the 2 as a String without the quotes it gets treated like a number. Without any context I'm sure that difference must sound pretty small but let me tell you it makes a big difference in practice. Let's give it a try! try changing your program to look like this...

x = 2+2
print(x)
y = "2+2"
print(y)

Now before you run the program take a guess at what you think will happen. Will both print statements be the same or will they be different? Give it a try and let's find out. Assuming nothing went wrong you should have seen an output something like this...

Variables

As you should see this comparison returns a Boolean value telling us that yes 2 does in fact equal 2. Now what if we changed this slightly and put one of the 2s in quotations to make it a string?

print(2 == "2")

Take a guess and then feel free to run the program again. You should see a False this time. This is because like I talked about earlier although both side are 2, one is a String and the other is a number. What if we wanted to check if a number was bigger then another or maybe smaller? You could use the < or > operators. Let's try...

print(2 == "2")
print(2 > 3)
print(2 < 3)

Let's say that we want to compare 2 values. How would we go about doing this? Well one way is to use the == operator. Let's make a new file called Booleans.py and give this a try. Try comparing if 2 equals 2...

print(2 == 2)

Booleans

Neat right! Next let's check out a more practical use for Booleans.

If, Else and Elif

It's all well and good that we can print out comparisons but wouldn't it be good if they actually did something? Well that's where if statements can come into play. An if statement takes a bool as an input and given the value of that bool executes certain code. Take this next piece of code as an example...

# This if statement checks to see if 2 = 2
if 2 == 2:
print("2 is equal to 2")

print("Program complete!")

Now to break this down. If you're curious to see what the output is before the explanation feel free to copy this into your Booleans.py file and give it a run. Now to start with we have a comment on the top in green. Like I mentioned earlier the program will skip over this. Next is our if statement. As you can see it is just the keyword if followed by the condition that we want to check for. If our condition evaluates to true (which it does) it will run the print statement that is indented on the next line. It's important to note that the colon at the end of the statement tells the program where the condition stops. Also note the code you want to run if the condition is true needs to be indented by one space. That's how Python distinguishes it's code blocks apart. Finally the program prints "Program complete!". So our output should look something like this...

Ok but now that begs the question what happens when the condition is false. Let's change the 2 == 2 to a 2 > 2 and find out...

# This if statement checks to see if 2 = 2
if 2 > 2:
print("2 is equal to 2")

print("Program complete!")

Like you probably expected because our condition is now false so the indented code isn't executed. Interestingly enough your comparison doesn't have to be numbers either. Let's try using String as an example.

# This if statement checks to see if the strings are the same
if "String 1" == "String 2":
print("The strings are the same")

print("Program complete!")

As you can see since the 2 Strings don't match our condition is false meaning the print statement doesn't get executed. If we changed it so that both Strings said "String 1" our condition would be true and the print would be executed. Why don't you give that a try? Now what if we wanted something to happen only if our condition was false? We can use an else statement to do exactly that! Let's edit our program from above slightly to add an else.

# This if statement checks to see if the strings are the same
if "String 1" == "String 2":
print("The strings are the same")
else:
print("The strings are not the same")

print("Program complete!")

You can see now that we have an else statement because our condition is false it now prints the code in the else block. Try changing it so that the condition is true and check the output. If it's setup right you should see...

Lastly let's consider a situation where we have multiple conditions but we only want one to trigger. This is somewhat tricky because if you just put if statements one right after the other you might end up with multiple conditions that are all true. The answer to this problem is the elif statement or otherwise known as else if. This statement does exactly what we're looking for allowing us to add more conditions to the same if else block. Let me show you an example...
#define some variables
a = 3
b = 4

#Check to see if a + b = 5, 6 or 7 otherwise say you don't know
if a + b == 5:
print("The answer is 5!")
if a + b == 6:
print("The answer is 6!")
if a + b == 7:
print("The answer is 7!")
else:
print("I don't know the answer :(")

print("Program complete!")

To break this down I declared 2 variables a and b and gave them numerical values. I then set up a block that checked the value of a + b and printed out based on the answer. In this case the answer was 7. Try playing around with the code above. Change the values of a and b and see what answers you can get.

User Input

Let's start to make our examples more dynamic by using user input. User input is very easy in python as it just requires the use of the input function. Let's make a new file called Input.py. In Input.py we'll type this...

input("What is your name?")

Now before I give the explanation for this try running it. The program should wait for you to type something into the terminal. For example my output looks like...

As you can see the program prompts for an input using the text we provide in the brackets. Now since we didn't assign the input to a variable this doesn't do anything. Let's change our program so that the input is saved to a variable and the printed out to the terminal. Try doing this on your own if you can you should have all the needed skill. If you're not sure that's fine here's how I would do it...

name = input("What is your name? ")
print(name)

It's nothing too fancy but this allows us to feed our programs with input from the user making our programs more dynamic in nature. You might also notice that I added a space at the end. The function puts the input directly after the prompt finishes so for formatting reasons I like putting a space at the end. I'll touch more on this later but if you wanted to put the input on the next line down you could put a \n at the end like so...

name = input("What is your name?\n")
print(name)

Let me show you the difference. The first image is the prompt with a space at the end and the second image is with \n at the end...

Without getting to far into it \n in a String is considered to be a newline character. The last thing I will mention is that the input function always inputs a String. So if you were to type 52 into the input it would be "52" and not 52 in the variable. If you wanted it to be a number instead you could do what is called casting. This essentially converts one data type to another as long as there is an equivalent. So you couldn't turn Paul into a number for example. To cast your input you can use one of the data type functions int(), float() or str(). int() turns the input into a regular number, float() turns the input into a floating point number and str() turns it into a String. str() isn't as useful here since the input is already a String

Practice

Now time to put what you've learned into practice. Let's make a new file called Practice1.py. Now I want you to try and create a program that asks the user to input a number. The program should check to see if the number is smaller than 0, between 0 and 10, between 10 and 20, between 20 and 30, between 30 and 40, between 40 and 50, between 50 and 60, between 60 and 70, between 70 and 80, between 80 and 90, between 90 and 100, or finally greater than 100. Depending on where the number falls the program should print out an answer. (ex. User input is 57 program output should be "The number is between 50 and 60.") Give it a try and then come compare with my answer!

Answer:
number = int(input("Please input a number "))

if number < 0:
print("You entered a number less than 0")
elif 0 < number < 10:
print("Your number is between 0 and 10")
elif 10 < number < 20:
print("Your number is between 10 and 20")
elif 20 < number < 30:
print("Your number is between 20 and 30")
elif 30 < number < 40:
print("Your number is between 30 and 40")
elif 40 < number < 50:
print("Your number is between 40 and 50")
elif 50 < number < 60:
print("Your number is between 50 and 60")
elif 60 < number < 70:
print("Your number is between 60 and 70")
elif 70 < number < 80:
print("Your number is between 70 and 80")
elif 80 < number < 90:
print("Your number is between 80 and 90")
elif 90 < number < 100:
print("Your number is between 90 and 100")
elif 100 < number:
print("Your number is greater than 100")

Did you manage to do it? Don't worry if you didn't. Try playing around with the answer until you think you understand and then give it another try.

Lists

Our next topic is a data type used to store multiple elements namely a List. A List is a collection of elements given an order. That is to say that if I add to a list, the latest addition will always be put at the end. You can however overwrite existing elements to change the order around. List are defined using the square brackets []. Let's start by looking at how a list is created...

# This creates a list with predefined elements
list1 = ["Apple", 2, 3.75]
print(list1)

# This creates an empty list that I then add elements to later
list2 = []
list2.append("Apple")
list2.append(2)
list2.append(3.75)
print(list2)

As you can see I have created a list in 2 methods. The first method creates a list with 3 elements right of the bat. The second method creates an empty List and then appends the data to the end of the list. Both of these methods will produce the same result in the output.

Notice that the elements don't need to be of the same type. Also note that the elements of the List can be of any type, meaning you can even put a List in a List. Lists also allow for duplicate elements so if you wanted to have multiple 2s in your List you absolutely can. To access an element of a list you type the variables name followed by square brackets with the index of the element inside the brackets. The list is ordered by index starting at 0 and increasing from there. For example if I wanted to access "Apple" from the list above I would type list1[0]. To find out the length of a list you can use the len() function. For example...

print(len(list2))

Would print out 3 since there are 3 elements in the list. An interesting thing happens when you input a negative index though. Can you guess what might happen? If you guessed that it starts from the end of the List you would be correct. So for example index 0 = "Apple" and index -1 = 3.75. It's very helpful when you have a long List or a List whose length you don't know and you need to access the end of the List. To remove an element from a list you can use the pop() method. For example list1.pop(0) removes the first element of a list.

Dictionaries

In the same vein as Lists we also have Dictionaries or Dicts. Dictionaries are similar to Lists in that they store multiple elements of any kind but those elements are accessed in a different manner. Unlike a List which is assigned an index a Dict uses what is called a key. A key can be a float, an integer or even a string. Because of the nature of these keys though it means that Dicts cannot have duplicate keys. Trying to assign a value to a key that already exists simply overwrites the old value. Let's look at how we might construct a Dict...

dict1 = {"Fruit": "Apple", 0: 2, 5.01: 4.5}
print(dict1)

dict2 = {}
dict2["Fruit"] = "Apple"
dict2[0] = 2
dict2[5.01] = 4.5
print(dict2)

dict3 = {}
dict3.update({"Fruit": "Apple"})
dict3.update({0: 2})
dict3.update({5.01: 4.5})
print(dict3)

As you can see similar to Lists we have multiple ways of creating Dicts. Also similarly to Lists all 3 of these produce the same result...

This is where things start to deviate however. Since a Dict is made of a key, value pair we can't just use a index and expect to get a result. We need to provide the Dict with a valid key for it to search for a value for. For example if I wanted to get "Apple" I would use the notation dict1["Fruit"]. Notice that we are still using the square brackets but now we put the "Key" inside. To find the length of a Dict we can still use the len() function just the same as with a List. If you ever need a list of either the keys in a Dict or the values in a Dict you can use the respective keys() and values() methods. These methods are called like so...

print(dict3.values())
print(dict3.keys())

They return the response of...

Finally to remove an item from a Dict we use the pop() method the same as a List. The difference is that instead of providing a index we give the pop() method they key we want to remove. So to remove the "Apple" entry I would use dict3.pop("Fruit").

Loops

Finally to remove an item from a Dict we use the pop() method the same as a List. The difference is that instead of providing a index we give the pop() method they key we want to remove. So to remove the "Apple" entry I would use dict3.pop("Fruit").

Functions

Classes & Objects

More to come