Page 39 -
P. 39
guessing games
This code is a guessing-game program. You were to write down
what you think the code does.
Don’t worry if your answers are
different from ours. If they are
similar, then everything is OK.
print("Welcome!") Display a welcome message.
g = input("Guess the number: ") Ask the user to input a guess.
Convert the input to a number.
guess = int(g)
Was the guessed number equal to 5?
if guess == 5:
Tell the user “You win!"
print("You win!")
Otherwise...
else:
print("You lose!") ...tell the user “You lose!"
End the program.
print("Game over!")
But what are g and guess?
You might be wondering what g and guess are in the code. They are
called variables and they’re used to keep track of data in the computer’s
memory.
A variable The value entered will Be careful with
be known as “g".
= signs in code.
g = input("Guess the number: ")
Programming
languages use =
guess = int(g) signs for different
purposes. In most languages
A variable
This creates a number- (including Python), a double
version of the g-value and
equals (==) is a test for equality.
calls it “guess". It means, “are these two things
equal?” In contrast, a single
equal (=) is an instruction
(known as assignment) that
A variable is really just a label for data. So if the user inputs “3” at the
keyboard, then guess will be set to the number 3, and whenever the means “set the value to.”
computer reads guess, it will read it as the value 3.
4 Chapter 1