Let’s Learn Programming in Python

A Complete Introduction Course to Python.

Introduction

I, like many others in my Bachelor’s courses for programming started using Python in our first year. For me it wasn’t the first time programming as I’ve had a previous education in IT already, but after learning Python I understand why most courses use it as a first venture into programming, and that’s exactly what I will teach you.

This article will be for all the first year’s students and those who want to get started with programming. Because starting can be a very scary task I will keep it simple, but once you get the basics down in one language you can learn other programming languages a lot easier. Now let’s start by installing Python.

Installing Python (3) isn’t hard at all, just follow the instruction on Python’s official website. It was just an .exe I had to install in my case.

Let’s run cmd on our machine and enter py --version in it to check if the installation was succesful. (This might differ on Mac or Linux)

Now that Python is installed and ready we will create our first Python application. A “Hello, world!” application, as is tradition in the wonderful world of information technology.

Hello World!

You can run simple Python programs directly into your ‘console’, or ‘terminal’. The most simple program you can run is a Hello-world application. This is a program that outputs “Hello, world!” in the console.

The syntax for writing to the console, or ‘printing’ is:

Where you would write your text between the brackets () . Text in Python, and in most other programming languages must be written between quotes "" . This means that our first program will look like this:

But how do we run it? Well, since it is our very first program, we will run it in our terminal. Open the terminal and type in python and press enter. This will open the Python interpreter.

Next you can enter the print statement and press enter. You will see that our input, our string between quotes is printed in the console.

And now, you have officially written your first program and are a Python programmer.

But you have most likely seen programs that are running from files, and that are written in files. So let’s take a look at how that’s done.

IDEs

An IDE is a program in which you develop code. It offers lots of useful tools such as code completion, type checking, error checking and much more. You can forget about these for now, and writing code in Notepad also works, but that is not the best way to go, so I will list a few free IDEs that you can use that support Python.

I will use Visual Studio Code in this article. It is made by Microsoft and offers a ton of plugins for all sorts of programming languages. PyCharm is also very good since it offers more functionalities specifically for Python.

Running from a file

Install the IDE of your choice and install any optional plugins for Python if you’d like.

Next up, create a folder to program in and make a file called prog.py . The prog part can be anything, as long as it’s a .py file. Now open the file in your IDE and write the code we wrote before in it.

If you save the file and open the terminal in the same folder you can run the py <filename>command to run the new Python file.

In Visual Studio Code you can click Terminal in the top bar, and click New terminal to open a new terminal in the correct directory.

Variables

A variable is a value that can be variable. It can be anything you want in theory. A number, a text string, a list of number, everything. And they are a very essential part of programming. Can you imagine a variable that Medium uses? Usernames, images, whole articles, they can all be variables.

A variable in Python is declared like this: <variable-name> = <value> . This means that we can declare a name, name = "John" , or a number age = 17 , or anything else in a very easy way. But how do we use them? Let’s start with the name.

This code will print whatever is the value of the variable name . In this case “John”. But what if we want to politely greet John? We need to concatenate the strings. This is done by using the + sign. We concatenate string like so.

So then our code will look like this if we add “Hello” in front.

Keep in mind that name is a variable, and therefore doesn’t need any quotes surrounding it. If it was not a variable it would be print("Hello" + "John") .

Basic Types

Variables can have a whole range of types. The most important for now are the string , number and boolean types. We’ve already used the string type, which is the text between quotes.

The number type, like you’d expect is a number. This can be any number, positive and negative, and with floating point values. Working with numbers is very easy. We’ve already used the + sign by adding string to each other, but if we use it with numbers it will add them together and return the outcome.

Next up we have the boolean type. This can be either True or False in Python. Note the capitalisation. A boolean can also be a statement. Something like x > y which will return True if x is more than y . Try it out!

Inputs

While greeting the same person over and over again is very fun to do, and I remember when I started programming I was stoked when I was first using variables, we need to add some sort of input.

Thankfully the input function in Python is easy and very straightforward to use. The function prompts the user to enter a value and returns it as a variable if used like this:

A function usually has trailing brackets. Inbetween these brackets you can put parameters which are variables the function can use. In the case of input it accepts a string parameter which it will print before asking for input.

I entered “John” by typing on my keyboard. If you understand this you might be better than a few of the first-year students I had to work with, and it might be time for you to take a minute to breathe, walk and grab some coffee since this is just the beginning.

We have now explored very basic input and output in our Python program using the input and print functions.

Conditional code

