Python 3


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)

PAGE 1 / 1
Guess the Number!
Home >>> Online Lessons, Python 3

The program generates a hidden random number between 1 and 10, and the user is invited to guess this number. If the number is not guessed correctly from the keyboard, a corresponding hint message is displayed - "lower" or "higher".

Solution. We will generate the random number – it's simple. Then, since we do not know how many times the loop will execute, we will definitely use the while statement. Its logical expression is evident – the entered number is either equal to or not equal to the randomly chosen one. We just need to add an if... in case the number is not guessed correctly!

Let's see the program:
Editor -

Note: this program cannot be run online; it should be executed in Python IDLE on your computer.

The first attempt (reading from the keyboard) is made before the while loop because we need an initial number to compare in the logical expression. If the number is guessed correctly on the first try, the final congratulations message is displayed directly. If not, a new number is read inside the while loop.

I have styled the program a bit (user-friendly) and chosen numbers between 1 and 100, as shown below:

You can download the source code from [here].


Add a variable that keeps track of and displays the number of attempts made by the user at the end!
 home   list  CONTENTS   perm_identity   arrow_upward