There are different types of loops which will repeat code a specific number of times or until a condition is met.
The first loop will use is a While loop.
A While loop will keep running as long as a condition is true.
For demonstration, we will create 2 variables, both integers.
One will be a secret number and the other will be a player’s guess, which at the start of the game will be empty.
In this demo, the secret number will be known to use, so it isn’t much of a secret, but bear with me!
secret = 7
guess = None
while guess != secret:
guess = int(input("Guess the number"))
print("Congratulations! You got it")
The While loop will repeat as long as the player does not guess the secret number (!= means not equal to), note it repeats the indented code below that.
Once the player guesses the secret number, the while condition is no longer true, so Python skips the indented lines and continues the code, which is the print() command that displays congratulations.
Now we can take the IF/ELIF/ELSE that we have seen in the last post and include them in our While loop to help the player.
IF the player’s guess is lower than the secret number THEN print “guess higher” or ELSE print (“guess lower”).
secret = 7
guess = None
while guess != secret:
guess = int(input("Guess the number"))
if guess < secret:
print("guess higher")
else:
print("guess lower")
print("Congratulations! You got it")
In the code above we check IF the player’s guess is lower than the secret number, if it is THEN print “guess higher”. We do not need to add in and ELIF here because we aren’t going to check another IF condition, we can use ELSE and print “guess lower”.
Now, let’s say we want to take this a bit further and give the player additional hints if their guess is close or super close to the secret number.
We can cut this code in half by using abs() which will be covered in the next post.
