1,105,214 Community Members

Help with Guessing game

Member Avatar
fdama
Newbie Poster
3 posts since Oct 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,

I am working on an exercise in a book and have difficulty with it. I have completed the first part of the exercise which was to create a guessing game where the the player attempts to guess a secret number randomly generated. Suggestions such as to guess Lower and Higher are also provided to help to narrow down to the secret number The code for that is below. The second part of the exercise is for the player to choose a number and allow the computer to guess that number. This is where I am struggling and I dont know why. I would appreciate it if someone would give me a a little 'push' to help me on this rather than the solution as I will need to do this on my own.

Complete code for first part of exercise:

#Guess my Number - Exercise 3
#Limited to 5 guesses

import random 

attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))

while secret_number != guess and attempts < 6:

    if guess < secret_number:
        print("Higher...")
    elif guess > secret_number:
        print("Lower...")
    guess = int(input("Take a guess: "))
    attempts += 1

if attempts == 6:
    print("\nSorry you reached the maximum number of tries")
    print("The secret number was ",secret_number) 

else:
    print("\nYou guessed it! The number was " ,secret_number)
    print("You guessed it in ", attempts,"attempts")

input("\n\n Press the enter key to exit")           

Thank you for your help.

Member Avatar
woooee
Posting Maven
2,792 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

Ask the user to enter a number to be guessed say between 1 and 100. The computer selects a random number in that range. If the computer guesses too low, then that number+1 becomes the lower number in the range for the next random number to choose from and so on for too high. On the first program that you posted here, what happens if the person guesses the number on the 6th and final try? A related question/answer, why is "isCorrect" declared but never used? The Python Style Guide says that variables names should be all lower case --> so "is_correct", BTW.

## only a partial solution
##
is_corect = False
while not is_correct and count < maximum:
    guess = int(input("Take a guess: "))

    if guess < secret_number:
        print("Higher...")  ## does "Higher" mean number is higher or guess is higher
    elif guess > secret_number:
        print("Lower...")
    else :   ## 2 numbers are equal
        is_correct = True
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article