Programming tutorials EP04 : Coding a guessing game in python

jimah1k(65)
Published in
DIYHub
Words
493
Reading
3 min
Listen
Play
4y

Greetings guys,

I’m back again with another edition of my coding tutorials. On my last episode I designed a countdown timer code. Today I be coding something fun a guessing game you can play with friends at home or at your leisure time. Let’s get straight into business.

The very first step in generating this code is to import the random. Since we are going to be dealing with generating secret numbers, we will define the function secret number. After which we will use the random.randint to help generate the random secret number known to know one but the computer. I decided to use the parameters (1, 100) to limit the game. You can change the parameters if you like.

The second aspect of the code is to define and set the function guess to None. Most people confuse none to the function false or “”. False is a Boolean value whiles “” is an empty string. Now I want to write the code such that the code is able to tell us the number of guesses the users made before they finally got the right answer. So because of that, we have to define the function number_gueses and set it to 0.

The third phase of the will require us to use a whole loop such that we will be able to tell the user if the number he guessed is too high or too low but before we can do this we need to take input from the user, and we do this by entering “int(input(“guess a number from 1 to 100)). Incase a user enters a number above 100, there should be something that will prompt the user that that number is not correct. To do this, am if clause is added.

The fourth phase is kinda joint to the third one. Whereas we would have to define a function num_gueses += 1. Now we can insert the if clause so that whenever we enter a number the computer will tell the user if it’s too high or two low.

Now the final piece of the code, to ask the computer to print “Congratulations you guessed the secret number in 10 number of gueeses”. Now let’s see the out out of this code.

When we run this code, we will be asked to enter a number from which I entered 60 and this was the out output;

It returned as too high, so I entered 50 as my next number and I got the same response;

I kept on entering reduced numbers and kept on getting the same response untill I entered 3 after which this was printed out;

This means that the secret number was 3. And I received the congratulation you guessed the secret number in 9 guesses. It’s a very simple code and I hope you guys try your hands on it. And I would love to hear from you and see you on the next one. Thank you.

Programming tutorials EP04 : Coding a guessing game in python | Ecency