Skip to content

Instantly share code, notes, and snippets.

@srahuliitb
Created September 9, 2017 18:44
Show Gist options
  • Select an option

  • Save srahuliitb/ee2329a84969a7a5f09f453b6dbeb2f7 to your computer and use it in GitHub Desktop.

Select an option

Save srahuliitb/ee2329a84969a7a5f09f453b6dbeb2f7 to your computer and use it in GitHub Desktop.
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
import random
rand_num = random.randint(1, 9)
user_guess = int(raw_input("Guess a number between 1 to 9: "))
attempts = 0
while user_guess != rand_num:
if user_guess == rand_num - 1 or user_guess == rand_num + 1:
print "You were very close. Try again!"
user_guess = int(raw_input("Guess a number between 1 to 9: "))
elif user_guess < rand_num:
print "Wrong guess. Try again!"
user_guess = int(raw_input("Guess a number between 1 to 9: "))
elif user_guess > rand_num:
print "Wrong guess. Try again!"
user_guess = int(raw_input("Guess a number between 1 to 9: "))
else:
break
attempts = attempts + 1
print "Congratulations! ", user_guess, " is the correct guess."
print "You took ", attempts + 1, " attempt(s) for the correct guess."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment