Categories
Blog Tech

Python Beginners Guide: The way rich kids are taught [2024]35 min read

Python beginners guide sections:
  1. What is there for you?
  2. What is Python?
  3. Variables in Python
  4. Python data types
  5. Conditions in Python
  6. Loops in Python
  7. Python Functions
  8. Python modules and packages
  9. Classes and Object-oriented programming (OOP) in Python
  10. Next steps with Python

You are most probably reading this post because you are just starting (or planning to start) with Python. Perhaps you heard from someone you know that they are earning a lot with programming, and you want to do the same (because you are as smart as them).

Now, the good news is that I created this post to do just that – to teach someone with little or no experience how to start quickly (and free) with Python!

Since I know that programming can be boring, I promise to use very simple language and some funny memes here and there to show you that learning Python can bring some fun!

What is there for you?

Python is the most popular programing language of today. If you search Google for “top programming languages today” you will see that Python takes first or second place in most of those lists!

As a Python programmer, you can earn an average yearly salary of $120k in the US or around €60k in Europe. Remember, these are the averages, meaning that the people at the top of the chain earn around $200k and 100k in the US and Europe! (Click here to read my other post about IT salaries abroad).

Next to this, there is an enormous shortage of Python developers across the globe and companies are literally fighting over even just decent Python programmers. This means that you do not have to know everything to get a starting job and enjoy a very successful career as you are learning more!

💡In the US, 1.2 million IT jobs remain unfilled every year, in Germany, the tech talent shortage grows year by year by 12%. Find the full statistics here.

If you are not persuaded that learning python and reading this post further will bring you good, you can take the blue pill, forget everything, and close this post!

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

What is Python?

Congrats, you have taken the red pill – the path of truth and understanding! Now let’s explain Python in a way the rich kids are thoughthe high-level understanding comes first and as you advance, we bring the new details into the picture!

Python is a language just like any other (English, Dutch, Serbian). The only difference here is that Python is a programming language meaning that you can use Python to request your computer to do something.

Similar to other languages, Python has its syntax — the way the sentences are written including punctuation and special character. (As we move through the post, I will also teach you some basic sentence writing in Python.)

Python interpreter is a software (program) that runs on your operating system (e.g. Windows or Mac). Your OS then understands Python programming language. That said, you can write as much Python code as you like but if your computer does not have the Python interpreter installed it won’t be able to understand (interpret) your Python script.

💡Mac and other Linux-based operating systems already contain the Python interpreter (understand Python). Windows users must still install the interpreter just as any other program – download Python for Windows here.

Now when you know this, what do you see in this photo?

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Python interpreter

You write your Python code in a text format that you save for example as my-cool-code.py. The .py part tells your operating system that once open, this file should be interpreted by the Python interpreter!

And why is this interpreter needed? Well, computers talk in bits (sequences of ones and zeros). Python interpreter (software) has the main job of translating your Python code into the machine language. That said, whatever you write in your .py file will be translated to something like 00001010100011100101110 so that your computer’s parts can understand it!

In other words, the interpreter is translating your request into the machine language. The interpreter also collects the response and brings it back to you in the form we humans understand — by printing it on the screen.

💡Before moving on, read some of the basic networking concepts from my other post here.

Now it’s time to get our hands dirty with some code. For simplicity reasons, you can run your code on someone else’s computer from here. (Rather than installing Python on your PC).


Variables in Python

A variable is storage space in computer science parlance. All the code you are ever going to write will deal with the data you are storing in your variables. The word “variable” already points out that you can change the value of the data that your variable contains.

To use an analogy, you can think of variables in the same way you think of your socks drawer — it can store the socks but also anything else, till you need it next time! The same is with variables.

In fact, you have already written some variables in your life even though you might not be aware that you did. Yes, that was in the second grade of your primary school. Consider this photo.

The variable in this green board has its name. We call it x in our example. It also has the value of 2 that the variable x holds. So, variables have the name and the value componentthe name is on the left side from the equality sign (=) while the value is on the right side!

Let’s try it out now. You go to the online Python interpreter and just paste the code below and see what happens! (For the time being, take the print() syntax as a gateway to the human-readable format of your code).

Click here to run this code — press the green “Run” button once there

drawer = "Cat"
print(drawer)Code language: Python (python)

