From Zero to Hero, master Python in one article

Image description

The first question, what is Python? According to Guido van Rossum, the father of Python, Python is:

A high-level programming language whose core design philosophy is code readability and syntax, allowing programmers to express their ideas with very little code.

For me, the number one reason to learn Python is that Python is a language that allows for elegant programming. It makes writing code and implementing my ideas simple and natural.

Another reason is that we can use Python in many places: data science, web development, machine learning, etc. can all be developed using Python. Quora, Pinterest, and Spotify all use Python for their backend web development. So let’s learn Python.

Python Basics

1. Variables

You can think of a variable as a word that stores a value. Let’s look at an example.

It is very easy to define a variable and assign a value to it in Python. Let’s try this if you want to store the number 1 in the variable “one”:

one = 1

Super simple, right? You just need to assign the value 1 to the variable “one”.

two = 2
some_number = 10000

You can assign any value to any other variable if you want. As you can see from above, the variable “two” stores the integer variable 2 and the variable “some_number” stores 10000.

In addition to integers, we can also use Boolean (True/Flase), string, floating point and other data types.

# booleanstrue_boolean = Truefalse_boolean = False# stringmy_name = "Leandro Tk"# floatbook_price = 15.80

2. Control flow: conditional statements

“If” uses an expression to determine whether a statement is True or False. If it is True, then execute the code within if. The example is as follows:

if True:
  print("Hello Python If")if 2 > 1:
  print("2 is greater than 1")

2 is greater than 1, so the print code is executed.

When the expression inside “if” is false, the “else” statement will be executed.

if 1 > 2:
  print("1 is greater than 2")else:
  print("1 is not greater than 2")

1 is smaller than 2, so the code inside “else” will be executed.

You can also use the “elif” statement:

if 1 > 2:
  print("1 is greater than 2")elif 2 > 1:
  print("1 is not greater than 2")else:
  print("1 is equal to 2")

3. Loops and iterations

In Python, we can iterate in different forms. I’ll talk about while and for.

While Loop: When the statement is True, the code block inside the while is executed. So the following code will print out 1 to 10 .

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

The while loop requires a loop condition. If the condition is always True, it will iterate forever. When the value of num is 11, the loop condition is false.

Another piece of code can help you better understand the usage of while statement:

loop_condition = Truewhile loop_condition:
    print("Loop Condition keeps: %s" (loop_condition))
    loop_condition = False

The loop condition is True so it will iterate until it is False .

For Loop: You can apply the variable “num” on a block of code and the “for” statement will iterate over it for you. This code will print the same code as in the while: from 1 to 10.

for i in range(1, 11):
  print(i)

Did you see that? It’s too simple. i ranges from 1 to the 11th element (10 is the tenth element)

List: collection | array | data structure

Suppose you want to store the integer 1 in a variable, but you also want to store 2 and 3 , 4 , 5 …

Instead of using hundreds or thousands of variables, is there another way for me to store the integers I want to store? As you guessed it, there are other ways to store them.

A list is a collection that can store a column of values (like the ones you want to store), so let’s use it:

my_integers = [1, 2, 3, 4, 5]

It’s really simple. We create an array called my_integer and store the data in it.

Maybe you will ask: “How do I get the values in the array?”

Good question. Lists have a concept called indexing. The first element of the lower table is index 0 (0). The index of the second one is 1, and so on, you should understand.

To make it more concise, we can represent the array element by its index. I drew it:

Image description

It’s easy to understand using Python’s syntax:

my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5print(my_integers[1]) # 7print(my_integers[4]) # 4

If you don’t want to store integers. You just want to store some strings, like a list of your relatives’ names. Mine looks something like this:

relatives_names = [ "Toshiaki", "Juliana", "Yuji", "Bruno", "Kaio"]

print(relatives_names[4]) # Kaio

Its principle is the same as storing integers, which is very friendly.

We have only learned how indexing of a list works, I also need to tell you how to add an element to the list’s data structure (add an item to the list).

The most common method of adding new data to a list is concatenation. Let’s see how it is used:

bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective Engineerprint(bookshelf[1]) # The 4 Hour Work W

Splicing is super easy, you only need to pass an element (such as “valid machine”) as a splicing parameter.

Okay, that’s enough about lists, let’s look at other data structures.

Dictionary: Key-Value data structure

Now we know that List is an indexed collection of integers. But what if we don’t want to use integers as indexes? We can use other data structures, such as numbers, strings, or other types of indexes.

Let us learn about the dictionary data structure. A dictionary is a collection of key-value pairs. The dictionary looks almost like this:

dictionary_example = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

Key is an index pointing to value. How do we access the value in the dictionary? You should have guessed it, that is using key . Let’s try it:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian"
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %s" %(dictionary_tk["nationality"])) # And by the way I'm Brazilian

We have a key(age)value(24), using a string as the key and an integer as the value.

I created a dictionary about me that contains my name, nickname, and nationality. These properties are keys in the dictionary.

Just like we learned to use indexes to access lists, we also use indexes (the key in the dictionary is the index) to access the value stored in the dictionary.

