You've done it, you've mastered functions, variables, strings, conditional statements, indefinite loops & definite loops...but now what?
It's time you knock together your first Python project, a number guessing game.
A word of warning though, NASA - National Aeronautics and Space Administration may come knocking at the door after you upload this masterpiece to GitHub, the next Margaret Hamilton they'll think...you've been warned.
Here's the project brief;
"Listen, I like numbers, I like guessing and I like games...do you think you could make me a number guessing game? Nice one, thanks." - Ben Goulding
Say no more, let's go.
First things first, we're going to need a random number. Luckily for us Python can simulate a random number with the help of the suitably named module called...random. Let's get that imported;
import random
If you haven't come across modules before, here's a brief TL/DR;
"A Python module is a file containing Python code. This file typically consists of functions, classes, variables, and runnable code. Modules are used to organise and reuse code in Python programming." - Mr C.GPT
Job done, put the kettle on, we're nearly there.
For reasons that will become apparent shortly, our best bet is to create a function that will hold the vast majority of the game logic.
import random
def playthemgames():
Feel free to name the function how you like, for this demonstration I've gone for 'playthemgames'.
Now we need the outer 'while' loop, this will come in handy when we want to replay the game, for those times where you just cant get enough.
import random
def playthemgames():
while True:
random_number = random.randint(1, 100)
You'll notice that this is actually an infinite loop, with thanks to the 'True', it will never be 'False' hence the infinite.
Within this outer loop, we have also created the 'random' number, with the help of the 'random' module we imported at the start.
The 'random_number' variable will be assigned a simulated random number, I say it's simulated as it can never truly be random due to the deterministic nature that they are generated within Python. That's all for another time, but if you want to look into it Google something along the lines of "random number seeds in Python".
On the 'random' module we imported we can access the '.randint()' method. This method accepts two arguments, the first being the starting minimum integer and the second being the maximum integer value you want to generate to. These values are inclusive meaning that they can be generated as the random number.
Now we need to add the second nested 'while' loop, this one in particular will allow the player to keep guessing until the correct number has been found.
import random
def playthemgames():
while True:
random_number = random.randint(1, 100)
while True:
user_input = input("Please enter a number between 1-100: ")
if user_input.lower() == "stop":
return
You'll see that we are now asking for some user input;
user_input = input("Please enter a number between 1-100: ")
As you've probably guessed, this get's the user's guess or their command to stop the game.
if user_input.lower() == "stop":
return
The 'if' conditional is here to check is the user has entered "stop". If "stop" was entered by the user it would be assigned to the 'user_input' variable where the conditional would match the equality '==' and exit the function 'return', effectively ending the game. The '.lower()' method on the 'user_input' variable is there to account for Pythons case sensitivity incase the user was to enter "sTOp", "Stop" or some other fruity case concoction.
Moving on...
import random
def playthemgames():
while True:
random_number = random.randint(1,100)
while True:
user_input = input("Please enter a number between 1-100: ")
if user_input.lower() == "stop":
return
try:
int_guess = int(user_input)
if int_guess < random_number:
print("Too low!")
elif int_guess > random_number:
print("Too high!")
elif int_guess == random_number:
print("You got it right!")
break
except ValueError:
print("Invalid Entry - Please input a number.")
What you now see in the block above is the bulk of the game logic, I imagine this looks very similar in both style and size to Rockstar Games upcoming GTA IV source code.
I will briefly address the 'Try/Except' in case you haven't stumbled across this yet.
try:
...
except ValueError:
print("Invalid Entry - Please input a number.")
Within the 'Try/Except' I've nested the logic that attempts to convert the user's input to an integer. If the conversion fails (the user enters something that's not a number), a 'ValueError' is caught, and a message is printed. It would be worthwhile looking into this in greater detail, have a gander here: https://docs.python.org/3/tutorial/errors.html
int_guess = int(user_input)
if int_guess < random_number:
print("Too low!")
elif int_guess > random_number:
print("Too high!")
elif int_guess == random_number:
print("You got it right!")
break
The user's guess is now compared with the random number. Feedback is provided if the guess is too low or too high. If the guess is correct, a message of your choosing is displayed, and the inner loop is broken. No prize money or leaderboard here though...yet.
Onwards and upwards!
import random
def playthemgames():
while True:
random_number = random.randint(1,100)
while True:
user_input = input("Please enter a number between 1-100: ")
if user_input.lower() == "stop":
return
try:
int_guess = int(user_input)
if int_guess < random_number:
print("Too low!")
elif int_guess > random_number:
print("Too high!")
elif int_guess == random_number:
print("You got it right!")
break
except ValueError:
print("Invalid Entry - Please input a number.")
print("Game Over")
play_again = input("Play again? Y/N: ")
if play_again.lower() != "y":
break
print("Game Over")
play_again = input("Play again? Y/N: ")
if play_again.lower() != "y":
break
After a round ends (either through a correct guess or the user typing "stop"), the game prints "Game Over". It then asks if the user wants to play again, if the user responds with anything other than 'y', the outer loop breaks, ending the game. Once again, notice the use of the '.lower()' method.
Nearly there...
import random
def playthemgames():
while True:
random_number = random.randint(1,100)
while True:
user_input = input("Please enter a number between 1-100: ")
if user_input.lower() == "stop":
return
try:
int_guess = int(user_input)
if int_guess < random_number:
print("Too low!")
elif int_guess > random_number:
print("Too high!")
elif int_guess == random_number:
print("You got it right!")
break
except ValueError:
print("Invalid Entry - Please input a number.")
print("Game Over")
play_again = input("Play again? Y/N: ")
if play_again.lower() != "y":
break
start_game = input("Start Game? Y/N: ")
if start_game.lower() == "y":
playthemgames()
As you would have noticed, everything that has been written up to now has been included within the 'playthemgames()' function.
We need to actually write the code that will start the game, this wont be within the function.
start_game = input("Start Game? Y/N: ")
if start_game.lower() == "y":
playthemgames()
else:
exit()
Initially, the script prompts the user to start the game. If they respond with 'y', the 'playthemgames' function is called, starting the game. If not, 'exit()' is called to terminate the script altogether.
And there we have it, your first Python project, short and sweet, much like myself.
In all seriousness, I hope you've found this somewhat useful and it's opened your mind to the beginnings of control flow and how to construct a simple script. There are many different ways this same result could have been achieved, that's the beauty of programming. At the end of the day and especially so if you are just starting out, if it get's the job done then the jobs a good'un.
If you would like further tutorials then please let me know, this is my first attempt and I'm more than happy to delve deeper into more complex topics or alternatively put together a basic Python tutorial that assumes no prior knowledge of programming.
Speak again soon!