python try_except_while_guessingnumber_demo.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 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.')

以上是关于python try_except_while_guessingnumber_demo.py的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识