Bonjour à tous,
J'essaie de me mettre à python et j'ai codé un petit "plus ou moins".
J'aimerais savoir si mon code est "pythonic" ou non et comment l'améliorer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | # -*- coding: utf-8 -*- import random from enum import Enum class POM(Enum): TOO_BIG = 1 TOO_SMALL = -1 FOUND = 0 class PlusOuMoins: def __init__(self, max_number=100): self.__max_number = 100 self.__guessed_number = random.randint(0,max_number) def ask_for(self, number): if(number<self.__guessed_number): return POM.TOO_SMALL elif(number>self.__guessed_number): return POM.TOO_BIG else: return POM.FOUND def plus_ou_moins(max_number=100): pom = PlusOuMoins(max_number) while True: user_number = ask_a_number(max_number) res = pom.ask_for(user_number) if(res == POM.TOO_SMALL): print('Too small') elif(res == POM.TOO_BIG): print('Too big') else: print('Found') break def ask_a_number(max_number): try: user_number = int(input('Enter a number between 0 and {}: '.format(max_number))) if(user_number<0 or user_number>max_number): return ask_a_number(max_number) else: return user_number except ValueError: print('Please enter a number') return ask_a_number(max_number) def try_to_guess_number(max_number=100): pom = PlusOuMoins(max_number) max_guess = max_number min_guess = 0 while True: guess = (max_guess-min_guess)//2+min_guess print(guess) res = pom.ask_for(guess) if(res == POM.TOO_SMALL): min_guess = guess+1 elif(res == POM.TOO_BIG): max_guess = guess-1 else: break if __name__ == "__main__": try: user_input = int(input('Enter 0 to play or 1 to let the compulter play: ')) except ValueError: print('Please enter a number') if(user_input == 0): plus_ou_moins(100) elif(user_input == 1): try_to_guess_number(100) else: print('Plesae enter 0 or 1') |
+0
-0