Prime numbers Python

Prime numbers Python

Let’s create a program on prime numbers in Python using the iterative structures studied so far, in order to deepen them.

So, let’s remember the definition of prime number:

A number is prime when it has only two divisors: one and itself.

So, every natural number greater than 1 that is divisible only by 1 and by itself is prime.

The sequence of prime numbers begins with 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, …

Algorithm for prime numbers in Python

We have, already, implemented this algorithm in C language: prime number in C. Furthermore, also with Algobuild, we have faced the same topic: prime numbers from 1 to 100 with Algobuild and with Scratch: prime numbers from 1 to 100 with Scratch.

Given a number as input, verify that it is prime.

To implement this algorithm on prime numbers in Python, we take a number as input and divide it gradually by numbers smaller than its half. In fact, it is assumed that dividing a number by values ​​greater than its half, the remainder of the division is different from 0.

Also, since all numbers are divisible by 1, we do without even counting it as a divisor.

So, we set the variable div to 2 and increment it from time to time until we get to number / 2.

If the remainder of the division number % div equals zero, then we count the divisors in a counter variable count initialized to zero.

If the variable count remains at 0 then there are no divisors and therefore the number is prime. Otherwise the number is not prime.

We optimize the algorithm by ending the cycle if the divider reaches half of the number taken into consideration but also if the counter becomes 1, so as not to divide unnecessarily and save much more time. This is especially good for very large numbers.

Here is the complete code of the algorithm for prime numbers in Python:


number = int(input('Enter a number:'))
if number <= 1:
    print('You must enter a number greater than 1')
else:
    div, count = 2.0

while div <= number / 2 and count == 0:
    if number% div == 0:
       count += 1
    div += 1

if count == 0:
    print('Prime number!')
else:
    print('The number is not prime!')

If you want, you can test the code in the online Python compiler in that link: Python compiler online.

We will come back again to propose solutions on prime numbers in Python in the next lessons.

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

Python while loop exercises

Python while loop exercises

Let’s improve our knowledge in Python with some while loop exercises.

In particular, today we will face an exercise that also deals with the exchange of variables as a topic.

Python while loop exercises – first exercise

Write a program that, by reading two integers, subtracts the lesser from the greater until their difference becomes less than 3 units, displaying the result of each iteration on the screen.

Let’s take an example by taking 2 values ​​a = 20 and b = 7.

In this case, being a greater than b, we will proceed with these operations:

20 – 7 = 13 is not less than 3 so we continue to subtract

13 – 7 = 6 is not less than 3 so we continue to subtract

6 – 7 = -1 the difference is less than 3, so we stop.

First of all we ask as input the two numbers a and b integers.

Then with a conditional statement we check if a is smaller than b.

If it is true we exchange the values.

Subsequently we store in d the difference between a and b.

Then with a while loop, that continues until the difference is less than 3, we continue to subtract b from a. Therefore, we only establish the major at the beginning of the procedure, after which we continue to subtract.

Python while loop exercises – Here is a possible implementation of the code:


a = int(input('Enter the number a:'))
b = int(input('Enter the number b:'))

if a < b:
    a, b = b, a
d = a - b

while d>3
    print(d)
    d = d - b

We can leave out the case where a and b are equal as the while loop will not be executed anyway.

However, if we want to display an output message that the two numbers are the same then we should add another condition.

Test the code in the online Python compiler online in this link: Python compiler.

Conclusion

Python while loop exercises allow us to learn more confidently how to use iterative structures, in the next lessons we will develop many other exercises.

Some Useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

number guessing game Python

number guessing game Python

In this tutorial we will make the number guessing game in Python, also known as the high-low game.

That is, let’s imagine that the computer thinks a number in a certain interval and we have to try to guess it.

number guessing game in Python – first solution

Guess a number between 1 and 100, but with a maximum of 10 attempts.

To develop the solution we will use some functions.

Randrange() function

First we need to generate a random number.

To generate a random number in Python we can use the randrange() method, which generates a random number in a specified range.

Here is the syntax:

random.randrange(start, end + 1, step) #step is optional

That is for example if we want a number between 2 and 7 we have to set randrange(2,8).

But be careful, to use this method we have to import the library that contains it.

We then use this command:

import random

