A summary of language Python knowledge points that can be elegantly programmed

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 primary reason for learning Python is that Python is a language that can be elegantly programmed. It can write code and implement my ideas simply and naturally.

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

Python basics

Variable

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

It's easy to define a variable in Python and assign it a value. If you want to store the number 1 to the variable "one", let's try it out:

One = 1

Super simple? You only need to assign the value 1 to the variable "one".

Two = 2

Some_number = 10000

You can assign any value to any other variable as long as 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 values ​​(True/Flase), strings, floats, 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 inside the if. The example is as follows:

If True:

Print("Hello Python If")

If 2 > 1:

Print("2 is greater than 1")

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

When the expression in "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 execute.

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 will say 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 = 1

While num <= 10:

Print(num)

Num += 1

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

Another piece of code can help you better understand the use of the 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 the code block, and the "for" statement will iterate over it for you. This code will print the same code as in while: from 1 to 10.

For i in range(1, 11):

Print(i)

Did you see it? This is too simple. The range of i starts from 1 to the 11th element (10 is the tenth element)

List: Collection | Array | Data Structure

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

Instead of using hundreds or thousands of variables, do I have other ways to store the integers I want to store? As you have already guessed, there are other ways to store them.

A list is a collection that stores a list of values ​​(just like the ones you want to store), so let's use it:

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

This is really simple. We created an array called my_integer and saved the data inside.

Maybe you will ask: "How do I get the values ​​in the array?"

Good question. The list has a concept called an index. The following table for the first element is index 0 (0). The second index is 1, and so on, you should understand.

To make it more concise, we can use its index to represent array elements. I drew it out:

Using Python's syntax is also very good to understand:

My_integers = [5, 7, 1, 3, 4]

Print(my_integers[0]) # 5print(my_integers[1]) # 7print(my_integers[4]) # 4

Suppose you don't want to save an integer. You just want to save some strings, like a list of your relatives' names. My looks look like this:

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

Print(relatives_names[4]) # Kaio

Its principle is as friendly as storing integers.

We only learned how the index of the list works, and I need to show you how to add an element to the list's data structure (add an item to the list).

The most common way to add new data to a list is stitching. 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 simple, you only need to use an element (such as "valid machine") as a splicing parameter.

Ok, this is enough about the knowledge of the list. Let's take a look at the other data structures.

Dictionary: Key-Value Data Structure

Now we know that List is an indexed set of integer numbers. But what if we don't use integer numbers as indexes? We can use other data structures such as numbers, strings or other types of indexes.

Let's learn the data structure of the dictionary. A dictionary is a collection of key-value pairs. The dictionary is almost as long as this:

Dictionary_example = {

"key1": "value1",

"key2": "value2",

"key3": "value3"

}

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

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) that uses a string as the key integer as value .

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

Just as we learned to use an index to access a list, we also use an index (in the dictionary, the key is the index) to access the value stored in the dictionary.

As we use lists, let's learn how to add elements to a dictionary. The dictionary is mainly the key that points to value. The same is true 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 only need to point a key in a dictionary to a value . Nothing hard, right?

Iteration: looping through the data structure

As we learned in the basics of Python, List iterations are quite simple. Our Python developers usually use For loops. Let's try it out:

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 (can do anything) to the console. Super simple and intuitive. This is the beauty of Python.

For hash data structures, we can also use a for loop, but we need to use the key.

Dictionary = { "some_key": "some_value" }

For key in dictionary:

Print("%s --> %s" %(key, dictionary[key])) # some_key --> some_value

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

Another way is to use the 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 as you like. Let us look at:

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

# My nationality is Brazilian

# My age is 24

You can see that we used attribute as the argument to the key in the dictionary, which has the same effect as using the key naming. That's great!

Class & object

Some theories:

An object is a representation of a real-world entity, such as a car, dog, or bicycle. These objects have two main characteristics in common: data and behavior.

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

We see data as attributes and behaviors in object-oriented programming. Also expressed as:

Data → Properties and Behavior → Method

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, a car. All cars have the same structure and model (all have an engine, wheels, doors, etc.). Each car is constructed 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 such a concept: classes and objects.

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

Then, a class is a model, or a way to define properties and behaviors (as we discussed in the theory section). For example, a vehicle class has its own properties to define what kind of vehicle the object is. The attributes of a car are the number of wheels, energy type, seat capacity and maximum speed.

With this in mind, let's take a look at the syntax of Python's classes:

Class Vehicle:

Pass

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

An object is an instantiation of a class, which we can instantiate by class name.

Car = Vehicle()

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

Here, car is the object (or instantiated) of the class Vehicle.