Just like we did with lists, let’s learn how to add elements to a dictionary. The dictionary mainly refers to the key that points to value. The same goes for when we add elements:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I'm Brazilian

We just need to point a key in a dictionary to a value. Nothing difficult, right?

Iteration: Looping through data structures

As we learned in Python Basics, List iteration is very simple. We Python developers usually use For loops. Let’s try it:

 bookshelf = [
      "The Effective Engineer",
      "The 4 hours work week",
      "Zero to One",
      "Lean Startup",
      "Hooked"
    ]

    for book in bookshelf:
        print(book)

For each book on the shelf, we print (and do whatever we want) to the console. It’s super simple and intuitive. That’s the beauty of Python.

For hash data structures, we can also use for loops, but we need to use key to do it:

 dictionary = { "some_key": "some_value" }
    for key in dictionary:
         print("%s --> %s" %(key, dictionary[key])) # some_key --> some_value

Above is an example of how to use a For loop in a dictionary. For each key in the dictionary, we print out the key and the value corresponding to the key.

Another way is to use iteritems method.

 dictionary = { "some_key": "some_value" }
    for key, value in dictionary.items():
        print("%s --> %s" %(key, value))# some_key --> some_value

We name the two parameters key and value , but this is not necessary. We can name it whatever we want. Let’s take a look:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}

for attribute, value in dictionary_tk.items():
    print("My %s is %s" %(attribute, value))

# My name is Leandro
# My nickname is Tk
#MynationalityisBrazilian
# My age is 24

You can see that we use attribute as the parameter of key in the dictionary, which has the same effect as using key naming. What a great experience!

Class & Object

Some theories:

Objects are representations of real-world entities, such as cars, dogs, or bicycles. These objects share two main characteristics: data and behavior.

Cars have data, such as the number of wheels, doors and seat space, and they can exhibit their behavior: they can accelerate, stop, show how much fuel is left, and many other things.

We think of data as properties and behaviors in object-oriented programming. Also expressed as:

Data Properties and Behavior Methods

A class is a blueprint for creating a single object. In the real world, we often find many objects of the same type. For example, cars. All cars have the same make and model (have an engine, wheels, doors, etc.). Each vehicle is built from the same set of blueprints and has the same components.

Python object-oriented programming mode: ON

Python, as an object-oriented programming language, has the concept of classes and objects.

A class is a blueprint, a model of an object.

Well, a class is a model, or a way of defining properties and behavior (as we discussed in the theory section). For example, a vehicle class has its own properties that define what kind of vehicle the object is. A vehicle’s attributes include the number of wheels, type of energy source, seating capacity and maximum speed.

With this in mind, let’s look at the syntax of Python classes:

class Vehicle:
   pass

In the above code, we use the class statement to define a class. Is it easy?

An object is an instantiation of a class, and we can instantiate it through the class name.

car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>

Here, car is an object (or instantiation) of class Vehicle.

Remember that the vehicle class has four properties: number of wheels, fuel tank type, seating capacity, and maximum speed. When we create a new vehicle object, we must set all properties. So here, we define a class that accepts parameters when it is initialized:

class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
    self.number_of_wheels = number_of_wheels
    self.type_of_tank = type_of_tank
    self.seating_capacity = seating_capacity
    self.maximum_velocity = maximum_velocity

This init method. We call it a constructor. So when we create a vehicle object, we can define these properties. Imagine we like Tesla Model S, so we want to create an object of this type. It has four wheels, runs on electricity, seats five and has a top speed of 250 kilometers per hour (155 miles per hour). We start by creating an object like this:

tesla_model_s = Vehicle(4, 'electric', 5, 250)

Four wheels + electric energy + five seats + maximum speed of 250 kilometers per hour.

All properties have been set. But how do we access these property values? We send a message to the object to request the value from it. We call it method. It is the behavior of the object. Let’s implement it:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity def number_of_wheels(self):
        return self.number_of_wheels def set_number_of_wheels(self, number):
        self.number_of_wheels = number

This is the implementation of the two methods number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first function is to get the attribute value, and the second function is to set a new value for the attribute.

In Python, we can use @property (modifier) to define getters and setters. Let’s see the actual code:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity @property
    def number_of_wheels(self):
        return self.number_of_wheels @number_of_wheels.setter
    def number_of_wheels(self, number):
        self.number_of_wheels = number

And we can use these methods as properties:

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2print(tesla_model_s.number_of_wheels) # 2

This is slightly different from method definition. The methods here are executed according to the properties. For example, when we set the new number of wheels, we do not regard these two as parameters, but set the value 2 to number_of_wheels. This is one way of writing python style getter and setter code.

But we can also use this method for other things, such as the “make_noise” method. let us see:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity def make_noise(self):
        print('VRUUUUUUUM')

When we call this method, it simply returns a string “VRRRRUUUUM.”

