Skip to content Skip to sidebar Skip to footer

Correct Way Of Coding A 'guess The Number' Game In Python

I'm new to python and programming in general and I've written some code for a Guess the Number game in Python. It allows the user 6 attempts at guessing a random number. It works,

Solution 1:

I'd refactor your code to use a for loop instead of a while loop. Using a for loop removes the need to manually implement a counter variable:

import random

attempts = 5
secret_number = random.randint(1, 100)

for attempt in range(attempts):
    guess = int(input('Take a guess: '))

    if guess < secret_number:
        print('Higher...')
    elif guess > secret_number:
        print('Lower...')
    else:
        print()
        print('You guessed it! The number was ', secret_number)
        print('You guessed it in', attempts, 'attempts')

        break

if guess != secret_number:
    print()
    print('Sorry you reached the maximum number of tries')
    print('The secret number was', secret_number)

Post a Comment for "Correct Way Of Coding A 'guess The Number' Game In Python"