Therefore, after generating the random number, we can continue to implement our game.

We set the maximum number of attempts to 10 using, as already explained, the range() function.

Then we enter a number between 1 and 100 as input and check with the if statement if this number is the same as the one thought up by the computer. If it is the same then we output the ‘guessed’ message and exit the program with the break function.

Otherwise we check if we still have attempts available. If we have any, we also check if the number we entered is less than the one thought by the computer. If so, we display the ‘higher’ message in the output to suggest entering a higher number.

Conversely, if the number is greater than the number thought up by the computer, we give the ‘lower’ message to suggest entering a lower number.

Finally, if we have run out of attempts, we notify the user with an output message.

Here is the complete code of number guessing game in Python:


import random #import the library
n = random.randrange(1,101) #generate a random number between 1 and 100
for i in range(10):
    x = int(input('Enter a number between 1 and 100:'))
    if x == n: #if you guessed right
        print('You guessed the number attempt:', i + 1)
        break #exit the program
    elif i < 9: # else if we're still in range
        if x < n: #evaluate if the number is lower than what the computer thought
            print ('Enter a higher number')
        else: #evaluate if the number is higher than the computer thought
            print ('Enter a lower number')
    else:
        print ('I\'m sorry, you have run out of attempts')

N.B. We check if i <9 as i becomes equal to 9 only after I enter the last number.

We can try the code in Python compiler online, in that link: Compiler Python online.

number guessing game in Python - second solution

Here is another possible solution to the game.


import random #importiamo la libreria
n=random.randrange(1,101)  #generate a random number between 1 and 100
for i in range(10):
    x = int(input('Enter a number:'))
    if x == n: #if you guessed right
        print('You guessed the number attempt:', i + 1)
        break #we leave the loop
    elif x < n: #if the number is lower than what the computer thinks
        print('Higher')
    else:
        print('Lower')
