Python programming course using Linux. Part 6

Microsoft uses Python to create scripts in its applications.

We are doing a short Python programming course using Linux. This cross-platform programming language is ideal for getting started in the world of programming.and continue to be used as we acquire advanced knowledge because it is also useful for creating more complex applications.

Currently, Python is the preferred language for use in applications in Data Science, Artificial Intelligence, and even Microsoft itself is using it to replace its own macro language in the Excel spreadsheet.

Python programming course using Linux

In the previous post, we discussed the parameters of the `open()` command when working with files. Depending on the file type, it's advisable to tell the Python interpreter how to handle special characters that indicate line breaks.

open("archivo.txt", newline=None) Transforms \r\n and \ra \n (default)
open("archivo.txt", newline="") It makes no transformation
open("archivo.txt", newline="\n") It only performs a line break when it detects the special character \n (Used by Linux)
open("archivo.txt", newline="\r\n") It only performs a line break when it detects the special character \r\n (Used by Windows)

To summarize the parameters of the open() instruction

    • File: Indicates the file name (if it is in the same folder) or the path where to find it.
    • Mode: Optional parameter, indicates whether the file is opened in read mode, write mode, both, and whether the content will be erased when new content is written.
    • Buffering: Optional parameter, determines the size of the memory buffer.

<li>Encoding: Optional parameter. Specifies the text encoding; by default, the operating system's encoding is used. Very useful if you are developing applications for others that use special characters.

  • Bugs: This parameter specifies how to proceed if coding errors are detected. It is also optional.
  • Newline: Determines how to handle line breaks. It is also an optional parameter.

Let's look at the following program

class Sistemas:

We define the Systems class that will be used to create the objects that will represent the operating systems.

def __init__(self, nombre, version, derivada):

We start the constructor and set the parameters.

self.nombre = nombre
self.version = version
self.derivada = derivada

These 3 lines will take the values ​​as they are entered and store them in the object.

def mostrar_info(self):

It defines how the data will be displayed.

print(f"Nombre: {self.nombre}")
print(f"Versión: {self.version}")
print(f"Derivada: {self.derivada}")
print("-" * 20)

Print the parameters and at the end of each group print scripts.

nombre = input("Nombre del sistema: ")
version = input("Versión: ")
derivada = input("Derivada: ")

Here the user is instructed to enter distribution data.

with open("sistemas.txt", "a") as archivo:

This command checks if a file called sistemass.txt exists, creates it if it does not exist, and appends the data to the end of the existing files.

archivo.write(nombre + "\n")
archivo.write(version + "\n")
archivo.write(derivada + "\n")

Prints stored data with a line break.

with open("sistemas.txt", "r") as archivo

Open the file in read-only mode.

lineas = [linea.strip() for linea in archivo.readlines()]

This instruction reads all lines of the file and removes the special characters that indicate a line break.

sistemas = []

Create the empty list where the objects to be rebuilt are stored.

for i in range(0, len(lineas), 3):

It generates series of numbers in groups of three. This is because 3 parameters are stored for each instance of the operating systems object.

Let's assume we have 3 systems (9 parameters)

range(0, 9, 3) → 0, 3, 6

i=0 → lines 0, 1, 2 → first system
i=3 → lines 3, 4, 5 → second system
i=6 → lines 6, 7, 8 → third system

if i + 2 < len(lines):

This is for security. A group is checked to ensure it has 3 parameters before performing the reading. If there isn't a group of 3, the reading is not performed.

Program that reads files and adds data

Python offers several options for reading and writing files.

Create the Systems object

work = Systems()

Incorporate the data from the corresponding lines.

lines[i],
lines[i + 1],
lines[i + 2]
E.g.

i=0:
lines[0] → «Ubuntu» → name
lines[1] → «26.04» → version
lines[2] → «Debian» → derivative

i=3:
lines[3] → «Manjaro» → name
lines[4] → «44» → version
lines[5] → «Arch Linux»→ derivative

i=6:
lines[6] → «Linux Mint» → name
lines[7] → «22» → version
lines[8] → «Ubuntu» → derivative

sistemas.append(sistema)

Add the newly created object to the Systems list. The loop ends when all the reconstructed objects from the file have been added.

for s in sistemas:

Browse the newly created file.

s.mostrar_info()

Call the method to display the parameters of each object.

Up until now, we've been just winging it, using instructions whose purpose we don't fully understand. It's time to take care of them.

Basic mathematical operations with Python

The following mathematical operations can be used in programs created in Python.

  • Sum: a = 5 + 3 Assign the value 8 to the variable
  • Subtraction: b = 10 – 2 Assign the value 8 to the variable
  • Multiplication: c = 4 * 2 I bet you can't guess the value of the variable!
  • Division: d = 5 / 3 Assigns the value 1,6666 to the variable…
  • Division without decimals: e = 21 // 7 Result in 3.
  • Calculating the remainder of the division: f = 5 % 3 Assign the value 2 to the variable.
  •  Power: g = 2 ** 4 Assigns the variable the value 16.

It is possible to perform more complex operations, but it will be necessary to introduce the concept of module, which we will discuss later.

Variables

Both in the example programs we used and in the list of mathematical operations we just provided, we used variables. Variables are containers in which data is stored. This data can be entered by the code or externally, modified, and displayed when needed. Unlike other programming languages, in Python it is not necessary to declare the type of each variable before using it.

A variable is declared like this

Nombre = "Diego"

Where name is the name of the variable and the text in quotes to the right of the equals sign assigns the value Diego.

It is possible to assign values ​​to different variables in a single line of code

name, surname, age = «Diego», «González», 55

Rules for naming variables

  • Allowed characters: While letters, punctuation marks, and underscores can be used, the name must always begin with a letter or an underscore. It doesn't matter whether the letters are uppercase or lowercase.
  • Case sensitive: The system differentiates between words written in uppercase or lowercase, so they must be written exactly as they were declared.
  • Reserved words: There are a number of words that cannot be used because they are reserved by the interpreter.

The reserved words are:

False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield match case
In the next article we will continue with the components of the Python programming language

Python is a very popular programming language.
Related article:
Python Programming Course Using Linux Part Five