preface
This article is for experienced developers. If you are pure white also does not matter for you to prepare the corresponding learning materials behind.
First, what is Python? Python is, in the words of Python author Guido Van Rossum himself, “a high-level programming language whose core design is to make all code easier to read and to give developers a syntax that allows them to write programming logic in just a few lines of code.”
So, for me, the first reason to learn Python is that it’s beautiful and elegant, and it allows me to implement my ideas smoothly and naturally.
Another reason is that Python supports multiple programming domains, such as:
- Data science
- Web development
- Machine learning projects like Quora, Pinterest, Spotify, all use Python to develop their backends.
So, let’s start learning Python!
basis
1. The variable
You can think of a variable simply as a word that stores a value.
To be reasonable, there is no need to explain what a variable is… Everybody gets it.
In Python, defining variables and assigning values to variables is very simple. For example, if you want to store the number 1 in a variable named one, you just need to do this:
one = 1
Copy the code
Pretty simple, right? (some_number = 10000) (some_number = 10000) (some_number = 10000)
two = 2
some_number = 10000
Copy the code
Of course, we can also set Booleans, strings, single-precision, and a few other data types in addition to integers. As follows:
# booleans
true_boolean = True
false_boolean = False
# string
my_name = "Leandro Tk"
# float
book_price = 15.80
Copy the code
Scanning for free
2. Flow control: branch statements
If, this statement is used to determine whether a condition is met. It is followed by a logical expression that ends with a value of True or False. If True, the statement inside if is executed. As follows:
if True:
print("Hello Python If")
if 2 > 1:
print("2 is greater than 1")
Copy the code
Since 2 is greater than 1, the condition is true, so the print statement is executed
Of course, if the condition is not met, else comes in handy!
If the final value of the logical expression followed by if is false, the else program is run as follows:
if 1 > 2:
print("1 is greater than 2")
else:
print("1 is not greater than 2")
Copy the code
You can also use elif, which is short for else if, but be sure to write it wrong
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")
Copy the code
3. Loops/iterators
In Python, we have several ways of iterating, and I’ll mention two here:
While loop: When the logical expression is true, the indented block of code under the While is executed in a loop. So the following code snippet will print from 1 to 10.
num = 1
while num <= 10:
print(num)
num += 1
Copy the code
The above loop requires a loop condition. If the loop condition is true, the iteration continues. In the above example, when num becomes 11, the loop condition is False.”
Take a look at the following basic code block to understand:
loop_condition = True
while loop_condition:
print("Loop Condition keeps: %s" %(loop_condition))
loop_condition = False
Copy the code
As long as the loop condition is True, it will continue to loop until the loop condition becomes False
For loop: As in other languages, this is used For counting loops, depending on the range method that follows.
Range in the loop, it’s used to represent the range from x to n, as follows, from 1 to 11. The third parameter is null, which means incrementing each time. By default, I is incremented once in the loop
for i in range(1, 11):
print(i)
Copy the code
Video recommendation:
Python to learn these interview part-time orders are not a problem!
www.bilibili.com College students how to use Python online orders, part-time jobs can also earn more than 10,000 yuan a month
List: set | | array data structure
Imagine that you want to store the integer 1 in a variable. But maybe now you want to store 2 and 3,4,5…
Do I have another way to store all the integers I want, but not in millions of variables? You guessed it — there really is another way to store them.
A List is a collection that can be used to store a List of values (such as the integers you want). So let’s use it:
my_integers = [1, 2, 3, 4, 5]
Copy the code
It’s really easy. We create an array and store it in my_INTEGER.
But maybe you’re asking, “How do I get value from this list?”
Good question. List has a concept called index. The first element gets the index 0 (zero). The second one is 1, and so on. You get the idea.
To make it clearer, we can use its index to represent the array and each element. I can draw it:
It is also easy to understand using Python syntax:
my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5
print(my_integers[1]) # 7
print(my_integers[4]) # 4
Copy the code
Imagine now that you don’t want to store integers. You just want to store strings, like a list of your relatives’ names. It looks something like this:
relatives_names = [
"Toshiaki",
"Juliana",
"Yuji",
"Bruno",
"Kaio"
]
print(relatives_names[4]) # Kaio
Copy the code
It works the same way as integers, beautiful.
We’ve just seen how Lists indexing works. But I still need to show you how to add an element to the List data structure (an item to the List).
The most common way to add a value to a List is append. Let’s see how he works:
bookshelf = [] bookshelf.append("The Effective Engineer") bookshelf.append("The 4 Hour Work Week") print(bookshelf[0]) # The Effective Engineer print(bookshelf[1]) # The 4 Hour Work WeekCopy the code
Append is pretty simple. All you need to do is apply an element (such as “The Effective Engineer”) as an “Append” parameter. So, with Lists out of the way, let’s talk about another data structure.
Dictionary: key-value data structures
We now know that Lists are indexed by integers. But what if we don’t want to use integers to index? Other data structures can be indexed using numbers, strings, or other types.
Let’s learn about Dictionary data structures. A Dictionary is a collection of key-value pairs. It looks like this:
dictionary_example = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Copy the code
Keys are used to index to values. So how do we access Dictionary values? You guessed it — use the keys. 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
Copy the code
I created a Dictionary about me. My name, nickname and nationality. These properties are the keys of the Dictionary.
We know that accessing a List uses subscripts, and we also use subscripts here (the contents of keys in the Dictionary) to access values that exist in the Dictionary.
In this example, I printed out all the phrases about me that exist in the Dictionary. It’s very simple.
Another cool thing about dictionaries is that we can use anything as a Dictionary value. In the Dictionary I created, I want to add the key “age” and the value to be my integer age:
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
Copy the code
Here we have a key (age) value (24) pair using strings as keys and integers as values.
Just as we studied Lists, let’s learn how to add elements to a Dictionary. In Dictionary, it is important that a key points to a value. That’s why we talk about it when we add elements:
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}
dictionary_tk['age'] = 24
print(dictionary_tk) # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}
Copy the code
We just need to specify a value to the Dictionary’s key. It’s not complicated at all. 484?
Iteration: Loop over data structures in Python
As we learn the basics of Python, iterating over a list is a very easy thing to do, and usually we Python developers use a For loop to iterate over it. Now 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)
Copy the code
As you can see we’ve done the for operation on the books in the bookshelf, and we’ve printed out the books in it (of course you can do anything with them in the loop). Simple and intuitive, that’s Python.
We can also iterate over hash data structures, such as dictionaries in Python, using a for loop, but we need key:
dictionary = { "some_key": "some_value" }
for key in dictionary:
print("%s --> %s" %(key, dictionary[key]))
# some_key --> some_value
Copy the code
This is a small example of a circular dictionary-type variable. For a dictionary variable, we use a for loop to operate on its key, and then we print out its key and its matching value.
Of course, there is another way to implement this, which is to use iteritems:
dictionary = { "some_key": "some_value" }
for key, value in dictionary.items():
print("%s --> %s" %(key, value))
# some_key --> some_value
Copy the code
You can see that we have named two parameters key and value, but this is not necessary. You can even name them either ^.^.
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
Copy the code
Haha, you can see that we have used the attribute as the key parameter of the Dictionary, and the code is running correctly. Wow!!!!
Types and Objects
A bit of basic theory:
Objects represent things in the real world like cars, dogs, bicycles. Objects have two main characteristics: data and behavior.
In object-oriented programming, we treat data as properties and behavior as methods. That is:
Data → properties and behaviors → methods
A type is the blueprint for creating a single object instance. In the real world, we often find that many object instances have the same type, such as cars. They all have the same construction and model (with engines, wheels, doors, etc.). Each car is built from the same blueprint and has the same components.
Python’s object-oriented programming mode: ON
Python, as an object-oriented programming language, has the concepts of classes and objects.
Classes are blueprints and objects are models.
Similarly, a class is just a model, or a way of defining properties and behaviors (as we discussed in the theory section). For example, the vehicle class has its own attributes that define what a vehicle is. The number of wheels, type of energy, seating capacity and maximum speed are all attributes of the vehicle.
With that in mind, let’s look at the Python syntax for the class:
class Vehicle:
pass
Copy the code
We define the class with a class declaration, and that’s it. Simple, isn’t it?
An object is an instance of a class, which we create with a named class.
car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>
Copy the code
Here ‘car’ is an object (or instance) of the ‘Vehicle’ class.
Remember, our ‘Vehicle’ class has four attributes: number of wheels, power type, seat capacity, and maximum speed. We set all of these properties when we create a ‘Vehicle’ object. So here we define when our class is initialized to receive data:
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
Copy the code
We use the ‘init’ method. We call it a constructor. So you can define these properties when you create the ‘vehicle’ object. Let’s say we like the Tesla Model S and we want to create this object. It has four wheels, runs on electricity, has five seats and a maximum speed of 250km/h (155mph).
tesla_model_s = Vehicle(4, 'electric', 5, 250)
Copy the code
4 “wheels” + power “power” +5 “seats” +250km/h “maximum speed”
All the properties are set. But how do we get these property values? We send a message to the object to ask them. We call this method. Methods are the behavior of objects. 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
Copy the code
Two methods are created: number_of_wheels and set_number_of_wheels. We call it get&set. Because the first one gets the property value, and then the second one sets a new property value.
In Python, we can define “getters” and “setters” with “@property” (” decorator “). Take a look at the following 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
Copy the code
In the meantime, we can use these methods as attributes:
tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2
Copy the code
This is slightly different from the definition. These methods work differently from attributes. For example, when we set the number of wheels, we need to assign 2 to a variable, just set “number_of_wheels” to 2. This is a way to write “pythonic”, “getter”, “setter” code.
And we can also use other methods, such as the “make_noise” method. Take a look at the following example.
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')
Copy the code
When we call this method, it returns the string “VRRRRUUUUM”.
tesla_model_s = Vehicle(4, 'electric', 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUM
Copy the code
Encapsulation: Information hiding
Encapsulation is a mechanism that restricts direct access to object data and methods. But it speeds up access to data in object methods.
“Encapsulation hides data and function members from definitions, meaning that the internal description of an object definition is hidden from the outside” — Wikipedia
An object hides its internal description from the outside. Only an object can interact with its internal data.
First, we need to understand how “public” and “non-public” variable instances work.
Public variable instance
For a Python type, we can use the constructor to initialize an instance of a public variable. Let’s look at this:
By constructing:
class Person:
def __init__(self, first_name):
self.first_name = first_name
Copy the code
Here we pass the value of “first_name” as a parameter to the public variable instance.
tk = Person('TK')
print(tk.first_name) # => TK
Copy the code
In the class:
class Person:
first_name = 'TK'
Copy the code
Here, we do not need to use “first_name” as a parameter, all object instances have a class attribute initialized with “TK”.
tk = Person()
print(tk.first_name) # => TK
Copy the code
Beautiful. We’ve learned that we can use public variable instances and type attributes. Another interesting thing about the “public” part is that we can manage the values of its variables. What do I mean by that? Our object can manage its variable values: get and set variable values.
Remember the “Person” class, we want to set another value to its “first_name” variable:
tk = Person('TK')
tk.first_name = 'Kaio'
print(tk.first_name) # => Kaio
Copy the code
Ok, we just set another value (“kaio”) to the object variable “first_name” and it updates its value. It’s that simple, because of the “public” variable, we can do this.
Non-public variable instances
“We don’t use the word ‘private’ here, because there are no real ‘private’ attributes in Python (avoiding unnecessary work in general).” – the PEP 8
As with public variable instances, we can define non-public variable instances inside a constructor or class. The syntax difference is that for instances of non-public variables, we precede the variable name with an underscore (_).
“There is no object in Python that cannot be accessed internally from a ‘private’ instance of a variable. However, most Python code follows a convention: an object with an underscore before its name should be considered a non-public part of the API, such as _spam, whether it is a function, method, or data member.” – Python Software Foundation
Here’s an example:
class Person:
def __init__(self, first_name, email):
self.first_name = first_name
self._email = email
Copy the code
See the email variable? That’s how you define a non-public variable.
tk = Person('TK', '[email protected]')
print(tk._email) # [email protected]
Copy the code
A non-public variable is just a convention, and there is no mechanism to prevent us from accessing and updating it externally. But by convention, we should treat it as a non-public part of the API.
Inside classes, we usually use methods to manipulate “non-public variables,” so let’s implement two methods (email and update_email) to understand that.
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
Copy the code
We can now access and update non-public variables using these methods.
tk = Person('TK', '[email protected]')
print(tk.email()) # => [email protected]
tk._email = '[email protected]'
print(tk.email()) # => [email protected]
tk.update_email('[email protected]')
print(tk.email()) # => [email protected]
Copy the code
- We initialize a Person object with first_name TK and email [email protected].
- Method access the non-public variable email and print it out.
- Set a new email directly from outside the class.
- We should treat non-public variables as non-public parts of the API.
- Update the non-public variable email via the instance method.
- Success! We can update it by default.
Public methods
With public methods, we can also use these methods outside of our class:
class Person:
def __init__(self, first_name, age):
self.first_name = first_name
self._age = age
def show_age(self):
return self._age
Copy the code
Let’s try it:
tk = Person('TK', 25)
print(tk.show_age()) # => 25
Copy the code
Awesome – No problem with it.
Non-public method
But we can’t do that by non-public means. Let’s start by implementing the same Person class, but this time with an underscore (_) to define a non-public method of show_age.
class Person:
def __init__(self, first_name, age):
self.first_name = first_name
self._age = age
def _show_age(self):
return self._age
Copy the code
So now, let’s try calling this non-public method from our object:
tk = Person('TK', 25)
print(tk._show_age()) # => 25
Copy the code
We can access it and update it. Non-public methods are just a class of conventions and should be treated as non-public parts of the interface.
Here’s an example of how we can 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
Copy the code
Here we have a _get_age non-public method and a show_age public method. Show_age can be called by our object (outside the class) while _get_age can only be used inside our class definition (the internal show_age method). But again, this is just a rule.
Encapsulates summary
Encapsulation allows us to hide the internal representation of an object from the outside.
Inheritance: Behavior and characteristics
Some objects have something in common: behaviors and characteristics.
For example, I inherited some traits and behaviors from my father. I inherited his eyes and hair as features, his impatience and introversion as behavior.
In object-oriented programming, classes can inherit characteristics (data) and behaviors (methods) from other classes.
Let’s look at another example.
Let’s say I have a car. The number of wheels, passenger capacity and top speed are all attributes of a car. We can then assume that ElectricCar inherits these attributes from the 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
Copy the code
After our Car class is implemented:
my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)
print(my_car.seating_capacity)
print(my_car.maximum_velocity)
Copy the code
Once initialized, we can use all created instance variables.
In Python we can use a parent class as an argument when defining a subclass. An ElectricCar class can inherit from a previous 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)
Copy the code
Simple as above. We don’t need to implement any other methods because this class already exists (inherited from the Car class). Let’s be sure:
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
Copy the code
That’s it!
We’ve learned a lot about Python basics:
- variable
- Branch statements
- Loop syntax
- List: set | array
- Dictionary: a collection of key-value pairs
- How do you iterate over these data structures
- Object and class
- Use properties as data for objects
- The act of using methods as objects
- Getters, setters, and Property decorators
- Encapsulation: Information hiding
- Inheritance: Behavior and characteristics
A: congratulations! You’ve completed this dense section of Python.
For more stories and articles on my journey to learn and master programming, follow Python here
Keep learning, keep programming, and have fun!