Guessing number game in Python
This exercise is to write a program which asks the user to guess a number and the program will give hints to help the user guess the correct answer.
To display a prompt waiting for a user to enter some data, we use the input()
function. The input()
function provides the data as a string, which is a sequence of letters. To convert to an integer number we use the int()
function.
To control the flow of the program based on the user’s answers, we use if
and elif
statements (elif
is short for “else if”).
answer=15 guess=None while guess != answer: guess=int(input("Guess a number between 0 and 50 ? ")) if guess > answer: print("too high") elif guess < answer: print("too low") print("Yes. Answer is ", answer)
Importing more functionality
Sometimes we want more functionality than is provided in the base python system. In our example we want a random number generator which is available in the random
module (library). The program becomes a lot more interesting now, because we can’t see the answer by reading the source code.
import random answer=random.randint(0,50) guess=None while guess != answer: guess=int(input("Guess a number between 0 and 50 ? ")) if guess > answer: print("too high") elif guess < answer: print("too low") print("Yes. Answer is ", answer)
In the previous countdown examples, we can put a timer to ensure the countdown happens one second at a time.
import time x=10 while x>0: print(x) x-=1 time.sleep(1) print("blast off")