The next step most courses will learn you is how to write conditional code. This means that we have any conditition and change the flow of our program accordingly. Most (if not all) programming languages do this using if , else and if else statements.

The basic syntax in Python is very simple.

If you don’t need a else for some reason you can simply write the if . pass Means that the code can continue, Python doesn’t accept empty if bodies, so we use pass as an empty statement.

Also note the identation. The bodies of the if and else are written with a <tab> before them. This matters in Python and the code will not run otherwise. It also increases readability when working with multiple if-statements nested in each other.

Let’s try and add an if statement that checks if a number is more than zero.

Run this code and try to understand what is happening. What will happen if you set num to a negative value? num = -3 for example. Or if it’s set to 0 or maybe to a string or boolean value.

But for some, 0 isn’t positive nor negative, so we want to add the option for 0 being “Zero”. This can be done using another if or using a so called elif in Python. elif is Python’s way of saying else if . This is an additional if that you can chain together to create more complex programs. Let’s try and add it to our number checker.

We have our first check, Checking if num is equal to zero. If that check returns False , it will continue. And if the number isn’t greater than 0 as well, it will continue to the last if. So the order in which you will write these matters.

You can also check the length of a string in characters within if ‘s, and I’ll show that next. This uses a built-in function in the string type in Python. The __len__() function.

Note that, like print and input , the __len__ function also has trailing parenthesis. This is required to call a function. Leaving the parenthesis out will return the function itself, not the result the function gives. You can try printing it and it will return a memory address to the function body, but that isn’t very useful for us now.

Exercise 1

Try and create an if statement that checks the length of a variable that is a string type. It has to check on three different lengths. More than 0, less than 5 and more than 5. Remember to check the order of the checks and test what happens if they aren’t in the correct order.

Defining Functions

Functions are an essential part of programming. So far we have only used build-in functions, but we can also create our own. We define these using the def keyword in Python. Let’s make a function that can greet the user if he gives his name.

You can also define functions that do not take any parameters. This function takes the parameter name and we use it to greet the user using his name. Try and create a few functions of your own that print various inputs, sums or with multiple parameters. Note the identation we use.

You can expand on this and create more complex calculations. Try playing with numbers and the * , / , + and - signs to create complex calculations.

Return

The return keyword is very important in functions. Instead of printing it it will return the value to whatever called it. Like we did using the __len__() function which returned the length of the string as a value.

This is very useful for using functions. You can use the value as a parameter by calling the function if you want.

This will calculate sum(3, 3) first, and then it will calculate the outer function. The possibilities are endless. Try and understand how this works, it can be hard but is very important to understand, so try it yourself.

We also use a comment here. The line that is prefixed with a # is a comment. Python will not do anything with a commented line and they can be used to increase readability which is good practice.

Loops

Looping is also a very important thing in programming. Keep doing X while condition Y is True, we have all seen it before. There are multiple types of loops. A for loop and a while loop. You can translate these to plain english if you’d like. For every item in this object, do X. Or while condition X is True, do Y.

A while-loop is always a course favorite to learn first, and I cannot really disagree. So let’s see the basic syntax.

In plain English: “While num is less than or equal to 10, print the number and increase the number by one”. If the condition will never be False the loop will continue to run until you close the application or set the condition to False somehow. This can be useful for certain programs, so let’s take a look.

This loop will always go on and on and on until the user enters “quit”. Try and run this code. Note the identation which gets deeper, and try to understand what happens. Our code is getting more complex and I hope you’re still following along nicely.

The for-loop is used for iterating over certain objects. These can be lists, strings, ranges or other values. We will try it out using the range(x, y) function in Python. It will create a list with values from the first parameter to the second. We can use the for-loop to print all the values in the range.

This will print all numbers starting at 1 to 11, excluding 11. To it will print 1 through 10. The syntax is similar to foreach loops in other programming languages.

Lists

A range is a type of list . Also called an array . A list can hold a series of values that are declared between square brackets and separated with comma’s. And Like with the range, we can iterate over them using the for loop.

Here we declare a list of items. In this case fruits. In the for loop we iterate over them and print each one of them. Try it out yourself! Try and change the strings to numbers, or try to mix strings and numbers in the list. It is all possible.

Calling a specific item from a list is also possible without iterating over them.

Calling these list-items is done with square brackets with a value inbetween. This value is the index of the item you want to retrieve and it starts at 0. so 0 is the first item, 1 is the second item and so on. This value inside the quare brackets can also be a variable like in a while-loop.

