We want to design a robot that can choose a lower case letter from the alphabet randomly. Then the user needs to guess which letter the robot has chosen. Like this:
Please guess my chosen letter: g You are wrong! Try again! Please guess my chosen letter: k Great! You are right!
Solution with while loop. The event ending the loop is having guessed the right letter.
#02Loops example_07 GuessLetter.py import random alphabet = 'abcdefghijklmnopqrstuvwxyz' #Initialize the alphabet answer = random.choice(alphabet) #Pick up a letter randomly guess = raw_input('Please guess my letter: ') #Ask the user to guess while guess != answer: #If the user's answer is not right, repeat the statements print('You are wrong! Try again!') guess = raw_input('Please guess my letter: ') print('Great! Your are right!')
To help the user guess the right answer faster, we add a hint when the guess is wrong. The following is the revised code giving a hint:
# 02Loops example_07 GuessLetterWithHint.py # with hint on whether guessed letter is too high ot too low import random alphabet = 'abcdefghijklmnopqrstuvwxyz' #Initialize the alphabet answer = random.choice(alphabet) #Pick up a letter randomly guess = raw_input('Please guess my letter: ') #Ask the user to guess while guess != answer: #If the user's answer is not right, repeat the statements if guess > answer: #If the user抯 answer is not right, provide hints. print('My letter is before your guess in the alphabet') else: print('My letter is after your guess in the alphabet') guess = raw_input('Please guess my letter: ') print('Great! Your are right!')
This code above is an example of what is known as binary search.