Last active
May 8, 2020 15:27
-
-
Save arpit-omprakash/26d2916999a2e04379995d1ddba08165 to your computer and use it in GitHub Desktop.
A simple guessing game in python. Read the article for more info: https://medium.com/byte-sized-code/a-simple-guessing-game-in-python-3d825dc9223b?source=friends_link&sk=209b685920e3026e0f6d0e46eef7b752
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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