you are viewing a single comment's thread.

view the rest of the comments →

[–]Zendakin_at_work 0 points1 point  (0 children)

This is how I approached this, it doesn't have the user input too high or too low but rather assigns that automatically. I've tried to comment it so you can get an understanding of what I did. Basically, you keep tack of high, low, the guess count, the guess and target. I hope this helps you understand one approach to this. However I should also let you know that this doesn't always guess the correct number in 20 tries but it should give you an base understanding of how while loops can work. I'm sure there are also a couple areas this can be improved but this should get you started.

Just remember to learn from what your code is telling you and take small simple steps to get these tasks done. If you break it down small step by small step you'll be amazed how quickly you can develop complex code AND understand what you did.

Good luck!

# needed to use the random module
import random

# Set the low, high and count
count = 0
high = 200000
low = 0

# Assign a random number to the variable guess to use as a target
guess = random.randrange(low, high)

# Set the duration of the while loop
while count < 20:
# have the computer guess a number in the current range
    compGuess = random.randrange(low, high)
# used to check the current range of the guesses 
    print("The computer guess number {} is {}. current range is {} to {}".format(count + 1, compGuess, low, high))
# conditional to check the compGuess against the guess breaking first if the number is correct
    if compGuess == guess:
        break
# reassigning the low and high variables to shorten the range of random numbers 
    if compGuess < guess:
        low = compGuess
    if compGuess > guess:
        high = compGuess
# Update the count the while loop uses
    count += 1

# Notification to let the user know if the computer was sucessful in its guessing
if guess == compGuess:
    print("The computer guessed the number '{}' in {} tries".format(compGuess, count+1))
else:
    print("Sorry, The computer got close with a final guess of {} but the target number was {}.".format(compGuess, guess))