In the process of learning Python using the book 'Python Programming for the Absolute Beginner Third Edition' and struggling with a challenge that has been set.
I have to create a Number Guessing program where the player picks a number and the program tries to guess it by picking a random number then using higher or lower questions to get closer to the number. I've got most of it figured out but I'm struggling with the higher or lower loop. The trouble I'm having is that i can't get the program to not go above or below it's second to last guess i.e.
My number is 78
computer picks 50
i say higher
computer picks 80
i say lower
computer can then pick 12 (when i don't want it going below 50.
I'm using Python 3.1
Here is a copy of the code.
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
Thanks in advance for any help you folks can give.
Ally
I see the following problems with your code:
your random number generators are bound only on one side of the number spectrum, e.g. random.randint(0, lower) - so it's ignoring the higher bound. Similarly for computer_guess = random.randint(higher, 101).
I suggest you initialise higher and lower.
Some debug helps :)
Here's the working code:
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
lower = 0 # initial lower guess
higher = 101 # initial higher guess
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(lower+1, higher-1)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(lower+1, higher-1)
else:
print("Please choose either higher or lower.")
print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))
input("\n\nPress the enter key to exit")
You have to store something like min_comp_guess and max_comp_guess
Then, when you are about to "guess" number you have to generate it for a valid range (obviously min_comp_guess up to max_comp_guess).
I'm always second! :)
You are never storing the upper and lower bounds to the possible numbers. In your example, as soon as your program picks 50 and you say "higher", you need to store somewhere the information that "the number is definitely higher than 50". The same goes for when you answer "lower".
I may be completely wrong but whilst testing your code I found that by choosing the programs number was higher than my chosen number it would increase the number instead or a presumable decrease, not making it any closer to the number I had guessed. A similar higher/lower program I created had the same problem, to fix the problem I simply switched the more than and less than signs around, hopefully you find this helpful and could apply this to your program.
Related
I would like to generate a random number (1,100), however, the random number is bigger than the user idea changes the range of random EX: computer random =36 but users answer is 87 so tell the computer my answer is bigger than your guess, the computer change its range (36,100) and vice versa.
this program runs just one time and doesn't repeat asking for select more randomly.
Thank you so much
from random import randint
a = int(1)
b = int(100)`enter code here`
guess = randint(a,b)
print(guess)
answer = input ("your idea:")
while answer != "done":
if answer == "big":
a = int(guess)
guess = randint(a,100)
print(guess)
if answer == "small":
b = int(guess)
guess = randint(1, b)
print(guess)
else:
answer == "done"
print("your guess number ", guess, "is right")
break
else:
answer == "done"
print("your guess number ", guess, "is right")
break
The break is indented outside the else. So it'll break regardless of the value of the answer. Just indent the break inside the else and it'll be fine
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
Thank you for your patience everyone.
Thank you Ben10 for your answer. (posted below with my corrected print statements) My print statements were wrong. I needed to take the parenthesis out and separate the variable with commas on either side.
print("It only took you ", counter, " attempts!")
The number guessing game asks for hints after a certain number of responses as well as the option to type in cheat to have number revealed. One to last hints to to let the person guessing see if the number is divisible by another number. I wanted to have this hint available until the end of the game to help narrow down options of the number.
Again thank you everyone for your time and feedback.
guessing_game.py
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: ", random_) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 10:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by ", divisor, ". ")
else:
print("Not it quite yet, The random number is NOT divisible by ", divisor, ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is ", cheat, ".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you ", counter, " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
I rewrite the code, to allow it to be more versitile. Noticed quite a few errors, like how you forgot to put a closing bracket at the end of a print statement. Also in the print statements you were doing String concatenation (where you combine strings together) incorrectly.
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: " + str(random_)) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 5:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by " + str(divisor) + ". ")
else:
print("Not it quite yet, The random number is NOT divisible by " + str(divisor) + ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is " + str(cheat) +".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you " + str(counter) + " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
Implement the GuessNumber game. In this game, the computer
- Think of a random number in the range 0-50. (Hint: use the random module.)
- Repeatedly prompt the user to guess the mystery number.
- If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low.
- After 5 incorrect guesses, tell the user the right answer.
The following is an example of correct input and output.
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
This is what I got so far:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...
Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.
for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
Do you see how that works?
You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. E.g.,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
import random
arr=[]
for i in range(50):
arr.append(i)
answer=random.choice(arr)
for trial in range(5):
guess=int(input("Please enter your guess number between 0-50. You have 5
trials to guess the number."))
if answer is guess:
print("Congratulations....You have guessed right number")
break
elif guess < answer-5:
print("You guessed too low....Try again")
elif guess > answer+5:
print("You guessed too high..Try again")
else:
print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))
Just a three things to add:
The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.
I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format().
The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.
import random
from ast import literal_eval
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
win = False
for guess_count in range(1,6):
userInput = literal_eval(input(f"Guess {guess_count}: "))
if userInput == randomNumber:
print(f"You are right! I was thinking of {randomNumber}!")
win = True
break
else:
result = "low" if userInput < randomNumber else "high"
print(f"{userInput} is too {result}")
if win:
print ("YOU WIN!")
else:
print("Better luck next time")
print("End of program")
I am trying to find the average number of times a user guesses a number. The user is asked how many problems they want to do and then the program will give them that many problems. I am having trouble recording the amount of times they guess and get wrong and guess and get right and finding the average between the two. This is what I have so far
print("Hello!")
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVGcorrect = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
AVGcorrect+=1
print("Correct!")
AVERAGE+=((AVGcorrect+AVGcounter)/AVGcorrect)
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
numPROBLEMS = input("How many problems would you like to solve? ")
PROBLEMS = int(numPROBLEMS)
if PROBLEMS in range(1,11):
for PROBLEMS in range(PROBLEMS):
HOOBLAH()
else:
print("Average number of tries: {0}".format(HOOBLAH,AVERAGE))
else:
print("Please input a value between 1 through 10!")
main()
Thanks!
So I tried to change as little as possible as to not cramp your style. So think about it like this, the average number of guesses needed to get the correct answer is just the total number of guesses divided by the number of correct guesses. Because you make sure the user eventually gets the correct answer, the number of correct guesses will just be the number of problems!
So each time you run HOOBLAH(), return the number of guesses it took to get the correct answer. Add all those up together outside the for loop, then at the end of the loop, divide the number of guesses by the number of problems and then you've got your answer! Also, I don't think python supports '+=', so you may need to change AVGcounter+=1 to AVGcounter = AVGcounter +1, but I totally may be mistaken, I switch between languages a bunch!
One note is I cast numGuesses to a float ( float(numGuesses) ), that is to make sure the int data type doesn't truncate your average. For example, you wouldn't want 5/2 to come out to 2, you want it to be 2.5, a float!
Hopefully that helps!
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
print("Correct!")
return AVGcounter
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
problemsString = input("How many problems would you like to solve? ")
numProblems = int(problemsString)
numGuesses = 0
if numProblems in range(1,11):
for problem in range(numProblems):
numGuesses = numGuesses + HOOBLAH()
print("Average number of tries: " + str(float(numGuesses)/numProblems)
else:
print("Please input a value between 1 through 10!")
main()
I'm not totally sure what you're trying to do, but if you want to give the user x number of problems, and find the average number of guesses per problem, you'll want your HOOBLAH() function to return the number of guesses for each run. You can keep track of this outside your method call and average it at the end. But right now, your program has no access to AVGcounter, which seems to be the variable you're using to count the number of guesses, outside the HOOBLAH() function call.