You can change specific items using this syntax as well. Try it yourself.

Exercise 2

Try and create a list with some values. And iterate over this list using a while-loop. Then you can see how to iterate over something without a for-loop.

Tip: use len(<your list>). This is a length function for lists.

Dictionaries

Dictionaries are one of the more complex data types in Python. They consists of key-value pairs. The key, or name of these pairs must be written between quotes. These keys need to be unique as well.

A car cannot have two model names, or two years.

Calling the values from keys is a very similar to getting a value from a list. By using the square brackets with the name of the key we can retrieve the value from that dictionary with that key.

A key can contain any value. A string, a number, a list ,another dictionary or a list of dictonaries. This is very useful for creating complex data structures. These inner dictionary values can also be retrieved. Let’s see how it works.

We define a dict person with a key for children . The children key contains a list of dictionaries. Both dictionaries are for a child. With this you can create complex family trees if you’d want to.

See how we retrieve the value of the first child? We chain the square brackets with the keys after each other. And since children is a list we need to retrieve the first value using [0] .

Exercise 3

Create a function that, when called retrieves a specific list item inside a dictionary. The function should have one parameter, the index of the list-item it should return. If the number exceeds the amount of available list items it should return an error in the form of a string.

Lambda Functions

Functions can have several parameters as we’ve seen so far. We have made function that use numbers or strings as parameters. Lists and dictionaries are also possible, but what about functions?

Functions that return a function or retrieve one as a parameter are called higher-order functions. You can create these to, for example, create modular functions that share functionality.

In Python, functions to return will be anonymous. They don’t have a name (yet). Another word for anonymous functions is lambda functions. And in Python we use the lambda keyword to define these.

Let’s look at the following code.

We define one function func that returns a lambda function. This lambda function takes one parameter a and multiplies it by n .

We get n as a parameter from func , so the function we return is a * 2 in the case of the doubler and a * 4 in for the quadrupler .

This means that we can create any multiplication function using the func function. And we can also use the lambda function as a parameter in a regular function.

This might seem very weird to use, and I agree, it is weird at first. However, programming with lambda functions can be useful when working with recursion or filtering and mapping lists. Let’s filter a list using a lambda to get the point of lambda’s across a bit better.

This code is a bit messy since filtering in Python is a bit hard to do as it returns a filter-object which you have to convert to a list again, but oh well.

We create a lambda which uses one parameter. This parameter is filled automatically and applied to every list-item by the filter() function. The lambda returns either True or False depending on if the list item is more than 6.

While the concept of lambda functions might be a bit blurry still, we will get on to the next topic. Just try and let it sink in and try to play around with it to understand this topic better.

Classes

Almost everything in Python is an object, with its properties and methods. A Class is an object constructor, or a “blueprint” for creating objects.

We can create a class for Persons to create person objects from. Or we can use the most used example: Books in a library. A class is made with the class keyword.

We define two books here, but both have the same values. We create a book object by calling the object as a function. We can retrieve values by using the dot-notation like we do in the print function.

A class is not very useful in most cases without a constructor. A constructor is a function that initializes a object with optional values you can set during this construction. A constructor can have parameters like regular functions to create more dynamic objects from a class.

The __init__() function takes at least one parameter. self . The self parameter refers to the new object itself and doesn’t need to be given when calling the constructor when creating new objects. As you can see, we still call Book(params) with the two parameters that you can refer to in the __init__ function where we set self.title to the parameter _title , etcetera.

A class can contain any type of variable like you would expect, and some can be present in the constructor while some may already have a static value. You can change these values at runtime if you would like to.

Here we set the value of title for book1 to a new title after the object has been created. This allows for some intricate programming.

Exercise 4

Create an empty list of books. Create a function that adds a book to the list with given parameters. The book has to be an object made from a class using the __init__ function to specify the values of the book.

You can add new values into a list using list.append(<obj>) where <obj> is the value to add to the list.

Create a function outside of the class that prints all the titles of the books using a loop of your choice. The function should recieve the books using a parameter.

Conclusion

This article is a course for the basics of programming in Python. This article is made for those with no experience yet and I really hope I made a difference in your studies, either for school or for hobby projects.

W3Schools has a lot of easy to use documentation about Python on which you can expand your knowledge.

Have a great time programming, make something great, and have a wonderful day. Thank you for reading.

Student at Hogeschool Rotterdam 👨🏻‍🎓. I write about programming or one of my many hobbies. Follow me on Twitter @MVissers4

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store