Everything you need to know to get started in Python

In this section, we are going to give an introduction to Python; you can take this section as reinforcement for the development of the framework that we will do in the next section.

It is important to note that this section is a reinforcement and not a introduction to programming, therefore, it is assumed that the reader has at least basic knowledge of programming and Python in general.

Interactive console/Python console

The first tool that you can use when developing in Python is the interactive console, once Python is installed on your computer and the environment variable has been configured so that it can be used through the terminal, by opening a CMD or Terminal and writing:

$ python
Los caracteres de:
>>>

They indicate that the console is waiting for you to type something, and they are not characters that you should type when performing the various tests that we will do in this section.

You will see that the console is active, ready to perform the first tests with Python, from here you can create variables, functions, lists, classes, etc., all for testing purposes, and this tool is ideal for when you want to introduce development in the language. or perform some tests with a script.

For example, if you type a number, you will see the output on the screen:

>>> 6
6
>>>

Or a text:

>>> hello world
hello world
>>>

In short, you can take the Python interactive console as another tool that you have easily available for testing.

Python files

The traditional way to develop in any programming language is through a file that is then compiled or interpreted, as in the case of Python, you can create a folder in any location on your computer that we will call:

C:\Users\andres\Escritorio\proyectos\python

From here we will develop the different scripts that we will see in this section.

We will create a file called:

test.py

In the case of this writing, we place the file in the previous location on the desktop and from here, we will do a hello world:

C:\Users> cd C:\Users\andres\Escritorio\proyectos\python

The print() function allows you to print a text through the terminal or CMD and is a tool that we will use greatly to quickly debug when developing the different functionalities of our application, so, following our example we put:

test.py

print("hello world")

And to execute, from the terminal and without running the interactive Python console, we execute:

$ python test.py

And we will see through the console:

hello world

You can also run the above content from the interactive Python console:

>>> print("hello world")
hello world

In this section, you can decide when to use one or the other depending on your preferences.

Variables and data type

The first thing we must know in any programming language is the use of variables to store data and data types, which are the primitives in any programming language. In Python, we can store numbers and text strings or strings; specifically:

  • Text Type: str
  • Numeric Types: int, float, complex
  • Sequence Types: list, tuple, range
  • Mapping Type: dict
  • Set Types: set, frozenset
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview
  • None Type: NoneType

Python is not a language in which we must enter the data type when declaring the variable, it is dynamically typed, which means that Python infers it when initializing a value:

n = 5

Otherwise, as in JavaScript, the type is inferred based on the declared value; if it is an integer:

n = 5

If it is a float:

n = 5.2

Or a String:

t = 'text'

A boolean:

b = True

In python, we have a function called type() with which we can ask the data type:

>>> t = 'text'
>>> type(t)
<class 'str'>

Or to measure the length:

>>> t = 'text'
>>> len(t)
4

Mathematical operations

The mathematical operations do not change at all if we compare them with other programming languages, regardless of whether the result to be operated is stored in a variable, or is a fixed value or returned from a function or similar:

>>> a = 5
>>> 4 + a
9

We can always perform mathematical operations:

>>> a = 5
>>> 4 + a
9
>>> 4 - a
-1
>>> -4 + a
1
>>> 4 / a
1.0
>>> 4 % a
4
>>> 4 * a
20

String concatenation

Many times we have two or more Strings and we want to convert them into one, for that, we must concatenate the texts, for that, we use the same operator as the addition operator or sum seen previously:

>>> name = 'andres'
>>> surname = 'cruz'
>>> name+surname
'andrescruz'

Here you can see that with the same operator + vary data type, the operation is different.

Castings

We can also convert between data types, to do this, you just have to use functions like int(), str(), float() to cast the data to the corresponding type; for example, from an integer to a float:

>>> n = 5
>>> float(n)
5.0

From a float to an integer:

>>> n = 5.2
>>> int(n)
5

A number to a boolean:

>>> n = 5
>>> float(n)
5.0
>>> n=5
>>> bool(n)
True
>>> n=-5
>>> bool(n)
True
>>> n=0
>>> bool(n)
False
>>>