Yes! You now know what variables are and their use! Programming does not get much farther from variables actually. Everything else revolves around playing with variables, adding and removing values, and ultimately presenting the data to humans. So, you completed one crucial step here!

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Python data types

In the previous section, I taught you about Python variables. The value of any variable can be expressed in different formats. To simplify, you can assign “Hello” to your variable called drawer or you can assign the number 2 to the same variable. You are already playing with data types here! Read on!

💡Basic data types in Python include strings, numbers, lists, sets, dictionaries, tuples, and boolean.

Before I explain every of these, I want you to know early what all of this can serve you. The biggest mistake of many of the subject-matter books is that they keep everything too abstract for too long. (This particularly frustrated me in the beginning since I would read almost half of a book while still having a little clue on what is the real-life usage of all that – what’s the use of any knowledge if you cannot apply it?)

If you understand early the real-life usage of variables and data types, everything will make more sense. Things will start clicking on their own!

Pythons is a backend language meaning that it is running behind the scenes. Picture this simplified scenario for a moment. You are visiting a website in your browser where you want to leave your contact information. You fill in the form and click the send button. What you are seeing in your browser is not Python but most likely JavaScript (or similar). What happens further when you clicked the button is that JavaScript forwards the contact details to the backend script which can be written in Python (say filename contact.py). This Python script is now creating variables such as first_name, last_name, mobile_number, address and assigns the values you just typed in your browser! As the last line of contact.py, there can be a call to a database to store these details so that they can call you later!

After these words of wisdom, let’s look into every data type!

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

String

This one is very simple. A string is a sequence of characters that are treated literally by the Python interpreter. Your drawer variable was already of the string type!

So, you use strings when you want to pack a sentence or a word in a variable. Some example lines are below.


Click here to run this code — press the green “Run” button once there

introduction = "My name is Igor"
greeting = "Good evening!"
name = "Igor"
country = "The Netherlands"

print(introduction)Code language: PHP (php)

You can easily recognize a string since it is always within the (double or single) quotation marks! This simply tells the Python interpreter to leave everything as it is and just return what is within the quotes.

Number

There are several number data types in Python. Common for all of these data types is that they all store numbers. The catch is that the format can be different.

This means that not every number is the same. For instance, you can have the value of 3 or the value of 3.33333. Both are actually numbers but the first will be of the int (integer) data type while the second will be of the float data type. Here are some examples.

length = 3   # This variable is of the integer type that is written as int in Python
kilograms = 73.5   # This is now the float data type since the number contains the fraction part (not the whole number)
diameter = 13.63638386822948384   # Due to the many items after the decimal point, this type of number is called long in PythonCode language: PHP (php)

