Python programming course using Linux. Part twelve.

Programming in Python using Linux

As we said in the previous post of this course Python programming using Linux, When we need a program to run continuously, we can use loops. These repeat the execution of code as long as one or more conditions are met.

We had left the previous article explaining the usefulness of the instructions break y keep on going.

Python programming course using Linux

Using the break and continue instructions within a loop

Using the break and continue instructions within a while loop, we can stop the execution of the code inside the loop, either partially or completely.

Let's take a detailed look at what this code does:

intentos = 0

Create the variable "attempts" to keep track of how many valid logins the user made. Set its value to 0.

while intentos = 5

It states that the loop must be executed 5 times unless it encounters the break instruction.

distro = input(f"Intento {intentos + 1}/5 - Escribí una distro: ")

It prompts the user to enter the name of a distribution and assigns it to the variable `distro`. To avoid confusing the user, it displays what the counter would show as attempt 0 as attempt 1.

if distro == ""

Check if the user pressed Enter without typing anything.

print("No escribiste nada, no cuenta como intento.")

It notifies the user that they haven't written anything

continue

Restart the loop without adding any attempts.

intentos += 1

If the user typed something, it adds one attempt to the counter.

if distro == "Ubuntu"

Check if the user typed "Ubuntu"

print(f"¡Correcto! Adivinaste en {intentos} intento(s).")

Indicate whether the answer is correct and how many attempts were needed.

break

Since the user was correct, it stops the loop.

else:

Since the condition of less than 5 attempts is no longer met, the alternative applies.

print("¡Se acabaron los intentos! Era Ubuntu.")

The message is printed that the attempts have run out and that the distro was Ubuntu.

The for loop

The while loop is useful when we want a program to repeat until a certain condition is met. But If we want to execute a loop, for example by displaying all the elements of a list, and that list has a variable number of elements, the instruction will be more useful. for.

The syntax is as follows:

for variable in secuencia

The for loop works with a sequence that can be a list, a string of text, or a numeric range.
 and it traverses it in its entirety, executing the same block of code for each of the elements in the sequence.

This is an example:

Using the for loop in Python 3

This example shows the message set for each of the items in the list.

Break

The instruction break stops the loop execution before the end of the sequence is reached.

The break statement in a for loop

In this case, the break instruction stops the for block when the desired result is found.


distribuciones = ["Ubuntu", "Debian", "Linux Mint", "Arch Linux", "Fedora"]

Create a list of distributions

distro_a_buscar = "Debian"

It states that the Debian distribution will be sought.

for distro in distribuciones

It sequentially assigns each element of the list to the distro variable.

print("Buscando...")

Displays the search message at the beginning of each attempt.

if distro == distro_a_buscar

Check if you found the distribution you were looking for.

print("Distribución encontrada:", distro)

It gives the message that the searched distribution was found and prints what the name is.

break

Stop the loop.

print("Fin de la búsqueda.")

It displays the search completion message, which it would also do even if the searched distribution was not found.

Continue

The `continue` instruction works similarly to the `while` loop. When Python encounters it, it skips to the next element in the list, ignoring the remaining code. This is useful when the current element doesn't meet a condition, but we still want the loop to continue executing.

This is an example:

Using the continue instruction in a for loop.

The continue instruction, in a for loop, just as in a while loop, stops the execution of the current code and moves on to the next element in the list.

distros = ["Ubuntu", "Debian", "arch linux", "Fedora", "Linux Mint"]

Create a list of 5 Linux distributions. The lowercase "arch linux" is intentional.

for distro in distros

Iterate through each element of the list, assigning it in turn to the variable distro.

if distro[0].islower():

Check that the first letter of the distribution is capitalized.

print(f»'{distro}' does not start with a capital letter,»)

It notifies the user that the distro does not meet the condition of starting with capital letters and that it will continue with the next one:

keep on going

Since the condition is not met, it moves to the next element of the loop.

print(f"* {distro}")

Print the distributions that meet the condition of starting with a capital letter.

Range

The range function is used in conjunction with the for loop to generate number sequences.

range(inicio, fin, paso)

Where:

  • Home: Number where the sequence begins. Default is 0
  • End: It is the number where the sequence ends without including this value.
  • Paso:  It is the interval between each number in the sequence. By default it is 1.

Suppose we have this instruction:

for i in range(4):

Since by default it starts from 0 and uses the range 1, the instruction:

print(i)

It will print the numbers from 0 to 3.

Whereas if we define the loop:

for i in range(4, 10):

print(i)

It will display all the numbers from 4 to 9

While the loop:

for i in range(3, 21, 3):

By doing:

print(i)

It will show

3

6

9

12

15

18

We can also generate the sequence of numbers in descending order:

for i in range(21, 3,- 3):

It's possible to use `range` to enumerate the elements of a list. It would look something like this:

Using range to enumerate items in a list

Range can be used to enumerate the elements of a list, although Python 3 has its own command for that.

Let's look at the program in detail

distros = ["Ubuntu", "Debian", "Fedora"]

Create a list of three distributions.

len(distros)

Determine the number of items in the list.

range(len(distros))

It sets the number of items in the list as the upper limit for range.

for i in range(len(distros)):

Start going through each of the items on the list.

print(f"{i} - {distros[i]}")

Prints the index and the list item.

However, this can be done more easily with:

for i, distro in enumerate(distros)

In the next article we will continue with the features of Python