if x! = n:
    print('I'm sorry, you have run out of attempts, the number was', n)

number guessing game in Python - third solution

In the latter example we do not establish a predefined number of attempts but we exit the cycle only after having guessed the number. we will therefore use an indefinite cycle.


import random
n = random.randrange (1,101)
guessed = 0
while guessed == 0:
    x = int(input('Enter a number:'))
    if x == n:
        print('You guessed it')
        guessed = 1
    elif x < n:
        print('Higher')
    else:
        print('Lower')

As you can see there can be various ways to implement number guessing game in Python. Feel free to propose your solution in the comments below.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Python insert

Python insert

In this lesson, I propose an exercise that still uses the method Python insert.

Python Insert – First exercise

Insert 20 random numbers from 50 to 150 at the top of the list, with the method Python insert. Display the elements with another cycle. Next, modify each element, subtracting the sum of its digits from each number. Finally, display the modified list with another cycle.

That is, if for example I have the following list: random [50,55,80,90….]

So I calculate the sum of the digits for each number:

50: the sum of the digits is 5;

55: the sum of the digits is 10;

80: the sum of the digits is 8;

90: the sum of the digits is 9;

etc…

So the new list at the end of the modification will contain the following elements: random [45,45,72,81,….].

Solution to the exercise on Python insert method

First, I populate the list with random numbers included in the range [50.150] using the Python insert method.

Then I see the elements entered and find the sum of the digits of each number. To do this, ultimately, I have to create an algorithm that, one by one, is able to find the digits of each number and add them to a sum variable.

One procedure could be to divide the number by 10 and then add the remainders.

Let’s take some examples:

sum = 0

50 ÷ 10 = 5 remainder 0, sum = 0 + 0 = 0

5-10 = 0 remainder 5, sum = 0 + 5 = 5

So the total sum of the digits is 5.

sum = 0

55 ÷ 10 = 5 remainder 5, sum = 0 + 5 = 5

5-10 = 0 remainder 5, sum = 5 + 5 = 10

The total sum of the digits is 10.

sum = 0

80 ÷ 10 = 8 remainder 0, sum = 0 + 0 = 0

8-10 = 0 remainder 8, sum = 0 + 8 = 8

etc…

As you can see, the sum variable must be initialized to zero for each number to be evaluated.

Each total must then be subtracted from the initial number, of which a temporary copy must be made, as at the end of the operation its value will be changed.

Here is therefore a possible implementation of the proposed algorithm that uses the Python insert method:


from random import randint

n = 2
random_numbers = []

for i in range(n):
    number= randint(100,1000)
    random_numbers.insert(0,number)

for i in range(n):
    print('Item in position: ', i, 'is ',  random_numbers[i])

for i in range(n):
    s = 0
    temp = random_numbers[i]    #I make a copy of the number
    while random_numbers[i]>0:
        s += random_numbers[i] % 10
        random_numbers[i] //= 10    
    random_numbers[i] = temp-s

for i in range(n):
    print('Item in position: ', i, 'is ', random_numbers[i])

Try it in the editor:

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Python for loop examples

Python for loop examples

In this Python lesson we will give some for loop examples, in order to better understand how it works and develop logical thinking.

Python for loop examples – first example

Design an algorithm that writes all pairs of numbers that give 60 as a product.

The solution is to use a for loop to find the divisors of 60, so for each divisor we also find the quotient.

In fact, let’s recall how the terms of the division are called by giving an example:

60:3 = 20

So 60 is called a dividend, 3 is called a divisor, and 20 is called a quotient. This means that if I multiply the quotient obtained by the divisor I get the dividend. In fact in this specific case we have: 20 * 3 = 60.

Then we initialize n to 60.

After we set the range with the index i must start from 1 as otherwise there would be a division by zero and this is not possible and it stops at n + 1 because we have to divide by 60 if we want to find all the pairs.

Then, doing this operation n% i == 0 we check if the remainder of the division is zero. If it is true it means that i is the divisor, so we find the quotient.

Finally we print the pairs.

Here, then, is the algorithm that uses the for loop in python to find the pairs that give 60 as a product:


n = 60

for i in range (1, n + 1):
    if n% i == 0:
        q = n // i
        print ('Pair', i, 'e', ​​q)

You can try the code in Python compiler online in that link: Python compiler.

Let’s carry out some algorithm steps to explain it better.

n = 60

Python for loop examples – Step by step explanation of the algorithm

First step:

for i in range (1, n + 1): # i = 1

    if n% i == 0: # 60% 1 == 0 is true

        q = n//i  #troviamo il quoziente cioè q=60//1=60
        print(‘Pair ‘,i,’ and ‘,q)  #Print the first pair, that is: i=1 and q=60

Second step:

for i in range (1, n + 1): # i = 2

    if n% i == 0: # 60% 2 == 0 is true

        q = n // i # we find the quotient that is q = 60 // 2 = 30
        print (‘Pair’, i, ‘and’, q) # We print the second pair:  i = 2 and q = 30

Third step:

for i in range (1, n + 1): # i = 3

    if n% i == 0: # 60% 3 == 0 is true

        q = n // i # we find the quotient that is q = 60 // 3 = 20
        print (‘Pair ‘, i, ‘ and’, q) # We print the third pair: i = 3 and q = 20

And so on until the last step where we will divide the number by itself.

Python for loop examples – second example

Prints the first N odd numbers following the number A.

We take as input the number to start from, that is A and the quantity of odd numbers to be displayed following A.

ES: We insert N = 5 and A = 6.

So the next 5 odd numbers of A that we need to visualize are: 7, 9, 11, 13, 15.

Then the index i of the for must start from 7 and end at 15. From 7 to 15 there are 2 * N -1 (9) numbers of which 5 are odd and 4 even.

Another example: We insert N = 3 and A = 7.

So the next 3 odd numbers of A that we need to visualize are: 9, 11, 13.

Then the index i of the for must start from 9 and end at 13. From 9 to 13 there are 2 * N -1 (5) numbers of which 3 are odd and 2 even.

Looking at the examples above, to avoid creating two for loops, we execute an if and if A is even we make it odd, if A is odd we increment it by 2.

Then we create a for loop that initializes the index i to A, as it represents the starting number and increases the value of A by 2 until reaching the sum of A plus double the required numbers.

So just simply print the index to get what the algorithm requires.

Here is the complete code using the for loop in Python:


N = int(input('How many numbers to display?: '))
A = int(input('Enter the value to start from: '))

if A % 2 == 0:
    A += 1
else:
    A += 2

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

These are just a few examples of the for loop in Python, we will do some more in the next lessons.

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