Your First Python Tutorial

Except for the formal, boring stuff

Yağız Işkırık
Interesthings
Published in
18 min readJan 2, 2022

--

You saw some cool stuff that you can do with programming, maybe you wanted to make some games to your taste, you have an incredible idea that can change the world, and the only thing you need is to learn how to program. Sounds easy, right? Actually, if you don’t fix yourself to the step-by-step guides that you found online, learning itself is easy. You need to see the programming language you are learning as a tool instead of a purpose. And every tool has its own purpose. You can hammer a nail with a wrench, but the hammer would be an easier tool for your purposes.

The first thing you need to know is, what you can and can’t do with that “tool”. Almost every programming language is capable of doing certain stuff in a basic way. In our case, Python is a very versatile programming language that you can do almost everything you can imagine from data analysis to automation in every sort, despite some drawbacks that are not “well known” to beginners. I would like to tell you the dark sides of Python first:

  • It is significantly slower compared to other C languages and even JavaScript.
  • Python is more like a back-end language rather than a front-end. You can create a basic user interface (UI) with it, but it won’t be as powerful and good-looking as an interface built with HTML/CSS/JavaScript triplet.
  • You will be restricted to writing your program for PC and Mac only. You can write mobile applications with Python but, it will be much faster and painless to learn another language from scratch to write mobile apps.
  • Python won’t be efficient on your memory usage as well. You can run a full Kerbal Space Program which is written in C# with intense calculations per second while you are playing, which will be equivalent to a data analysis algorithm written with Python.

In the beginning stage, you will not feel these drawbacks intensely. The more you improve yourself and try bigger projects, the more you feel the bulkiness of Python.

Despite these drawbacks, numerous things make Python a very solid programming language. There are more good features than bad ones. The good ways are briefly:

  • It is simple, more forgiving with your errors.
  • Requires less code to do the same objective compared to the other languages.
  • Python has countless libraries that you can use for free. This solves the problems with Python. If you want to make faster calculations, you can use libraries like NumPy which is working on C. If you want to make a good looking interface, you can use some libraries to use your HTML/CSS/JavaScript knowledge and some extensions like Django or Flask to make that happen.

The best feature of Python is the libraries that you can use. If you want to do some specific task that you can’t accomplish with standard libraries you have, there is probably a library for that. I will mention what are they and how you can use them in my articles later.

disclaimer; This will be a concentrated first lesson and I would like to remind you that I am trying to create a base for advanced lessons in a short time. Because the more advanced it gets, the more fun you have from it. I will emphasise it in a couple of areas, but please repeat these exercises to understand them.

downloading and installing.

The first thing you need to do is to install Python on your computer. If you are using Mac or Linux or you have already installed it, you can access it already and skip this step. For Windows users, stick with me. I started a new virtual machine to help you better.

  1. First, go to the Python website and go to Downloads. Or click this link, if you feel lazy.
Python Downloads page
Python Downloads page
  1. Install the latest version and wait for the download to finish. After it finishes, open it up. This screen will welcome you:
  1. Make sure to check the Add Python 3.x to PATH option and click “Install Now”. After installation finishes, click on the Disable path length limit option to access Python from cmd system-wide.
  1. Then do the Windows + R key combination to open the Run panel, and type cmd. Hit enter.
  1. Type python and hit enter. If you are seeing a screen similar to this, you have successfully installed Python for Windows.

This is an interactive shell for Python. You can test your ideas and experiment with them here. If you would like to access it, you can start from step 4 to open it up every time you need it.

ide, optional.

This step is optional but highly recommended. You can download and set up VSCode for a better experience. It gives you easier control over the programming language and execution. Just to quickly explain the setup:

  1. Go to the VSCode Downloads link.
  2. Download the latest version according to your system.
  3. Install it and open it.

You can also customise it with lots of extensions. You can check out my VSCode article for more information from here.

usage.

First of all, you can use Python interactively or you can create a file for your code and execute it from there. For short tests and confirmations whether the logic I created works, I generally use an interactive shell otherwise, I code in a file since it is a lot easier to correct your mistakes. Without further ado, let’s get started.

