Python Tutorial For Beginners With Examples. Learn Python In One Day by following this blog post. Coding compiler has done it’s best to share this Python tutorial with examples. Let’s start learning Python programming in a day to get started with Python language. All the best for your future and happy python learning.
Python Tutorial For Beginners
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 that allows programmers to express their ideas with very little code.
For me, the primary reason to learn Python is that it is a language that can be gracefully programmed. It’s easy and natural to write code and implement my ideas.
What is Python Used For?
Another reason is that we can use Python in many places: data science, web development, machine learning, and so on, all can be developed using Python. Google, Quora, Pinterest, and Spotify all use Python for their backend Web development. Let’s learn about Python now.
Python Basics For Beginners
Here we go with learning Python in one day.
1. Python Variables
You can think of a variable as a word for storing a value. Let’s see an example.
It’s easy to define a variable in Python and assign it a value. If you want to store the number one to the variable “one,” let’s try it out:
two = 2 some_number = 10000
In addition to an integer, we can also use the True / False, string, float and other data types.
# booleanstrue_boolean = Truefalse_boolean = False# stringmy_name = "Leandro Tk"# floatbook_price = 15.80
2. Python Control flow: conditional statement
” If ” uses an expression to determine whether a statement is True or False. If True, execute the code in if, as shown in the following example:
1
2
3
|
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.
1
2
3
|
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 in ” else ” will be executed.
You can also use the “elif ” statement:
1
2
3
4
|
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. Python Loop and iterate
In Python, we can iterate in different ways. I will say while and for.
Python While Loop: While the statement is True, while the code block inside will be executed. So the code below prints 1 through 10.
1
2
3
|
num = 1while num <= 10:
print(num)
num += 1
|
The while loop needs a loop condition, and if condition, on is always true, it iterates all the time, with a loop condition of false when num’s value is 11.
Another piece of code can help you better understand the use of the while statement:
1
2
3
|
loop_condition = Truewhile loop_condition:
print(“Loop Condition keeps: %s” %(loop_condition))
loop_condition = False
|
The loop condition is True so it iterates until it’s False.
Python For loop : You can apply the variable ” num ” on the block of code , and the “for” statement will iterate over it for you. This code will print the same code as in while : from 1 to 10.
1
2
|
for i in range(1, 11):
print(i)
|
Did you see? This is too simple. The range of i starts from 1 until the eleventh element (10 is the tenth element).
Python 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, I have other ways to store these integers that I want to store? As you have already guessed, there are other ways to store them.
The list is a collection that can store a list of values (just like what you want to store), then let’s use it:
1
|
my_integers = [1, 2, 3, 4, 5]
|
This is really easy. We created an array called my_integer and put the data in it.
Maybe you might ask, “How do I get the value in the array?”
Ask good. The list has a concept called indexing. The following table of the first element is index 0 (0). The second index is 1, and so on, you should understand.
In Python’s syntax, it is also good to understand:
1
2
|
my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5print(my_integers[1]) # 7print(my_integers[4]) # 4
|
If you do not want to save the whole number. You just want to save some strings, like your relative’s list of names. My look is similar to this:
1
2
3
|
relatives_names = [ “Toshiaki”, “Juliana”, “Yuji”, “Bruno”, “Kaio”]
print(relatives_names[4]) # Kaio
|
Its principle is the same as storing an integer, very friendly.
We only learned how the index of a list works and 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 way to add new data to the list is to splicing. Let’s take a look at how it is used:
1
2
3
4
|
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
|
Stitching super easy, you only need to put an element (such as “valid machine”) as the splicing parameters.
Well, the list of knowledge is enough, let’s take a look at the other data structures.
Python Dictionary: Key-Value Data Structure
Now we know that List is an indexed integer number set. But what if we do not use integer numbers as indexes? We can use some other data structures, such as numbers, strings or other types of indexes.
Let’s learn about this dictionaries data structure. A dictionary is a collection of key-value pairs. The dictionary is about this long:
1
2
3
4
5
|
dictionary_example = {
“key1”: “value1”,
“key2”: “value2”,
“key3”: “value3”
}
|
Key is the index to value . How do we access the dictionary value ? You should guess, that is the use of key. Let’s try it out
1
2
3
4
5
6
7
8
9
|
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 for value .
I created a dictionary about me that contains my name, nickname, and nationality. These attributes are the keys in the dictionary.
Just as we have learned of using an index to access a list, we also use an index (the key in the dictionary is an index) to access the value stored in the dictionary.
As we use the list, let’s learn how to add elements to the dictionary. The dictionary mainly points to the value of the key. The same is true when we add elements:
1
2
3
4
5
6
7
8
9
10
|
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 vvalue. No hardship, right?
Python Iteration: Loop through the data structure
As we learned in the basics of Python, List iteration is simple. We Python developers usually use For loops. Let’s try it out
1
2
3
4
5
6
7
8
9
10
|
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 easy and intuitive. This is the beauty of Python.
We can also use the for loop for the hash data structure, but we need to use the key:
1
2
3
|
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 of key and key.
1
2
3
|
dictionary = { “some_key”: “some_value” }
for key, value in dictionary.items():
print(“%s –> %s” %(key, value))# some_key –> some_value
|
We named the two parameters key and value, but this is not necessary. We are free to name it. Let’s take a look:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 use the attribute as the key parameter in the dictionary, which has the same effect as using key naming. Really great!
Python Classes & Objects
Some theories:
Objects are representations of real-world entities, such as cars, dogs, or bicycles. These objects share two main features in common: data and behavior.
Cars have data such as the number of wheels, the number of doors and the seat space, and they can show their behavior: they can accelerate, stop, show how much fuel left, and many more.
We treat the data as attributes and behaviors in object-oriented programming. Again expressed as:
Data → Properties and Behaviors → Methods
The class is a blueprint to create a single object. In the real world, we often find many objects of the same type. For example, cars. All cars have the same structure and model (all with an engine, wheels, doors, etc.). Each car is constructed from the same blueprint and has the same components.
Python object-oriented programming model: ON
Python, as an object-oriented programming language, has the notion of classes and objects.
A class is a blueprint that is a model of the object.
So, 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 that define what kind of vehicle this object is. The attributes of a car are the number of wheels, energy type, seat capacity and a maximum speed of these.
With that in mind, let’s take a look at the syntax of Python’s classes :
1
2
|
class Vehicle:
pass
|
Above the code, we use the class statement to define a class. Is not it easy?
An object is a class instantiation, which we can instantiate by class name.
1
2
|
car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>
|
Here, car is an object (or instantiation) of class Vehicle.
Remember the vehicle class has four attributes: the number of wheels, fuel tank type, seat capacity and maximum speed. When we create a new vehicle object to set all the attributes. So here, we define a class that accepts parameters when it’s initialized:
1
2
3
4
5
6
|
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 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, uses electric energy, five seats and a maximum speed of 250 kilometers (155 miles). Let’s start by creating an object like this :
1
|
tesla_model_s = Vehicle(4, ‘electric’, 5, 250)
|
Four + energy + five + maximum speed of 250 km.
All the properties have been set. But how do we access these property values? We send a message to the object to request that value from it. We call this method. It is the behavior of the object. Let’s achieve it:
1
2
3
4
5
6
7
8
|
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 property value, the second 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:
1
2
3
4
5
6
7
8
9
10
|
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:
1
2
|
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 based on the property. For example, when we set the new number of tires, we do not regard these two as parameters, but set the value 2 to number_of_wheels. This is a 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:
1
2
3
4
5
6
7
|
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. “
1
2
|
tesla_model_s = Vehicle(4, ‘electric’, 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUM
|
Python Package: Hide information
Encapsulation is a mechanism that limits direct access to object data and methods. At the same time, however, it makes it easier to manipulate data (object methods).
“Package can be used to hide data members and member functions in accordance with this definition, it means that the package. Objects inside an external view showing typically hidden in the object definition.” – Wikipedia
All internal representations of objects are hidden from the outside. Only the object itself can interact with its internal data.
First, we need to understand how open and closed instance variables and methods work.
Public instance variables
For the Python class, we can initialize a public instance variable in our constructor method. Let’s take a look at this one:
In this construction method:
1
2
3
|
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 variables.
1
2
|
tk = Person(‘TK’)
print(tk.first_name) # => TK
|
In the class:
1
2
|
class Person:
first_name = ‘TK’
|
Here, we do not need to first_name as a parameter, all instance objects have a class attribute initialized with TK.
1
2
|
tk = Person()
print(tk.first_name) # => TK
|
Too cool, and 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 the values of the variables. 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:
1
2
|
tk = Person(‘TK’)
tk.first_name = ‘Kaio’print(tk.first_name) # => Kaio
|
This is fine, we just set another value (kaio) for the first_name instance variable and update the value. It’s that simple. Because this is a public variable, we can do that.
Python Non-public instance variables
We do not use the term “private” here because all of the properties in Python are not really private (there is usually no unnecessary amount of work). - PEP 8
As public instance variable
(public instance variables), we can define non-public instance variable
(non-public instance variables) inside the constructor or class.
The difference in the syntax is that for non-public instance variables
(non-public instance variables), an underscore (_) is used before the variable name.
“Private ‘instance variables that are not accessible from inside the object do not exist in Python, however, there is a convention that most Python code will follow: underscore names (such as _spam) should be considered as Non-public part of API (whether function, method, or data member) “
Here is sample code:
1
2
3
4
|
class Person:
def __init__(self, first_name, email):
self.first_name = first_name
self._email = email
|
Have you seen the email variable yet? This is how we define non-public variables:
1
2
|
|
We can access and update it. Non-public variables are just a matter of usage and should be treated as a non-public part of the API.
So we use a method within the class definition to implement this functionality. Let’s implement two methods (email and update_email) to deepen our understanding:
1
2
3
4
5
6
|
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. Here is an example
1
2
3
|
print(tk.email()) # => [email protected]._email = ‘[email protected]’print(tk.email()) # => [email protected]_email(‘[email protected]’)
|
- We initialized a new object using first_name TK and email [email protected]
- Use the method to access a 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 method to update the non-public variables
- Success! We’ve updated it inside the class using helper methods.
Python Public method
For public methods, we can also use them in classes:
1
2
3
4
5
|
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:
1
2
|
tk = Person(‘TK’, 25)
print(tk.show_age()) # => 25
|
That’s fine – we have no problems using it in our class.
Python Non-public methods
But with a non-public method, we can not do that. If we want to implement the same Person class, we now use the underscore (_) show_age non-public method.
1
2
3
4
5
|
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 invoke this non-public method with our object:
1
2
|
tk = Person(‘TK’, 25)
print(tk._show_age()) # => 25
|
We can access and update it. The non-public method is just a convention and should be considered as a non-public part of the API.
Here’s an example of how we can use it:
1
2
3
4
5
6
7
8
9
|
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
|
Here’s a _get_age non-public method and a show_age public method. show_age can be used by our object (not in our class), while _get_age is only used in our class definition (in the show_age method). But again, this is usually the practice.
Python Package summary
Through the package, we can ensure that the internal representation of the object is hidden from the outside.
Python Inheritance: Behavior and Features
Some objects have something in common: their behavior and characteristics.
For example, I inherited some of my father’s features and behaviors. 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 characteristics (data) and behaviors (methods) of another class.
Let’s look at another example and implement it in Python.
Imagine the 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.
1
2
3
4
5
|
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 realization of our Car class:
1
2
3
4
|
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. awesome.
In Python, we inherit the parent class as a child argument. An ElectricCar class can inherit our Car class.
1
2
3
|
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 do not need to implement any other method because this class has completed the inheritance of the parent class (inherited from the Car class). Let’s prove:
1
2
3
4
|
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
|
Thats beautiful. Original Source.
Other Python Tutorials
What is Python – A Beginners Guide
Advantages of Python Programming