Number Guessing Game in Python

Waqar Ali Siyal
4 min readOct 6, 2020

--

In this article, I will be showing you how to develop a number guessing in python.

The first thing you need to do is to import random module because we are developing a number guessing game so it’s obvious that we need to generate a random number to be guessed by the user. So, Lets generate a random number in range 1 to 10 and store it in a variable named number. We will allow the user three times to guess a number (i.e. the user can have three tries to guess a number). Therefore, define a variable tries which has initially 0 in it and later we will store number of tries used in it.

Now, move forward and take some input from the user like ask his/her name and say/print ‘Hello! username’ or you can print any message just to make this game a little interesting. And, also ask from the user his/her choice that whether he/she wants to play or not. We will show only two options ( Yes and No) to be chosen by the user and we will store the selected option inside a variable named option and we will convert it to an integer.

Note: strip() method is used to remove spaces from left and right of the name.

Now, we will check what is inside the option variable. If the option is equal to 1 then we will apply our game logic (i.e. allow the user to play a game) and if the option is equal to 2 then you can print any message in my case I am printing ‘Thank you!’. For other input/option/choice, you can print any message in my case I am printing ‘Invalid Option!’.

In the first condition where option is equal to 1 we will write our game logic. Now, print these two messages:

And, take the input from the user (i.e. ask user to guess a number) and store it in a variable named guess. Convert the guessed number into an integer because the number which we have generated above is an integer and we will compare the guessed number with the randomly generated number so both the variables guess and number should contain integer values. Add 1 to the existing value of tries variable and check if the guessed number is greater than the random number then we will print ‘Guess Lower…’ and if the guessed number is smaller than the random number then we will print ‘Guess Higher…’. Now, use a while loop with a condition that if the random number is not equal to the guessed number and tries is less than 3 then the loop will be executed and we will give user another try to guess a number and repeat the same steps. Now, what if the guessed number becomes equal to the random number which means that the user has won the game so we will just print ‘You Won!!’ and also print the number of tries and in other case we will print ‘You Lost!!’.

Here is the complete code:

If you want to watch a video to understand all the things then follow my you tube tutorial: Number Guessing Game in Python

--

--

Waqar Ali Siyal

Microsoft Learn Student Ambassador ❤️ | Mobile App Developer 💻 | Muetian ✨ | Technical Blog Writer ✍️