creating a file.

For Windows users, make sure you enabled the file extensions. If you don’t know how to do it, here is a link for you. Then right-click anywhere you want, create a new txt file, rename it as for example test.py. This way, it will be ready to work.

Mac and Linux users are pretty much fall into the same category. There are numerous ways to do that, but as an old Linux and new Mac user, I fire up the terminal, cd into the directory I want, type touch test.py and voila!

You can now right-click on the file and edit it.

For VSCode users, just open a folder, right-click on Explorer and create a new file with the .py extension.

executing files and interactive shell.

For Windows users, if you already installed the Python version 3.x, the command python will refer to Python.

For Mac and Linux users, the command python3 will refer to Python 3.x. Why is that important? Because regular python expression on Linux and Mac will refer to Python 2.x and Python 2 is depreciated.

If you add the file name you created with the extension after the python command, the file you created will be executed. i.e. python3 test.py or python test.py.

For VSCode users, just press the Play button at the top-right corner of the screen.

variables.

You can create and change any variable you like in any programming language. Even though generating a variable name is sometimes the worst thing you can do, variables are one of the main structures of programming.

You can create one in Python via ‘the variable name equals to the variable value’. For example, let’s say we want to set a variable named “age” equal to 25. It is age = 25 . But be aware of the lack of quotation marks on 25, otherwise, it makes 25 a “String”.

variable types.

Since we already mentioned the “String” type, we should also mention the other types of variables. There are different types of variables in Python that you can use for different purposes.

int.

Integer (or Int for short) is the whole number that you can use without decimal numbers (i.e. 7). They are generally useful for counting and indexing.

age = 25

float.

Floats (or floating-point numbers) are numbers with decimal points (i.e. 3.14159265359). It is advisable to use them for dividing and storing the value or complex results (for example 15/7).

pi = 3.14159265359

”string”.

Strings are text values that come in handy when storing variables like names (i.e. “Bob”).

name = "Bob"

bool.

Booleans are “True” or “False” values which are defined as capital “T“ and “F” at the beginning of the word. We will see how they are becoming handy a few headlines later.

isLookingGood = True

maths.

We can do math with Python and we need to do it. Basic +, -, *, / signs work just fine when you define a variable. Also, I need to mention that when you redefine your variable, the old value is discarded unless you use that variable again. i.e. age = age + 1, age is now 26, happy birthday!

comparisons.

We can compare two variables using a few comparators. Note that all the comparisons return a boolean value. I use their return values in parentheses in order to show you their values, otherwise they are used like for example this: 1 == 2 (False) is used as 1 == 2.

==.

We can check if two variables are equal to each other with the == comparator. Notice that there are two equal signs since one equal sign defines a variable already. 1 == 2 returns a False value and 2 == 2 returns a True value.

!=.

If we want to check two variables are not equal to each other, we use != comparator. 1 != 2 returns False where 1 != 1 returns True.

>=.

Checking one value is greater or equal than the other, we use >=. 1 >= 1 and 2 >= 1 returns True while 1 >= 2 returns False.

<=.

In the same manner, we do the exact opposite with “less than or equal to” comparator. 1 <= 2 and 2 <= 2 returns True where 2 <= 1 return False.

<, >.

Greater or less than operators are to check if on variable less than or greater than the other. 1 < 2 and 2 > 1 returns True while 2 < 1 and 1 > 1 returns False.

not.

If we want to get the reversed value of a boolean or comparison, we can use not comparator. not 1 == 2 returns True and not 2 > 1 returns False.

and.

And comparator returns True when both of the comparisons returns True. Even one of the comparisons returns False, and comparator also returns False. 1 == 1 (True) and 2 > 1 (True) returns True where 1 != 1 (False) and 1 < 2 (True) and 1 > 2 (False) and 2 < 1 (False) returns False.

or.

Or comparator returns True if there are any True values in comparison, otherwise returns False. 1 != 1 (False) or 1 == 1 (True) and 1 == 1 or 1 == 1 (True) returns True while only 1 == 2 (False) or 1 != 1 (False) returns False.

