Skip to content

Instantly share code, notes, and snippets.

@arpit-omprakash
Last active May 8, 2020 15:27
Show Gist options
  • Save arpit-omprakash/26d2916999a2e04379995d1ddba08165 to your computer and use it in GitHub Desktop.
Save arpit-omprakash/26d2916999a2e04379995d1ddba08165 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# imports
import argparse
import random
from math import log
def main(range_end):
guesses_made = 0
# number of guesses is 1 + the log of the range
no_of_guesses = round(log(range_end)) + 1
# introductory message
name = input('Hello! What is your name?\n')
number = random.randint(1, range_end)
print('Well, {}, I am thinking of a number between 1 and {}'.format(name, range_end))
print("You get {} guesses!".format(no_of_guesses))
# flag to keep track of whether the user loses
lost = True
# guessing loop
while guesses_made < no_of_guesses:
guesses_made += 1
try:
guess = int(input('Take a guess: '))
except ValueError:
print("Oops! That was not a valid integer!\nAlas! You lose a chance!")
finally:
print("Number of chances left: ", no_of_guesses - guesses_made)
print("")
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
else:
# user wins!
print("good job, {}! You guessed my number in {} guesses!".format(name, guesses_made))
lost = False
break
# losing message
if lost:
print("Nope. The number I was thinking of was {}".format(number))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment