Learning Python: From Zero To Hero: by TK
Learning Python: From Zero To Hero: by TK
Learning Python: From Zero To Hero: by TK
by TK
First of all, what is Python? According to its creator, Guido van Rossum,
Python is a:
Another reason was that we can use coding in Python in multiple ways:
data science, web development, and machine learning all shine here.
Quora, Pinterest and Spotify all use Python for their backend web
development. So let’s learn a bit about it.
The Basics
1. Variables
You can think about variables as words that store a value. Simple as that.
one = 1
How simple was that? You just assigned the value 1 to the variable “one.”
two = 2
some_number = 10000
And you can assign any other value to whatever other variables you want.
As you see in the table above, the variable “two” stores the integer 2, and
“some_number” stores 10,000.
Besides integers, we can also use booleans (True / False), strings, oat, and
so many other data types.
# booleans
true_boolean = True
false_boolean = False
# string
my_name = "Leandro Tk"
# float
book_price = 15.80
if True:
print("Hello Python If")
if 2 > 1:
print("2 is greater than 1")
if 1 > 2:
print("1 is greater than 2")
else:
print("1 is not greater than 2")
1 is not greater than 2, so the code inside the “else” statement will be
executed.
You can also use an “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. Looping / Iterator
In Python, we can iterate in different forms. I’ll talk about two: while and
for.
While Looping: while the statement is True, the code inside the block will
be executed. So, this code will print the number from 1 to 10.
num = 1
loop_condition = True
while loop_condition:
print("Loop Condition keeps: %s" %(loop_condition))
loop_condition = False
The loop condition is True so it keeps iterating — until we set it to False .
For Looping: you apply the variable “num” to the block, and the “for”
statement will iterate it for you. This code will print the same as while
code: from 1 to 10.
See? It is so simple. The range starts with 1 and goes until the 11 th
element ( 10 is the 10 th element).
Do I have another way to store all the integers that I want, but not in
millions of variables? You guessed it — there is indeed another way to
store them.
List is a collection that can be used to store a list of values (like these
integers that you want). So let’s use it:
my_integers = [1, 2, 3, 4, 5]
But maybe you are asking: “How can I get a value from this array?”
Great question. List has a concept called index. The rst element gets
the index 0 (zero). The second gets 1, and so on. You get the idea.
To make it clearer, we can represent the array and each element with its
index. I can draw it:
my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5
print(my_integers[1]) # 7
print(my_integers[4]) # 4
Imagine that you don’t want to store integers. You just want to store
strings, like a list of your relatives’ names. Mine would look something like
this: Follow me on LinkedIn for more:
Steve Nouri
https://www.linkedin.com/in/stevenouri/
relatives_names = [
"Toshiaki",
"Juliana",
"Yuji",
"Bruno",
"Kaio"
]
print(relatives_names[4]) # Kaio
We just learned how Lists indices work. But I still need to show you how
we can add an element to the List data structure (an item to a list).
The most common method to add a new value to a List is append . Let’s
see how it 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 Week
append is super simple. You just need to apply the element (eg. “The
Effective Engineer”) as the append parameter.
Well, enough about Lists . Let’s talk about another data structure.
The key is the index pointing to the value. How do we access the Dictiona
ry value? You guessed it — using the key. Let’s try it:
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}
As we learned how to access the List using index, we also use indices
(keys in the Dictionary context) to access the value stored in the Dictio
nary .
In the example, I printed a phrase about me using all the values stored in
the Dictionary . Pretty simple, right?
Another cool thing about Dictionary is that we can use anything as the
value. In the Dictionary I created, I want to add the key “age” and my real
integer age in it:
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian",
"age": 24
}
Here we have a key (age) value (24) pair using string as the key and integer
as the value.
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}
dictionary_tk['age'] = 24
So for each book in the bookshelf, we (can do everything with it) print it.
Pretty simple and intuitive. That’s Python.
For a hash data structure, we can also use the for loop, but we apply the
key :
This is an example how to use it. For each key in the dictionary , we pri
nt the key and its corresponding value .
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian",
"age": 24
}
# My name is Leandro
# My nickname is Tk
# My nationality is Brazilian
# My age is 24
We can see we used attribute as a parameter for the Dictionary key , and
it works properly. Great!
Cars have data, like number of wheels, number of doors, and seating
capacity They also exhibit behavior: they can accelerate, stop, show how
much fuel is left, and so many other things.
And a Class is the blueprint from which individual objects are created. In
the real world, we often nd many objects with the same type. Like cars.
All the same make and model (and all have an engine, wheels, doors, and
so on). Each car was built from the same set of blueprints and has the
same components.
class Vehicle:
pass
We de ne classes with a class statement — and that’s it. Easy, isn’t it?
car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity,
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity
All attributes are set. But how can we access these attributes’ values? We
send a message to the object asking about them. We call it a method. It’s
the object’s behavior. Let’s implement it:
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity,
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
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity,
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
But we can also use methods for other things, like the “make_noise”
method. Let’s see it:
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity,
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')
class Person:
def __init__(self, first_name):
self.first_name = first_name
tk = Person('TK')
print(tk.first_name) # => TK
class Person:
first_name = 'TK'
Cool. We have now learned that we can use public instance variables
and class attributes . Another interesting thing about the public part
is that we can manage the variable value. What do I mean by that? Our o
bject can manage its variable value: Get and Set variable values.
Keeping the Person class in mind, we want to set another value to its fir
st_name variable:
tk = Person('TK')
tk.first_name = 'Kaio'
print(tk.first_name) # => Kaio
There we go. We just set another value ( kaio ) to the first_name instance
variable and it updated the value. Simple as that. Since it’s a public
variable, we can do that.
Here’s an example:
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 de ne a non-public vari
able :
tk = Person('TK', '[email protected]')
print(tk._email) # [email protected]
class Person:
def __init__(self, first_name, email):
self.first_name = first_name
self._email = email
tk = Person('TK', '[email protected]')
print(tk.email()) # => [email protected]
# tk._email = '[email protected]' -- treat as a non-public part of the cla
print(tk.email()) # => [email protected]
tk.update_email('[email protected]')
print(tk.email()) # => [email protected]
6. Success! We can update it inside our class with the helper method
Public Method
With public methods , we can also use them out 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
tk = Person('TK', 25)
print(tk.show_age()) # => 25
Non-public Method
But with non-public methods we aren’t able to do it. Let’s implement the
same Person class, but now with a show_age non-public method using 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
And now, we’ll try to call this non-public method with our object:
tk = Person('TK', 25)
print(tk._show_age()) # => 25
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
Encapsulation Summary
With encapsulation we can ensure that the internal representation of the
object is hidden from the outside.
class Car:
def __init__(self, number_of_wheels, seating_capacity, maximum_veloc
self.number_of_wheels = number_of_wheels
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity
class ElectricCar(Car):
def __init__(self, number_of_wheels, seating_capacity, maximum_veloc
Car.__init__(self, number_of_wheels, seating_capacity, maximum_v
Beautiful.
That’s it!
We learned a lot of things about Python basics:
If you want a complete Python course, learn more real-world coding skills
and build projects, try One Month Python Bootcamp. See you there ☺
For more stories and posts about my journey learning & mastering