Remember that the vehicle class has four attributes: the number of wheels, the type of tank, the seat capacity and the maximum speed. Set all the properties when we create a new vehicle object. So here we define a class to accept arguments 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 this the constructor. So when we are creating a vehicle object, we can define these properties. Imagine that we like Tesla Model S, so we want to create an object of this type. It has four wheels, uses electric energy, five seats and has a maximum speed of 250 kilometers (155 miles). We started to create such an object:

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

Four rounds + 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. We call it a 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 two methods number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first function is to get the property value, the second function is to set a new value for the property.

In Python, we can use @property (modifier) ​​to define getters and setters. Let's take a look at 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 the method definition. The method here is performed according to the properties. For example, when we set a new number of tires, we do not consider these two as parameters, but set the value 2 to number_of_wheels. This is a way to write 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

Package: Hide information

Encapsulation is a mechanism that restricts direct access to object data and methods. But at the same time, it makes the operation on the data simpler (the method of the object).

"Encapsulation can be used to hide data members and member functions. According to this definition, encapsulation means that the internal representation of an object is generally hidden in the external view of the object definition." — Wikipedia

All internal representations of the object are hidden from the outside. Only the object itself can interact with its internal data.

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

Public instance variable

For Python classes, we can initialize a public instance variable in our constructor method. Let us 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 the class:

Class Person:

First_name = 'TK'

Here, we don't need to take first_name as a parameter, all instance objects have a class property initialized with TK.

Tk = Person()

Print(tk.first_name) # => TK

It's so cool, now we have learned that we can use public instance variables and class properties. Another interesting thing about the public part 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. Because this is a public variable, we can do this.

Non-public instance variable

We don't use the term "private" here because all properties in Python are not really private (no usual unnecessary work). — PEP 8

As a public instance variable, we can define a non-public instance variable inside a constructor or class. The grammatical difference is that for non-public instance variables, use an underscore (_) before the variable name.

"The 'Private' instance variable, which cannot be accessed from inside the object, does not exist in Python. However, there is a convention that most Python code will follow: the use of an underscore as a prefix (eg _spam) should be considered Non-public part of the API (whether it's a function, method, or data member)" — Python Software Foundation

Here is the sample code:

Class Person:

Def __init__(self, first_name, email):

Self.first_name = first_name

Self._email = email

Have you seen the email variable? This is how we define non-public variables:

Tk = Person('TK', '')

Print(tk._email) #

We can access and update it. Non-public variables are just an 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 function. Let's implement two methods (email and update_email) to deepen our understanding:

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. An example is as follows:

Tk = Person('TK', '')

Print(tk.email()) # => tk._email = ''print(tk.email()) # => tk.update_email('')

Print(tk.email()) # =>

We initialized a new object with first_name TK and email

Use method to access non-public variable email and output it

Try setting a new email outside the class

We need to treat non-public variables as non-public parts of the API

Use our instance methods to update non-public variables

success! We used the helper method to update it inside the class.

Public method

For public methods, we can also use them in classes:

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

Very good - we have no problems using it in the class.

Non-public method

But with a non-public approach, we can't do that. If we want to implement the same Person class, we 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 object (not in our class), and _get_age is only used in our class definition (in the show_age method). But again, this is usually the practice.

Package summary

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

Inheritance: behavior and characteristics

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

For example, I have inherited some of my father's characteristics and behavior. I inherited the characteristics of his eyes and hair, as well as his impatience and introverted behavior.

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

Let's look at another example and implement it in Python.

Imagine a car. The number of wheels, seat capacity and maximum speed are all attributes of a car. 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

The 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 the created instance variables. awesome.

In Python, we inherit from the parent class as a child parameter. 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 of the parent class (inherited from the Car class). Let us 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

Dry and beautiful.

Just come here!

Retractable Ethernet Cable

Retractable cable is usually double-pull-style.

Usage: double pull retractable cable, take the two ends of the retractable cable with two hands.Pull in the opposite direction and there will be a click in the middle. Repeat several times and choose your own length.When not in use, pull out a little bit when you hear the voice, let go of the telescopic cable will automatically retract.

The retractable cable is very easy to carry. Generally, 1 to 2 meters of net wire is made flat and soft wire, which is made into a coil with spring zhuan and other things. It can be stretched as long as you need, and retract back when not used, like a tape measure.

Retract ethernet cable

Retractable Ethernet,Retractable Ethernet Cable,Retractable Cat6 Cable,Retractable Network Cable

Shenzhen Kingwire Electronics Co., Ltd. , https://www.kingwires.com

Posted on