Python examples

Python Examples – In this lesson we will do other examples in Python using the for loop.

We therefore propose some algorithms to better understand the meaning of the iterative construct.

Python Examples – First example in Python

Write the numbers from 1 to N by skipping multiples of 3.

So we ask to take a number N as input, then we use a for loop with range from 1 to N + 1.

Within the cycle, if the index i is not divisible by 3, we print the number, otherwise we do nothing.

So here is a possible resolution.


N = int(input('Insert N: '))

for i in range(N+1):
    if i%3 != 0:
        print(i)

Python Examples – Second example

Given a number n write the first ‘n’ squares of the integers.

For example if n = 5 the first 5 squares are 1, 4, 9, 16, 25.

As usual, we ask the user to enter an internal number N. After with a for loop with index i in the range between 1 and N + 1, we calculate the powers and display them.


N = int(input('Insert N: '))

for i in range(1, N+1):
    i **= 2
    print(i)

Python Examples – Third example

Given two numbers m and n, write, count and add the numbers that are divisors of both.

Example with m = 20, n = 30 1 2 5 10 count 4, sum 18

So we take m and n as input and initialize the variables c and s to 0.

The variable c represents the divisor counter, while s represents the sum of the divisors.

After with a for loop with i in the range 1 and m + 1, we divide m and n by i and, only if both verify the divisibility criterion set, we print the values of i, we increment c and we add the divisor to the variable s.

Finally we display the values of c and s.

Here is the complete code:


m = int(input('Insert m: '))
n = int(input('Insert n: '))

c = s = 0

for i in range(1, m+1):
    if m % i == 0 and n % i == 0:
        print(i)
        c += 1
        s += i
        
print('The common dividers are in total: ', c)
print('The sum of the divisors in common is: ', s)

In doing so, however, if for example m = 30 and n = 20 then we will divide 20 by 30 and this does not make sense then I could stop setting a range at the minimum value between the two. For example:


m = int(input('Insert m: '))
n = int(input('Insert n: '))

c = s = 0

for i in range(1,min(m,n)+1):
    if m % i == 0 and n % i == 0:
        print(i)
        c += 1
        s += i
        
print('The common dividers are in total: ', c)
print('The sum of the divisors in common is: ', s)

I could also calculate the minimum of the two numbers before the for without using the minimum function.

These were just some Python examples, in the next lessons we will see other applications.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *