The best way to solidify concepts is to practice. These exercises cover functions, loops, and conditionals using a classic problem: finding prime numbers in a range.
Running the program
Save the code in a file named primes.py and run it from the terminal with:
python primes.py
Function to check if a number is prime
A number is prime if it’s only divisible by 1 and itself. The function iterates through possible divisors:
def es_primo(num):
if num == 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
Loop to find primes in a range
We use a for loop with range(inicio, final + 1) to iterate over all numbers:
def busca_numeros_primos(num_inicio, num_final):
for num in range(num_inicio, num_final + 1):
if es_primo(num):
print(num)
total_numeros_primos += 1
Measuring execution time
The timeit module lets you measure how long the program takes:
import timeit
inicio_tiempo = timeit.default_timer()
# ... code to measure ...
fin_tiempo = timeit.default_timer()
print(fin_tiempo - inicio_tiempo, "seconds")
Threading version
To speed things up, we can split the range into two halves and process them in parallel with threading.Thread:
num_mitad = int(((num_final - num_inicio) / 2) + num_inicio)
hilo = threading.Thread(target=consulta_primos, args=(num_inicio, num_mitad))
hilo.start()
hilo.join()