If we try to cast a value that is not valid, for example from a string to a number, it will give an exception:

>>> int('50.X')
ValueError: invalid literal for int() with base 10: '50.X'

Lists

Lists are nothing more than a collection of data, when you enter applications like X, Whatsapp or an email like Outlook or Gmail, and you see a list of emails or messages, structures such as lists are used, therefore, lists are a most used structure in which we can define the primitives as seen before or objects as we will see in the classes section:

>>> list = [1,2,3]
>>> list
[1, 2, 3]

To operate with these lists, we also have operations to know their length:

>>> len(list)
3

Or to add all the elements in the list:

>>> list = [1,2,3]
>>> sum(list)
6

Or to add all the elements in the list:

>>> list.append(5)
>>> list
[1, 2, 3, 5]

Or remove an element by value (not index):

>>> list.remove(1)
>>> list
[2, 3, 5]

Get a value from the list, we place the index starting from zero:

>>> list = [1,2,3]
>>> list[1]
2

If we place an index that does not exist, it will give an exception like the following:

>>> list = [1,2,3]
>>> list[3]
IndexError: list index out of range

There are many other operations that you can use on lists and that you can consult in the official documentation.

https://www.w3schools.com/python/python_lists.asp

From the framework, when we have a list of users or posts it is precisely that, a list of objects that we can then iterate in a loop or some similar operation.

Conditionals

The use of conditionals to execute blocks of code based on a true and false condition and with this, making branches in our code are one of the most used structures in any program in and in frameworks is no exception; in a conditional, we can evaluate based on operators like:

  • > Returns True if the left operator is greater than the right operator
  • < Returns True if the operator on the right is greater than the operator on the left
  • >= Returns True if the left operator is greater than or equal to the right operator
  • <= Returns True if the operator on the right is greater than or equal to the operator on the left
  • == Returns True if both operands are equal
  • != Returns True if both operands are not equal

True and false conditions and if the condition to be evaluated is true, then the code block that governs the conditional is executed:

age=15

if age >= 18:
    print("You're of age")

We can make complex conditions by nesting several conditions with the and:

age=15
woman=False
if age >= 18 and woman:
    print("You are a man of legal age")

Where all the conditions must be met to execute the conditional block, or the or, to execute the conditional block if only some of the conditions are met:

age=19
woman=False
if age >= 18 or woman:
    print("Message 1")

age=15
if age >= 18 or woman:
    print("Message 2")

age=15
woman=True
if age >= 18 or woman:
    print("Message 3")

We also have the else block that would be executed when the conditional condition is not met:

age=19
if age >= 18:
    print("You're of age")
else:
    print("You are a minor")

And we can evaluate multiple conditions or nest multiple conditionals:

age=19
woman=False
age=19
if age >= 18:
    print("You're of age")
elif woman:
    print("You're a woman")
else:
    print("You are a men")

Loops

As in any programming language, we have access to loops to be able to iterate lists; we have the while, with which a block is executed until the condition is met:

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

And the for loop, in which we have a variable that maintains the value of the structure to be iterated, in each iteration:

numbers = [1,2,3,4,5]
for i in numbers:
  print(i)

A common configuration is to use the for loop together with the range() function, which allows creating a range like the following:

for i in range(0,10):
   print(i)
0 1 2 3 4 5 6 7 8 9

And in this way, the variable i corresponds to an element of the range to be iterated.

Classes

One of the most important aspects of programming languages are classes, the use of classes in certain programming languages such as Python, are what define a programming language as an “object-based programming language” where the objects are nothing more than instances of the classes, previously when we presented the data types, when printing the type, we saw an output like the following:

>>> n=5
>>> type(n)
<class 'int'>
>>> name='andres'
>>> type(name)
<class 'str'>
>>> type(True)
<class 'bool'>

You can see that the reserved word class is present, and this is because in Python everything is an object that is nothing more than an instance of a class:

class MyClass:
  pass

Classes are nothing more than a plane in which we can create all types of objects that represent the real world, such as their primitives, integers, floats, text strings or, for example, we can create a class that represents a car:

class Car:
  pass

Or an animal:

class Animal:
  pass

As you can see, in both cases the reserved word class is used to mark that code as a class.

An empty class is not of much use to us, to make it functional, we can define variables and functions within the classes, when variables and functions are defined within a class, these are called attributes and methods respectively:

class Car:
  brand='MyBrand'
  model='MyModel'
  price=50.2
  
  def getCompleteDescription(self):
    return f"{self.brand} - {self.model} - {self.price}"

The reserved word self refers to the instance of the class with which its attributes and methods can be accessed.

For the previous code, we can create an instance, which is nothing more than a variable which we can manipulate as we wish, for example, create an instance for some type of car that we are going to manipulate in an application:

>>> car = Car()

And with this, access its methods and properties:

>>> print(car.brand)
>>> print(car.getCompleteDescription())
MyBrand
MyBrand - MyModel - 50.2

Methods and properties are the way we customize the class, for example, to change brands:

car = Car()
car.brand='OtherBrand'
print(car.brand)
print(car.getCompleteDescription())

Or use the constructor method of the class, which would be the __init__() method in which the arguments are supplied:

class Car:
  # brand='MyBrand'
  # model='MyModel'
  # price=50.2
  
  def __init__(self,brand,model,price):
    self.brand=brand
    self.model=model
    self.price=price
  
  def getCompleteDescription(self):
    return f"{self.brand} - {self.model} - {self.price}"
    
car = Car('OtherBrand','OtherModel',100)
# car.brand='OtherBrand'
print(car.brand)
print(car.getCompleteDescription())

When using the class constructor, it is not necessary to define the arguments from the class, they are created automatically from the constructor.

Inheritance

Podemos crear clases que se relacionen, por ejemplo, podemos tener una clase animal y de la misma, poder emplearla como base para crear clases específicas, por ejemplo, una clase perro y gato:

class Animal:
      def __init__(self, kind):
        self.kind = kind
        
      def legs(self):
          pass
            
      def fly(self):
          pass
            
      def type(self):
          print(f"The type is {self.kind}")
            
class Dog(Animal):
    def legs(self):
            return 4
            
    def fly(self):
        return False

    def other(self):
        print("To Do")
        
class Bird(Animal):
    def legs(self):
            return 2
            
    def fly(self):
        return True
    

dog = Dog('canine')
dog.type()
bird = Bird('bird')

In the previous example, we have an Animal class that has common characteristics for an animal, then, we create two classes Dog and Bird to represent dogs and birds, which are animals and therefore, they inherit from the Animal class and with this their attributes and methods, which are overridden and we can even implement custom methods and attributes like other() that are not part of the Animal class.

The use of classes and inheritance is fundamental in frameworks since there are classes predefined by the framework to define models, controllers/views, among other types and which can then be customized while preserving the default behavior.

Modules in Python

Modules in Python are a crucial part of the programming language and what differentiates it from other programming languages and what allows Python to be a modular programming language that takes advantage of the frameworks implemented in said language.

Modules allow you to easily reuse code between other files that correspond to the project.

A module in Python is nothing more than a file with a .py extension that can contain a set of functions, variables or classes that we can then use from other files that import said module.

Modules can use other modules, which facilitates code reuse and modularization of the application.

Create a module

We will create a file to handle the math operations:

mymath.py

def sum(a:int, b:int):
  return a+b
  
def subtract(a:int, b:int):  
  return a-b
  
def multiply(a:int, b:int):  
  return a*b
  
def divide(a:int, b:int):  
  return a/b

Import a module

Using import, we can import all the content of the module defined above:

app.py

import mymath 

print(mymath.sum(1,2))

Or we can also import specific components:

from mymath import sum, divide, multiply, subtract

print(sum(1,2))

We can even import the entire module using *:

from mymath import *

print(sum(1,2))

And in this way, we can reuse the math operations module from anywhere in the application.

The modules are a fundamental part of the frameworks, which, being organized in several folders according to the layers defined to represent each of the components of the MVC or MTV, the management of routes, among others, the way to unite all these layers is through modules that are important in specific parts of the framework

Modules are also used in frameworks to import the different characteristics of the framework and associated packages and be able to use them.

- Andrés Cruz

En español

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 3d 03:18!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!