Select Page

## 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.

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

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:

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

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.

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

In Python how can we add elements to a list? We have already said that we can use various methods, in this lesson we will see practical examples.

## Exercise – Python add to list

Populate a list of n elements with the first n multiples of 10. Numbers must be inserted at the end of the list. After insertion, display the values ​​of the list and the relative index in the output.
Then change only the elements greater than 30 by subtracting half the number. Display the list again.

Once n has been acquired, the multiples of 10 to be inserted must be automatically generated.

For example if n = 5 then the list must contain these values:

0 * 10, 1 * 10, 2 * 10, 3 * 10, 4 * 10

So I can assume a constant that is worth 10 and a variable that changes value from 0 to 4.

This last variable can be represented directly by the index i of the for loop.

After having populated the list and visualized the elements with the index (attention, the exercise asks to visualize the list after having inserted all the elements, therefore it is necessary to use another for loop that scrolls the list), we modify the elements greater than 30 removing half of the number.

Finally, after the changes, we display the list again.

Here is a possible solution:

``````
n = int(input('How many numbers do you want to enter?: '))
lista_numbers = []
c = 10

for i in range(n):
lista_numbers.append(i*c)

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

#edit elements greater than 30
for i in range(n):
if lista_numbers[i] > 30:
lista_numbers[i] //= 2

#visualizzo gli elementi modificati e l'indice
for i in range(n):
print('Item in position ', i, ' is ', lista_numbers[i])
``````

## Python add to list – second exercise

Given two numbers, a and b, build a list with an ascending sequence from the first to the second number inclusive. Numbers must be placed at the top of the list. After entering, view the list with its index.
Then modify each element by multiplying it by 2. Finally view the modified list.

N.B. If b is smaller than a the empty list will be displayed.

The initial difficulty lies in using the insert method to insert numbers at the top of the list.

So to insert an ascending sequence that goes from a to b, using insert, I must first insert the highest number, that is b.

This is why it is convenient to simply invert the range of the for.

``````
for i in range(b,a-1,-1):
numeri.insert(0,i)
``````

So if for example a = 5 and b = 10 then I have to output the list of numbers = [5,6,7,8,9,10].

To do this I consider the range with i ranging from 10 to 5 in steps of -1.

The first number entered at the top of the list will therefore be 10, then 9, then 8 and so on.

N.B. Using append I can simply write like this:

``````
for i in range(a,b+1):
numeri.append(i)
``````

But the exercise required the use of inserts.

Then I simply modify the list by multiplying each element by 2.

Here is the complete code:

``````
numbers = []

a = int(input('insert a number'))
b = int(input('insert a number'))

for i in range(b, a-1, -1):
numbers.insert(0, i)

for i in range(len(numbers2)):
print(i, numbers [i])

#modified list
for i in range(len(numbers)):
numbers[i] * = 2

for i in range(len(numbers)):
print(i, numbers[i])
``````

## Conclusions

In this section we have dealt with some exercises on how to add elements to list in Python, in the next lesson I propose others.

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