💡 The hashtag mark (#) in Python represents a comment. Comments serve to make your life easier and help you understand the code. Keep this good practice!

If you have already forgotten all the number data types — do not worry! You do not need to know it by heart, it is enough to Google “Python number data types” when you are unsure if it’s a float or a long.

I cannot stress enough how important the big picture is. Keep the high-level logic only and the small details will come with time.

List

All of the coming data types are now easier to understand since I already explained to you the strings and numbers. All other data types actually store strings or numbers (or both). This is the case with lists also. Since you already know a lot (not a joke), let’s look immediately into a sample list.

my_family = [5, "father", "mother", "brother", "sister"]Code language: JavaScript (javascript)

This list holds my family members that are grouped within the same list. Therefore, when you need to group more strings or numbers into one variable you can use lists for that.

If you have spotted that number 5, great. I added it just as an example to show you that lists can also hold numbers. In my case, it is the number of family members BUT it is used only for demonstration and it is not a good programming practice to have it this way.

Now, how do you collect an individual element of the list? Let’s say that you want to collect that number 5.

my_family = [5, "father", "mother", "brother", "sister"]
print(my_family[0]) #Prints 5Code language: PHP (php)

If you try the above code you will see that you can return any element by changing the [0] part, the number in particular. In programming, this is called an index. Every list member has an index number and in Python, the indexing starts at 0 and counts further till it reaches the last element. So, you can collect an individual element by mentioning its index. Below are the indexes of our list’s members.

Click here to run this code — press the green “Run” button once there

my_family = [5, "father", "mother", "brother", "sister"]
print(my_family[0]) # Prints 5
print(my_family[1]) # Prints "father"
print(my_family[2]) # Prints "mother"
print(my_family[3]) # Prints "brother"
print(my_family[4]) # Prints "sister"Code language: PHP (php)

The final thing to keep in mind regarding lists is that you can replace the value of any of their elements whenever you want. For instance, I could replace the number 5 with "dog" like this.

my_family = [5, "father", "mother", "brother", "sister"]
my_family[0] = "dog" # Replace the element at index 0 with the value "dog"
print(my_family) # Returns ["dog", "father", "mother", "brother", "sister"]Code language: PHP (php)

This feature of lists makes them mutable – changeable.


Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Sets

Sets have a very similar form to lists. You can recognize a set by curly brackets {}. Here is a sample set.

Click here to run this code — press the green “Run” button once there

my_class = {"Steve", "Peter", "Ivo", 3}
print(my_class)Code language: PHP (php)

As opposed to lists, sets are unordered sequences of elements. This means that if you execute the code above you might get a different order of the elements every time the code executes.

Sets are also immutable which means that you cannot change for instance the first element as we did with lists. The index does not work here. However, you can still, add the elements to the set. (This is a very common interview question – I also asked many candidates how lists differ from sets).

The last important fact is that sets do not contain duplicates. So, if you try to add “Peter” to our set above you would still see only one “Peter” in it – no duplicate allowed.

Almost there, 3 more data types to go!

Dictionary

Dictionaries you can also recognize by curly brackets {}. As opposed to sets, dictionaries contain elements in pairs. In programming, these pairs are called key-value pairs. The key part is an identifier while the value part is just a value assigned to that key. Let’s see an example.

contact_form = {
   "first_name":"Igor",
   "last_name":"Jovanovic",
   "country":"NL",
   "website":"https://igorjovanovic.com",
   "years_of_experience":17
}
print(contact_form)Code language: PHP (php)

This is exactly how the backend code of the contact form we explained earlier can store the entered contact details.

Now, if you want to access the individual values from the dictionary, you can write something like this.

Click here to run this code — press the green “Run” button once there

contact_form = {
   "first_name":"Igor",
   "last_name":"Jovanovic",
   "country":"NL",
   "website":"https://igorjovanovic.com",
   "years_of_experience":17
}
first_name = contact_form["first_name"]
last_name = contact_form["last_name"]
country = contact_form["country"]

print(first_name) # Prints "Igor"
print(last_name)  # Prints "Jovanovic"
print(country)    # Prints "NL"Code language: PHP (php)

Notice that we are collecting individual values by mentioning the key name in the square brackets []. So, to collect the first_name key out of the contact_form dictionary, you simply write contact_form["first_name"].

💡Dictionaries are one of the most common data types together with lists, strings, numbers, and booleans.

In a dictionary, you cannot have duplicate key names. Also, the order of the returned items remains the same in a dictionary. As with lists, you can change the elements of a dictionary whenever you want. Try the code below. Do you see what changed? Write in a comment.

contact_form = {
   "first_name":"Igor",
   "last_name":"Jovanovic",
   "country":"NL",
   "website":"https://igorjovanovic.com",
   "years_of_experience":17
}
contact_form["first_name"] = "Kristina"
print(contact_form)
Code language: PHP (php)
Tuple

Tuples you can recognize by regular brackets (). This data set is ordered and you can use the index to collect an individual element – the same you did with lists. Let’s say that we have a coffee queue with individuals’ names waiting for the coffee.

coffee_queue_name = ("igor", "joe", "nenad", "anna", "anna")
print(coffee_queue_name)Code language: PHP (php)

From here you can see that tuples allow duplicates! Another fact is that the order of the returned items remains the same as you execute the code again and again. Also, you can collect any value by using its index spot similar to the one below.

Click here to run this code — press the green “Run” button once there

coffee_queue_name = ("igor", "joe", "nenad", "anna", "anna")

print("The first to get coffee")
print(coffee_queue_name[0])

print("The last to get coffee")
print(coffee_queue_name[4])Code language: PHP (php)

Great, ready for the last data type? Let’s go to booleans.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Boolean

I sometimes respond very short to other people – YES/NO. Especially when I am sleepy or tired. If you are the same as me, you already used boolean in real life to confirm that something is TRUE or to declare it FALSE.

This data type can take only two values – True or False. A variable of the boolean type can look like this one.

respond_with_yes = True
respond_with_no = FalseCode language: PHP (php)

Booleans are used to test for truthfulness in your code. For instance, if one variable is greater than the other. I will explain more about the topic of conditions in the next section.

Now, congrats, you have completed the most difficult section and you have a very strong tool under your belt.

Conditions in Python

If you go on holiday now and then, you have most probably seen a sign similar to this while at a crossroads.

Depending on the direction (route) you take, you will reach London, Paris, or New York.

If you take the Paris route, you are not taking the New York one.

You can use this analogy to understand conditions in Python.

Basically, conditioning offers multiple routes for your code to take. These are the options, and when one is taken, other options get skipped.

A common keyword in programming for this job is called the If/Else statement. Let’s see an example immediately.

Click here to run this code — press the green “Run” button once there

my_destination = "Paris"

if my_destination == "Paris":
  print("Take the street 1")

elif my_destination == "London":
  print("Take the street 2")

elif my_destination == "New York":
  print("Take the street 3")

else:
  print("I do not know where you are going.")Code language: PHP (php)

This code will end up showing you the street number to take, depending on the desired destination. So, it will show you exactly one line depending on this condition, and all other options will be neglected.

💡Note: In Python, you check for equality by using the equality operator twice ==.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Since we already talked about the boolean data type, let’s zoom in on this line for a second.

if my_destination == "Paris":Code language: JavaScript (javascript)

The my_destination == "Paris" part is going to resolve to True or False during the code execution — to the boolean data type! The same logic holds for all other condition lines – these are translated to booleans during the execution so that the right route can be taken.

It is very simple; the execution starts from the first line and checks if and then every elif statement for truthfulness. If no condition is met before getting to the else statement, the else sentence gets returned.

💡Elif stands for else if in Python, and you can use it to introduce as many condition checks as you want. Remember that the condition set starts with a single if statement and ends with a single else statement. In between, you can add as many elif statements as you want.

Apart from the double equality sing =, you can also use other operators to compare two values. Here is the list.

a > b # a greater than b
a < b # a less than b
a >= b # a greater or equal to b
a <= b # a less or equal to bCode language: PHP (php)

That is all that you have to know for now about Python conditions. Was this easy to understand? Write in a comment.


Loops in Python

Going around in circles sometimes makes sense.

You use loops when you need to go over a bunch of items and collect the ones you are interested in.

Imagine this. You are reading a wonderful Python book that makes you so happy and enthusiastic about your programming future. Frequently you return to this book, but once you realize that you have lost the page separator and that you do not remember what the last page number you read was!

If you can remember that the last section was titled “Python Variables”, what are you going to do?

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Are you going to go page by page and check each for the title? If the book has 700 pages, this can be a lengthy process.

Since you are a programmer, you can write a loop that checks each page for the title, and if the title matches, ask your code to return the page number.

For Loop

The most common loop in programming is called the “For loop”. Let’s see how it works on our imaginary Python book.

Click here to run this code — press the green “Run” button once there

title_you_search_for = "Python Variables"

python_book_page_titles = {
   "1":"Introduction",
   "2":"Why Python",
   "3":"What is Python",
   "4":"Python Variables",
   "5":"Python Conditions",
   "6":"Data types: sets",
   "7":"Data types: dictionaries",
   "8":"Summary",
   "9":"Author's notes",
   "10":"The end"
}

for i in (1,2,3,4,5,6,7,8,9,10):

    if python_book_page_titles[str(i)] == title_you_search_for:
        print("The page number you are looking for is ")
        print(i)

    else:
        print("It is not on this page, looking on the next...")Code language: PHP (php)

Our book has 10 pages, and we pack the page numbers into the python_book_page_titles dictionary together with the corresponding titles as values.

The gist of the loop that checks each of our 10 pages is the for i in (1,2,3,4,5,6,7,8,9,10) part. So, as the loop runs once the i variable equals 1, on the second run the i variable equals 2, and so forth, until it reaches 10.

To check every page of the book, I use this condition.

if python_book_page_titles[str(i)] == title_you_search_for:

The variable i is taking the values of 1 to 10 , and my dictionary has the keys named the same. As the loop advances, each page will be checked against the title_you_search_for variable. If there is a match, the code prints the correct page number.

In other words, the loop makes the code run 10 times — one page each time (one key-value pair of the dictionary).

💡 The str(i) part is translating an integer into a string (casting). This is because my dictionary holds the keys in the string data format.

You have just read the gist of computing. Only at this moment, your knowledge is much different than writing everything on paper. Your code gets alive now, and it can do much more than any human can. It can check thousands of items (pages) in a second for any condition you can think of – welcome to the world of real powers!

If you need to spend more time on this section, feel free to reread it. Do not go further until you get this concept entirely. Try it yourself, fail sometimes, and generate some errors. Only once you are completely ready, go to the next section; it is worth every second of your time.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

💡Loops exist in every programming language in some form. It is mostly the case that once you know how loops work here, you can understand loops in any programming language since only the syntax part differs slightly.

Python Functions

Humans usually tend to save time and make things reusable as much as possible. In programming, this is achieved with functions.

Functions are nothing more than lines of code that you give a certain name so that you can call them later when you need them. This way, you can organize your code better so that the code is easier to read and understand.

When you create a function, you must define its name and the possible parameters that the function takes. Let’s immediately write a very simple function.

Click here to run this code — press the green “Run” button once there

def greetings(): # Defines a new function
  print("This is my first function!") 

greetings()   # Calls the functionCode language: PHP (php)

We defined our function by using the def keyword followed by the function name and the brackets (). In the body of the function, we have the line that prints This is my first function!.

Once the function is defined, we can call it later in our code by simply referring to its name — greetings().

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Parameters

To make a function more usable and smarter, you can introduce parameters. Parameters are variables that you pass to your functionvariables that you feed your function with. It would be better if our greetings() function could greet you by mentioning your name.

Click here to run this code — press the green “Run” button once there

def greetings(name): # Specifies that the function expects the name parameter
  print("Hello! Greetings to")
  print(name) 

greetings("Joe")   # Calls the function by passing the argument "Joe" for the name parameter
Code language: PHP (php)

By introducing the name parameter, you can reuse your function as many times as you want and greet as many people as you wish.

Most of the websites show a similar message once you log in — Welcome, Igor!. Now you understand that this is done by making use of a function.

💡 Arguments and parameters are terms that are used interchangeably in practice. Many IT professionals do not know this, but parameter refers to how you call your variables when you define a function. Argument refers to the value that is passed at the moment you call that function. In our example, name is a parameter, and "Joe" is an argument. You also do not need to know this – not a big deal.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Return

When you want your function to return some value, you use the keyword return.

Let’s consider this code.

Click here to run this code — press the green “Run” button once there

def do_the_math(a, b): # Define a new function
  sum_a_b = a + b
  return sum_a_b

find_the_sum = do_the_math(1, 4) # Call the function

print(find_the_sum) # Returns integer 5Code language: PHP (php)

The do_the_math function is going to return whatever the sum of a and b is. We pack those results in the find_the_sum variable. print() then prints what is in the find_the_sum variable.

💡 If you remove the return part, this code will not return any results.

When to use a function

Try to use functions as much as possible. This makes your code easier to follow. So, whenever you have lines of code participating in the same task, you can group them into a function.

Do you remember our code that can find the page we stopped reading at? It makes more sense to organize this code in a function.

Try to do it yourself — create a function named find_my_page() and make it receive the book (dictionary), title_to_look_for (string), and number_of_pages (integer) parameters. Reuse the code I wrote earlier to make this function return the page number and report results in a comment.

Python modules and packages

Next to its simplicity, Python is so popular because of the huge community of Python developers. These guys are constantly writing “shortcuts” available to the entire Python community, including you.

The shortcuts come in the shape of modules. Think of it; the function you wrote to find the lost page number could be useful to other people. You could therefore decide to put all your functions in a single .py file named lostfound.py and upload it to GitHub (code repository) so that others can download it. This is actually how you create a module.

Due to the enormous number of people writing Python, you can find a module for almost any task your code does. This means you will write fewer lines since you will reuse already written functions.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

All you have to do is install a module in your Python interpreter (or use Python built-in modules) and refer to the module in the first lines of your code. Here is what the code for that looks like.

import math

print("P value")
print(math.pi)Code language: PHP (php)

So, the keyword import followed by the module name does the trick here. It unlocks for you all the functions of the module that you can simply use by mentioning the module name followed by the function namemath.pi.

As you advance, you will also start storing your functions in different files and import them when there is a need. This means that you will create the custom modules that your program will use.

Let’s say you want to import your lostfound.py module, which contains the find_my_page()function. To use this function, you could write a code similar to mine below. (This code does not work due to the missing variables).

import lostfound

print("The lost page number is")
print(lostfound.find_my_page(book, title_to_look_for, number_of_pages))Code language: PHP (php)

💡Packages are nothing more than sets of Python modules bundled together. You import package in the same way you import modules. The way you pick individual functions is also the same. A more detailed description of the difference can be found here.

Now when you know that you can take shortcuts and not boil the ocean, it is reasonable to say that you can do a lot by only writing a few lines of code yourself. That is why Python is the easiest language to start with.

Let’s introduce now our last concept of this Python beginners guide. Fasten your seatbelt — here I present to you Object-oriented programming!


Classes and Object-oriented programming (OOP)

Let’s translate this complex term into something more tangible. Say you have a cat which is called Rocky. Once you want to leave your Rocky at a pet hotel, you need to complete a form with some of the cat’s details.

The receptionist would ask you what type of animal your pet is, and you would receive a form that is only for cats. So, you complete some of the fields below.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

  • Name of your cat……
  • Age of your cat……
  • Weight of your cat……
  • Fur color…….
  • Favorite game of your cat……
  • The number of meals that your cat consumes per day…….
  • Favorite food……

The hotel has created this template only once, yet all the cat owners use it. After an owner fills in the form, the form becomes personalized and refers to only one cat!

In programming, classes serve the same purpose as the intake form of the analogy.

Classes

A class is, therefore, a generic blueprint (template) that you can use to create personalized chunks of data. Let’s go and create one so that it becomes clearer.

Click here to run this code — press the green “Run” button once there

class Cat: # Create a new class called "Cat"

  def __init__(self, name, age, weight, fur_color, favorite_food, number_of_meals, favorite_game):
    self.name = name
    self.age = age
    self.weight = weight
    self.fur_color = fur_color
    self.favorite_food = favorite_food
    self.number_of_meals = number_of_meals
    self.favorite_game = favorite_game

my_cat = Cat("Rocky", 12, "11kg", "black", "crackers", "3", "running in circles")   # Creates an object out of the Cat class and stores it into the my_cat variable

print(my_cat.name) # Print "Rocky"
print(my_cat.weight) # Prints "12kg"

As you can see, the class looks very similar to a form with all the needed generic fields that would describe a cat. Once we defined the class, we can initiate that class with this line my_cat = Cat("Rocky", 12, "11kg", "black", "crackers", "3", "running in circles").

At that point, the Cat class gives life to a new object that we store within the my_cat variable. (This would be equivalent to the populated physical form with Rocky’s details).

An object is then an instance of a class — my_cat is an instance of the Cat class.

This means now that we can interact with the object stored in my_cat variable by referring to some of the labels, such as my_cat.name and my_cat.weight.

💡If you understand objects and classes in one programming language, you will understand them in any. The logic remains the same across all the programming languages.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

The __init__ function

In our earlier example, you have most probably spotted this unusual __init__ function within the class definition. Here is the code again.

class Cat: # Create a new class called "Cat"

  def __init__(self, name, age, weight, fur_color, favorite_food, number_of_meals, favorite_game):
    self.name = name
    self.age = age
    self.weight = weight
    self.fur_color = fur_color
    self.favorite_food = favorite_food
    self.number_of_meals = number_of_meals
    self.favorite_game = favorite_game

You remember that one of the biggest goals of programming is reusability. So, you can apply your knowledge of functions to understand this.

There is really nothing new here compared to other functions except that __init__ fires whenever you call (initiate) a given class. It is the primary function of the class, and the abbreviation init suggests that this function executes at the initiation of the class.

💡Perhaps a good analogy for the init function would be your car. You can drive the car only when started the engine by turning the key in the right direction. This is the first thing that the car ride assumes — the first thing that happens before you can use the car.

Attributes

Variables that you pass to your class via the __init__ function are called attributes. It is almost as in the spoken language. For instance, a cat has real-life attributes that describe her, such as name, color, and so forth. Similarly, attributes describe a particular class.

In our already famous example, attributes are defined with this line def __init__(self, name, age, weight, fur_color, favorite_food, number_of_meals, favorite_game):.

Once there is the usage of this class (embodied in a variable), you can access the attributes as we did earlier with my_cat.name and my_cat.weight.

💡The self keyword refers to the instance of a class. That is, to an object. It is the first declared parameter in __init__. With the help of this keyword, you can access the attributes and methods of your object. Note: self is not a Python-reserved keyword which means that you can replace it with almost any key.

Useful? Consider then my full-blown premium course on Engineering & Python. Click here to learn more.

Methods

You can think of attributes as static descriptors of a class. For instance, the name attribute of a cat will not change very often (if you do not want to confuse your cat).

To add behavior (action) to your class, you can use methods. Methods are nothing more than functions that reside within a given class. (Again, nothing new here, only a different name for the same thing).

By using methods, you can enrich your class with additional features. Let’s see now this in action by imagining that our cat hotel has a programmatic way to feed cats.

Click here to run this code — press the green “Run” button once there

class Cat: # Defines a class called "Cat"

  def __init__(self, name, age, weight, fur_color, favorite_food, number_of_meals, favorite_game):
    self.name = name
    self.age = age
    self.weight = weight
    self.fur_color = fur_color
    self.favorite_food = favorite_food
    self.number_of_meals = number_of_meals
    self.favorite_game = favorite_game
  
  def feed_this_cat(self): # Creates a new method called feed_this_cat
      print("The cat is eating now...")
      print("The cat is eating still...")
      print("The cat is happy again!")

my_cat = Cat("Rocky", 12, "11kg", "black", "crackers", "3", "running in circles")   # Creates an object out of the Cat class and stores it into the my_cat variable

my_cat.feed_this_cat() # Triggers the feeding process

You can spot that we have added a new function to our Cat class. feed_this_cat is a function within the class, meaning it is a method of that class. The primary goal of this method is to add some action to our class. That action happens in the last line of the code my_cat.feed_this_cat().

💡 Methods definitely support parameters in the way the usual function does. Here I wanted to demonstrate only a high-level usage of methods, but you can think of how to make this method more useful and write that in a comment.

This was all regarding classes, methods, and attributes. Allow yourself some time to completely digest this section and re-read it if you have to. You do not have to understand it entirely right now, and it is already great progress if you keep the big picture at this point.

Click here to learn how an efficient database connection can increase the app speed up to two times.

Next steps

This article has taught you that programming can be fun. Together, we went over the core concepts of Python (that apply to most modern programming languages).

I introduced the Python interpreter, the concept of variables, and all the core data types of Python.

Then we dug deeper into programming by understanding how conditions and loops can make your program do the heavy lifting. Finally, we added interaction to your code by talking about modules, functions, and classes.

If my post conveyed the message right, you also understand that Python programmers are in high demand since Python is the #1 programming language of today. There is also an enormous shortage of programmers, which will not improve at any time.

If you read the post to this point, I am happy to tell you that you have a great programming future. I can assure you that you are in a much better position than you think, even if you started this post as a complete beginner. These 9 sections are actually all that there is to programming. As a next step, you have to zoom in on the details of each section and continue writing more code by yourself.

As always, share your comments, and I will see you in the next post. Once again, you have done a great job here!

P.S. If you want to continue learning, consider my full-blown premium course on Engineering & Python. Click here to learn more.

Some common Python errors & resolutions:

  1. How to resolve IndexError: list index out of range
Avatar photo

By Igor Jovanovic

Founder & Full Stack Tech Consultant

Experienced tech professional with a strong track record in web services and fintech. Collaborating with Silicon Valley's multi-billion tech giants and offering a range of services committed to excellence. Check the Services page for how I can help you too.

13 replies on “Python Beginners Guide: The way rich kids are taught [2024]35 min read

Pravo je zadovoljstvo čitati ovaj tekst. Sve je lepo, kratko i jasno objašnjeno. Najlepše čestitke dragi Igore od Miomira Filipovića, profesora u penziji elektrotehničke srednje škole “Nikola Tesla” iz Beograda.

I am from South Africa and I am still 15. I do not have a career yet as I am still learning. I started learning the fundamentals of programming or “coding” earlier this year. I have found your resources and tips very useful.

If you came here via Quora quiz, the correct answer to the question is c). The code is going to print “Hello, Joe!”.

I like programming. Just started a few months ago and your post helped a lot! Thanks
I hope to continue your future lessons.

It’s was really interesting and i will love to continue learning python programming if you can teach me i will be great full

I learned a lot from this post, everything is excellent explained. I am looking forward to reading further your posts.

Leave a Reply

Your email address will not be published. Required fields are marked *