Guessing game - Python
For this project I want to write a program that does the following:
- Asks the player to input their name.
- Generate a random integer from 1-20.
- Ask the player to input their guess.
- Tell the player whether their guess is too high, too low, or correct.
- End the program when the correct guess is made or when the player runs out of guesses.
Like I mentioned yesterday, this is a great first test for new programmers because it seems to simple but it asks them to do so much.
Ok, let's jump into the Python version of this game.
There's a reason Python is an incredibly common first programming language. It's very simple and straightforward. The syntax is very approachable, there are great functions built in already, tons of libraries to further simplify things, and the code, especially with a good IDE, is readable.
So without further ado, here's the guessing game program:
import random # This is the easiest way to import a random number generator of any of the four projects. I wish the others were this simple.
guessesTaken = 0
print("What is your name? ")
playerName = input() # This is also the most simple way to handle player input.
number = random.randint(1,20) # We need to make sure we get a whole number. This is a way to show the difference in int and float numbers.
print(playerName + " I'm thinking of a number between 1 and 20")
for guessesTaken in range(6): # Players get six tries. This could be whatever.
print ("Take a guess")
guess = input()
guess = int(guess) # input() gets a string and we need to turn it into an int. More practice!
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken +1)
print("Good job! You guessed my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Nope, I was thinking of another")
In about 30 lines of code we have a solid guessing game. It's not going to win any awards, but it gets the job done. It also allows for some customization. Creators can increase the range of random numbers or have the program write a different message if the guess is within one.
Next comes my least favorite language - Java.