binh-bk
7/20/2018 - 5:20 AM

try_except_while_guessingnumber_demo.py

#! /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.')