Coding STEM

A Guessing Game in Python…

Let’s play a simple number guessing game! Then, let me show you how to program the game in Python. Nothing fancy…but core logic here.

Gameplay:

Here’s a sample output of the screen. Computer (AI) guesses a number (1-20 inclusive) and you guess the number via tries. Computer tells you each time if you’re “hot” or “cold”. That’s your hint. Simple!

Explanation:

Note that the program keeps track of number of your guesses and gives you hint along the way. So…how do you code it in Python???

The Code:

Actually, to keep the game easy I set a limit of 10 number of tries. I also set a range of numbers for AI to pick from by this statement:

number = random.randint(1, CEILING) #where CEILING is set to 20 but it's up to you!

Now, number variable contains the AI-picked random number in that range. Then I get user input (i.e. name) via this line of code:

name = input("What's your name?\n");

Now the input is saved in array 0 position…technically as {0} in Python. So, now your code can say:

print ('Hi {0}! Let us begin!'.format(name)) #or however you choose to greet :)

Then the next thing is your loop…in this case, I use While loop (you could use For loop too as long as you know the difference which are explained anywhere online)…this way:

while guesses_made < 10:
  • ….do stuff

Remember, I set a limit of tries to 10? Yes, so guesses_made is the variable that keeps track of number of inputs and compares to 10.

“Do stuff” is the key here…you need to get the number entered by user and store it in a variable, then compare with the number guessed by AI. Then indicate if it’s spot-on, too low, or too high…up to how many times?…right! 10 in this case.

So a sample, complete code might look this:   

Exercise:

  • Play with the range and dialog texts.
  • Can you change the number to guess to a word to guess? (HINT: int vs string)

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top