aren’t they boring?

Yes. Obviously, you have to start from somewhere, I didn’t even include basic fundamentals like tuples, lists, dictionaries, arrays. But we will come to them step-by-step when needed. These are (in my opinion and way of teaching) the bare minimums of Python. Now let’s use them in a “beginner-friendly” project. Buckle up, because the information will flow after this point.

baby steps.

I would like to start by giving you the most important rule of programming: WritingHello World.

general culture (tldr); The famous ‘Hello World’ story goes back to 1972 when Brian Kernighan used the phrase ‘hi’ to test if the program was working in his book. From that time, it became a symbol of new programmers to welcome them into the programming (and also test the compiler whether is working).

To do that, we need to use a “function”. There are some pre-defined functions in Python, we will learn them as we need. In this article, we will touch only two of them: input() and print(). Depending on the way the function is defined, a function can have some input (in parentheses). We call the functions by the function name followed by the parentheses.

print() function writes “strings” onto the terminal screen. It takes only one parameter and this parameter can be a string. The way it works is as follows:

print("Hello World!")

This writes “Hello World!” to the terminal screen. You can change the string value to print different values. For example, you can create a string variable and use this variable as a parameter to the print() function. This language may sound like Greek to you at first, but let me demonstrate it for you.

textToPrint = "Hello World!"
print(textToPrint)

This outputs the same result as before. But we defined a string variable and used that instead. To make things more interesting, you can get user input in the terminal and print that in the console. input() function can take one optional argument (string), which shows the user a message before entry.

textToPrint = input("Your name: ")
print("Hello " + textToPrint)

This program takes the user input and says hello to them. You can test all of them by rather using an interactive shell, or writing them in a “.py” file and executing them. Have fun testing and combining these all together!

problem solving.

I thought a lot about not repeating the same examples on the internet over and over again, so I didn’t check the internet to keep my creativity at the maximum. I would like to create a problem first and show you how it is solved, then give you homework (metaphorical, not literal) to exercise a little. In real-life examples, I use programming and coding to my advantage to solve real-life problems, just like these arbitrary ones. As we encounter new problems, I will show you more advanced things that you can use in Python.

problem: Get the user’s name, if it is more than 5 characters, print it out 5 times. Else, print it out 3 times.

To check if a variable satisfies a condition we use the if-elif-else statement. It is easy to construct and very powerful to use. Let’s give a quick example.

number = 5

if number > 3:
print("It is more then 3")
else:
print("It is less then 3")

As you can see, we are checking if the number is more than 3. It is easy to understand, but we need to be careful about a couple of rules. First, if statement needs to have a comparison and needs to and with a colon “:”. And after the definition of if statement, the integrity of if statement must be one tab in. If we combine it with elif and else, they must be at the same level with the corresponding if.

Elif statement is the continuous check when the first if statement is not satisfying the condition. You can nest many elif statements after the first if. If there are no cases that satisfy any of the if or elif statements, Python executes the else statement. Note that there could be one if and else statement, and you are not obliged to use an else statement after the if statement if you don’t need to. An example for the correct approach would be:

score = 100

if score == 100:
print("You got an A+")
elif score >= 90:
print("You got an A")
elif score >= 80:
print("You got an B")
elif score >= 70:
print("You got an C")
elif score >= 60:
print("You got an D")
elif score >= 50:
print("You got an E")
else:
print("You failed")

If you noticed that we use the comparators we learned before in action. They are not that hard, aren’t they?

By using this knowledge, we can create a solution to our first problem.

userName = input("Your name: ")

First, we get the user’s name.

if len(userName) > 5:

Then we are checking if the length of the user’s name with the len() function. As you can see, this function gets a variable and returns the length of it.

print(userName)
print(userName)
print(userName)
print(userName)
print(userName)

And we print it out 5 times.

else:
print(userName)
print(userName)
print(userName)

If the condition is not met, and the user’s name is less than 5 characters, we print out the name only three times. To sum things up, here is the whole code:

userName = input("Your name: ")

if len(userName) > 5:
print(userName)
print(userName)
print(userName)
print(userName)
print(userName)
else:
print(userName)
print(userName)
print(userName)

improving the logic with loops.

We have printed out the user’s name only 5 times or 3 times, but what if we were to do this step more than thousands of times? Then loops come to help. There are only 2 loops you need to know to make your life easier, and it really depends on the situation and your personal preference which one you use on a specific example.

while loop.

While loop is an uncertain loop, which means most of the time it depends on a situation where you activate or deactivate it manually, or conditionally. It is easy to construct, but for all the loops you need to remember one thing: if a program doesn’t exit from the loop, it loops infinitely and freezes. Let’s give a quick example:

number = 0

while number < 10:
print(number)
number = number + 1

As you can see, we defined a number and increased it inside the loop. number = number + 1 argument will add “1” to the old “number” value, and define the same “number” variable increased by one. If we didn’t write the number = number + 1 there, it would go to an infinite loop, hence never ends.

quick life-saver tip; You can use number += 1 instead of number = number + 1.

We defined the “limits” of the loop this time, but imagine if we are expecting a response and don’t know when we get it. Arbitrary example:

while itIsNight:
sleep()

We can use the ‘while’ loop to make our previous example even shorter, if you want to do it yourself, you can do it right now. Otherwise, there is the code on how you do it.

userName = input("Your name: ")
index = 0

if len(userName) > 5:
while index < 5:
print(userName)
index += 1
else:
while index < 3:
print(userName)
index += 1

There are more than one ways to do the same thing, but to make it simple, this example shows that we can simplify our code.

for loop.

For loop is most commonly used when we know exactly when our loop will end. Commonly used with range() function, which basically defines a range between definite numbers (for example range(3) returns [0, 1, 2]). You can define a starting number and interval with range(startingNumber, endingNumber, interval), but to make this article simple, I will show you the single input version only. We use the for loop like this:

for thing in things:
show(thing)

More realistically, we combine it with the range() function to loop through a range like this:

for i in range(20):
print(i)

This returns the numbers from 0 to 19 (0, 1, 2, …, 18, 19). Notice that “i” starts from zero and ends before 20. Also, we used the “i” in both defining and inside the function. This function looks inside the return of range(20), assign the first value to “i”, runs the code inside, then continues with the next value, assign it to “i”, so on and so forth.

general culture; “i” is short for index, and it is an unwritten rule of programming to use the variables “i, j, k, l” in a loop.

We can use the for loop to make our previous example even shorter, with range() function, let’s see how its done:

userName = input("Your name: ")
numberToPrint = 0

if len(userName) > 5:
numberToPrint = 5
else:
numberToPrint = 3

for _ in range(numberToPrint):
print(userName)

Notice that we didn’t use the “i” variable, and instead used “_”. This is also an unwritten rule of programming, we use “_” to discard the value we get. Because we only need to print our text in a certain amount and don’t need the index we are on.

So far, (I hope) you’ve learned the basics of variables, loops, if-elif-else statement and some tips and tricks along the way. I know I bombarded you with lots of new information, but you will get better by practising it. I highly recommend doing the exercises again and again until you become fluent in them. You can come up with your own examples, I encourage you to try them as well. I could show you more simple approaches, but everyone already teaches them online, I would rather prefer to show much better examples that actually makes sense. Without basic knowledge, examples have to be nonsense. But the further we get into the learning, the more fun and useful exercises we will have. And you can use some of them even on a daily basis.

advanced example.

This one comes for Harry Potter fans, although I am not a complete fan, I (almost) watched the entire series.

problem; Simulate the Dumbledore sending 5000 mails and if that didn’t work, send Hagrid.

To visualise the problem even better, I would like to give how many times we sent mail. We will use booleans, integers loops if-else statements and string concentration in this example. And I hope everything will make more sense at the end of this example. If you like to give yourself a chance, try it out and use the #interesthingprogram hashtag to share it if you want. I will be on Instagram, Twitter and waiting for your amazing work!

First things first, we can define whether Harry is notified as a variable. We can do that by defining a variable named “isHarryNotified” to False:

isHarryNotified = False

Then we would like to store how many copies we sent to Harry in another variable. I would like to call it copiesSent.

copiesSent = 0

After that we would like to send 5000 mails, check if Harry notified about the invitation. We can obviously copy-paste 5000 if statements to do this, but since we already learned about the loops, we can do that in a much more simple manner. Do you remember I mentioned we use while loops to loop until an uncertain condition has been satisfied? This is a perfect example to do it:

while not isHarryNotified:

Notice that we use the not word to indicate that we will loop through until isHarryNotified becomes True as I showed you before. When we start our loop, it starts with a “True” value in it. Also, we would like to check if it has been 5000 mails, we can integrate it with the and functionality we learned.

while not isHarryNotified and copiesSent < 5000:

Then we send imaginary mails by increasing the number of values of the copiesSent variable by one.

copiesSent += 1

I used the short version of copiesSent = copiesSent + 1 as you can see above. If the copiesSent variable reaches 5000 or Harry notifies about the situation, end the loop. But, we haven’t sent the Hagrid yet. To do that, after the loop we check if Harry has been notified yet:

if isHarryNotified == False:
print("Hagrid sent.")

We could use the not comparator as well, but I wanted to show you that there are numerous ways to write the same code in a different approach. If you like to do it with a not comparator, you can do it as well. Our code currently looks like this:

isHarryNotified = False
copiesSent = 0

while not isHarryNotified and copiesSent < 5000:
copiesSent += 1

if isHarryNotified == False:
print("Hagrid sent.")

Notice that the isHarryNotified variable didn’t change at all, and it is not necessary for our code. But imagine that there is another function that checks if Harry is actually notified. This is the next lesson’s project. But for now, the only thing we see as a user when we run the program is the Hagrid sent. message. To fix that, we can use string concentration methods. I will show you what I found the most effective way of doing that: f-string formatting.

We can use f-strings whenever we are defining a regular string. If we want to use f-strings, we do that like in this example:

age = 25
name = "John"

text = f"Hi {name}, you are {age} years old."
print(text)

We defined a name and age, then concentrated all of them together in another string. Instead of just defining a variable like test = "", we add an “f” at the beginning of the quote signs and use our variable in between curly brackets, inside the quotes.

Remember that we could just use text = "Hi " + name in our example since they were both strings, but if we try to do that with the age variable, it would throw an error. You cannot add apples and oranges together.

You don’t have to define the “text” variable, you can directly use the f-string inside the print() function as well. This will shrink our code by 25% in that example:

age = 25
name = "John"

print(f"Hi {name}, you are {age} years old.")

This would still yield the same result but use less space and memory. With all the new information we have, we can see how many mails Dumbledore sent to Harry in the console by simply adding this to our loop:

print(f"{copiesSent} mails sent.")

This addition made our code look like this:

isHarryNotified = False
copiesSent = 0

while not isHarryNotified and copiesSent < 5000:
copiesSent += 1
print(f"{copiesSent} mails sent.")

if isHarryNotified == False:
print("Hagrid sent.")

Save it as “DumbledoreSimulator.py”, run it, and voila! There is your first simulation!

homework.

We covered a lot of concepts in a short time. Again, I encourage you to do the exercises from scratch or come up with your own examples. It may look like voodoo magic to you now, and if I couldn’t explain a concept to you very well right now, you can Google it to get different explanations of the same subject. I never say that I am a good teacher, but in more advanced lessons we will have much more fun. I can just say that.

As your little exercise, I created a problem:

problem; You have 6 imaginary screws, each of them needs to be turned 4 times to be tightened up. Start each screw at 0 and show them tightened up 4 times. Be creative!

That is all for this article. I hope you are all safe and healthy. If you like to share your creations, I will be waiting for them on Instagram and Twitter with the #interesthingprogram hashtag. Until the next time, happy programming.

--

--

Yağız Işkırık
Interesthings

Pilot & Programmer | I’m just an ordinary smart guy.