Join The Revolution

Will you join the revolution? That’s what the children want to know. Will you grab the seeds and shovel and meet us in the field? Your flowers, they sing the song of joy and beauty. They bloom and…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Your First Python Tutorial

Except for the formal, boring stuff

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:

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:

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.

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.

Python Downloads page
Python Downloads page

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:

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

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.

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.

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.

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”.

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.

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

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

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

name = "Bob"

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

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!

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.

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 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 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.

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.

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

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:

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.

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.

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!

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.

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.

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:

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.

First, we get the user’s name.

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.

And we print it out 5 times.

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:

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 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:

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.

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:

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.

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 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:

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

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.

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

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.

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

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:

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

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:

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.

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

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:

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:

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:

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:

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:

This addition made our code look like this:

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

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:

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.

Add a comment

Related posts:

Bila

Dinginnya bersama diam, bisunya bersama hujan.. “Bila” is published by hsnabila.

IMDB Movies Analysis for New Movie Studio

An in depth walk through of using pandas and seaborn to determine what features of a movie make it succesful. Please visit my github repository for full code. The focus of this project is to analyze…

VR Property Viewings Helps You to Stay Home and Stay Safe from COVID

Through the use of new technologies, digital transformation allows companies to update their SOPs, simplify their original organization structure, increase the efficiency of teamwork and provide…