Skip to content

Instantly share code, notes, and snippets.

@binh-bk
Created July 20, 2018 05:20
Show Gist options
  • Save binh-bk/6cd401b893d0bef896547fc0f93cd0c0 to your computer and use it in GitHub Desktop.
Save binh-bk/6cd401b893d0bef896547fc0f93cd0c0 to your computer and use it in GitHub Desktop.
#! /usr/bin/python3
# demonstrate while loop, try-except block, and print string
# EAFP: Easier to Ask for Forgiveness than Permission
# Binh Nguyen, July 20, 2018
import random
secret = random.randint(0, 100)
flag = True
count = 0
def delta(input_, target):
if abs(input_ - target) <= 5:
print('Close one +-5, try something like: {}'.format(random.randint(secret-5, secret+5)))
elif abs(input_ - target) <= 12:
print('Closer but not yet +-25, try something like: {}'.format(random.randint(secret-10, secret+10)))
else:
if secret >= 21:
print('Not close, try something like: {}'.format(random.randint(secret-20, secret+20)))
else:
print('Not close, try something like: {}'.format(random.randint(0, secret+20)))
return None
while flag:
y = input("enter a number from 1 - 100 to guess, 0 for exit: ")
count += 1
try:
y = int(y)
except ValueError:
print('Please enter a number')
else:
if y == 0:
flag = False
try:
assert y == secret
except AssertionError:
delta(y, secret)
# print('Secret number: {}'.format(secret))
else:
print("Your guess is correct with {} tries".format(count))
flag = False
finally:
if not flag:
print('Exit.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment