|
| 1 | +import random |
| 2 | + |
| 3 | +print("Number guessing game") |
| 4 | + |
| 5 | +# randint function to generate the |
| 6 | +# random number b/w 1 to 9 |
| 7 | +number = random.randint(1, 9) |
| 8 | + |
| 9 | +# number of chances to be given |
| 10 | +# to the user to guess the number |
| 11 | +# or it is the inputs given by user |
| 12 | +# into input box here number of |
| 13 | +# chances are 5 |
| 14 | +chances = 0 |
| 15 | + |
| 16 | +print("Guess a number (between 1 and 9):") |
| 17 | + |
| 18 | +# While loop to count the number |
| 19 | +# of chances |
| 20 | +while True: |
| 21 | + |
| 22 | + # Enter a number between 1 to 9 |
| 23 | + guess = int(input()) |
| 24 | + |
| 25 | + # Compare the user entered number |
| 26 | + # with the number to be guessed |
| 27 | + if guess == number: |
| 28 | + |
| 29 | + # if number entered by user |
| 30 | + # is same as the generated |
| 31 | + # number by randint function then |
| 32 | + # break from loop using loop |
| 33 | + # control statement "break" |
| 34 | + print( |
| 35 | + f'CONGRATULATIONS! YOU HAVE GUESSED THE \ |
| 36 | + NUMBER {number} IN {chances} ATTEMPTS!') |
| 37 | + # Printing final statement using the f-strings method; |
| 38 | + break |
| 39 | + |
| 40 | + # Check if the user entered |
| 41 | + # number is smaller than |
| 42 | + # the generated number |
| 43 | + elif guess < number: |
| 44 | + print("Your guess was too low: Guess a number higher than", guess) |
| 45 | + |
| 46 | + # The user entered number is |
| 47 | + # greater than the generated |
| 48 | + # number |
| 49 | + else: |
| 50 | + print("Your guess was too high: Guess a number lower than", guess) |
| 51 | + |
| 52 | + # Increase the value of chance by 1 |
| 53 | + chances += 1 |
| 54 | + |
0 commit comments