tesla_model_s = Vehicle(4, 'electric', 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUM

Encapsulation: Hide information

Encapsulation is a mechanism that restricts direct access to an object’s data and methods. But at the same time, it makes it easier to operate on the data (methods of objects).

“Encapsulation can be used to hide data members and member functions. By this definition, encapsulation means that the internal representation of an object is generally hidden from an external view of the object’s definition.” – Wikipedia
All internal representation of the object is hidden from the outside. Only the object itself can interact with its internal data.

First, we need to understand how public and non-public instance variables and methods work.

Public instance variables

For Python classes, we can initialize a public instance variable in our constructor method. Let’s look at this:

In this constructor:

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

Here we apply the first_name value as a parameter to the public instance variable.

tk = Person('TK')
print(tk.first_name) # => TK

In class:

class Person:
    first_name = 'TK'

Here, we don’t need first_name as a parameter, all instance objects have a class attribute initialized with TK.

tk = Person()
print(tk.first_name) # => TK

Cool, now we’ve learned that we can use public instance variables and class properties. Another interesting thing about the public section is that we can manage variable values. What do I mean? Our object can manage its variable values: Get and Set variable values.

Still in the Person class, we want to set another value for its first_name variable:

tk = Person('TK')
tk.first_name = 'Kaio'print(tk.first_name) # => Kaio

That’s it, we just set another value (kaio) for the first_name instance variable and updated the value. It’s that simple. Since this is a public variable, we can do this.

Non-public instance variables

We don’t use the term “private” here because in Python no properties are really private (without the usual unnecessary work). ?-?PEP 8
As public instance variable, we can define non-public instance variable inside constructor or class. The syntax difference is: for non-public instance variables, use an underscore (_) before the variable name.

“‘Private’ instance variables that cannot be accessed except from within the object do not exist in Python. However, there is a convention that most Python code follows: names prefixed with an underscore (such as _spam) should be considered The non-public part of the API (whether it is a function, method or data member)”?-? Python Software Basics
Here is sample code:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

Did you see the email variable? This is how we define non-public variables:

tk = Person('TK', '[email protected]')
print(tk._email) # [email protected]

We can access and update it. Non-public variables are just a idiom and should be treated as a non-public part of the API.

So we use a method inside the class definition to implement this functionality. Let’s implement two methods (email and update_email) to understand better:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email def update_email(self, new_email):
        self._email = new_email def email(self):
        return self._email

Now we can use these two methods to update and access non-public variables. Examples are as follows

tk = Person('TK', '[email protected]')
print(tk.email()) # => [email protected]._email = '[email protected]'print(tk.email()) # => [email protected]_email('new_tk@mail. com')
print(tk.email()) # => [email protected]
  1. We initialize a new object using first_name TK and email [email protected]
  2. Use method to access the non-public variable email and output it
  3. Try setting a new email outside the class
  4. We need to treat non-public variables as non-public part of the API
  5. Use our instance methods to update non-public variables
  6. Success! We updated it inside the class using a helper method. Public methods

For public methods, we can also use them within the class:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age def show_age(self):
        return self._age

Let’s test it out:

tk = Person('TK', 25)
print(tk.show_age()) # => 25

That’s fine – we have no problems using it within classes.

Non-public methods

But with non-public methods, we cannot do this. If we want to implement the same Person class, now use the show_age non-public method with an underscore (_).

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age def _show_age(self):
        return self._age

Now, we will try to call this non-public method with our object:

tk = Person('TK', 25)
print(tk._show_age()) # => 25

We can access and update it. Non-public methods are just a convention and should be considered a non-public part of the API.

Here’s an example of how we use it:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age def show_age(self):
        return self._get_age() def _get_age(self):
        return self._age

tk = Person('TK', 25)
print(tk.show_age()) # => 25

There is a _get_age non-public method and a show_age public method. show_age can be used by our objects (not in our class), while _get_age is only used in our class definition (inside the show_age method). But again, this is often the norm.

Packaging Summary

Through encapsulation, we ensure that the internal representation of an object is hidden from the outside world.

Inheritance: Behaviors and Traits

Certain objects have something in common: their behavior and characteristics.

For example, I inherited some of my father’s traits and behaviors. I inherited his eye and hair features, as well as his irritable and withdrawn behavior.

In object-oriented programming, a class can inherit common characteristics (data) and behavior (methods) of another class.

Let’s take another example and implement it in Python.

Imagine a car. Number of wheels, seating capacity and maximum speed are all attributes of a vehicle. We can say that the ElectricCar class inherits these same properties from the normal Car class.

class Car:
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

Implementation of our Car class:

my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)
print(my_car.seating_capacity)
print(my_car.maximum_velocity)

Once initialized, we can use all created instance variables. marvelous.

In Python, we inherit from the parent class as the parameter of the child. The ElectricCar class can inherit from our Car class.

class ElectricCar(Car):
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)

It’s that simple. We don’t need to implement any other methods because this class has already completed the inheritance from the parent class (inherited from the Car class). Let’s prove it:

my_electric_car = ElectricCar(4, 5, 250)
print(my_electric_car.number_of_wheels) # => 4
print(my_electric_car.seating_capacity) # => 5
print(my_electric_car.maximum_velocity) # => 250

Beautifully done.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138192 people are learning the system