python guess my number exercise marked wrong on edX - python

The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number!
My code:
guess number using bisection
Ask for an input of number from the user
high = 100
low = 0
correct = False
response = ""
user_number = input("Please think of a number between 0 and 100!")
while (response != "c"):
guess = int((high + low)/2)
print("Is your secret number", guess, "?")
response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")
if not (response == "h" or response == "c" or response == "l"):
print("Sorry, I did not understand your input.")
elif (response is "h"):
high = guess
elif (response is "l"):
low = guess
print ("Game over. Your secret number was:", guess)
Currently the EdX website is marking my answer as incorrect, I checked the out put by trying input numbers such as 83, 8,42 it came out correctly as the edX website code's showing. Can someone give me some suggestions on where my code is flawed? Thank you.

Related

How do I compare the input value from one function, to the return value of another function?

I have a class project, where I am making a number guessing game. I have the following requirements:
#1. A main() function that holds the primary algorithm, but itself only passes information among other functions. main() must have the caller for random_int()
#2. A function called in main() (not nested in main()!) that compares the user's guess to the number from random_int() and lets the user know if it was too high or too low.
#3. A function called in main() that asks the user for a new guess.
#4. A function that prints out a string letting the user know that they won.
#5. Tell the user how many guesses it took them to get the correct answer.
I am currently having an issue trying to take the user inputted value "guess" and compare it with the value of a randomly generated integer "random_int" in a while loop in the function def high_low():
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
I either get the error "guess not defined" or '>' not supported between instances of 'function' and 'function'
Here is all of the code for context, note though that most of it below what I have posted above is pseudocode for the purposes of figuring out the logic of the game's function, and I have not yet gone through with debugging.
#Python number guessing game
#Import randrange module
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
random_int(1000)
new_guess()
high_low(random, new_guess)
win()
main() #Calls the "main" function, runs the program
The code has a couple of issues I'll walk through all of them with an explanation so that we understand the reason why they happen at all. First we'll address all errors one by one.
Error-1
The first error on executing the code is '>' not supported between instances of 'function' and 'function'.
To understand that, notice the difference between Call-1 and Call-2 in below example code:
def f1():
return 1
def f2():
return 2
def less_than(n1, n2):
return n1 < n2
less_than(f1, f2) # Call-1: this will not work and give you error similar to what you get
less_than(f1(), f2()) # Call-2: this works
Call-1 passes the function itself, whereas Call-2 passes result of f1() and f2(), which are integers and can be compared by <.
In the code the main() needs to be rewritten like this:
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
Error-2
After above fix, executing will give another error:
NameError: name 'guess' is not defined
It means guess has not been defined. That's fixed by re-writing high_low() again like this. Notice the name new_guess replaced with guess. One is the function and other is the variable.
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Error-3
Again running would give this error:
TypeError: '>' not supported between instances of 'str' and 'int'
Fix is simple, the new_guess() function needs to convert input to int as calling input returns everything as string.
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
Error-4
Last error would be:
UnboundLocalError: local variable 'attempts' referenced before assignment
This simply means no value has been set to attempts before using it in attempts += 1
This gets fixed again by updating high_low and adding attempts = 0:
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Final code looks like this:
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
main() #Calls the "main" function, runs the program
your high_low function has no reference to a variable named guess. I think the solution is to just add the line guess = new_guess() right before the while loop.

Input not mapping with the elif clause

I am new to learning python and programming in general. I wrote this code for computer to guess a number that i imagined (in between 1 to 100). It is showing me the same output "Sorry, I did not understand your input." which is applicable only if my input doesnot match l, h or c. In cases where my input is l,h or c, it should take those conditions and follow up to finally reach to an outcome. But that isn't happening.I am trying to use bisection method. Can you please help me where is it going wrong ?
num_begin = 0;
num_end = 100;
avg=(num_begin+num_end)/2
print("Please think of a number between 0 and 100!")
print("is your secret number "+ str(avg))
command=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")
while (True):
if (command != 'c' or command != 'h' or command != 'l'):
print("Sorry, I did not understand your input.")
print("is your secret number "+ str(avg))
command=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")
elif(command=='l'):
num_begin=avg
avg=(num_begin+num_end)/2
print("is your secret number "+ str(avg))
command=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")
elif(command=='h'):
num_end=avg
avg=(num_begin+num_end)/2
print("is your secret number "+ str(avg))
command=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")
else:
print("Game over. Your secret number was: " + str(avg))
break
Just replace or by and in your first condition
if (command != 'c' and command != 'h' and command != 'l'):

Loops and comparing strings in homework assignment

I need help with an assignment I have for Intro to Python.
The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.
My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?
P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.
Code:
import random
#answer= a
a= random.randint(1,100)
#x= original variable of a
x= a
correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")
#guess= g
while not correct:
g= input("Please enter a number between 1 and 100: ", )
if g == "x":
print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")
elif int(g) < x:
print("your guess was too low, try again.")
elif int(g) > x:
print("your guess was too high, try again.")
else:
print("Congratulations, you guessed the number!")
So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:
g=input("blah blah blah input here: ")
if g.isdigit():
# now you can do your too high too low conditionals
else:
print("Your input was not a number!")
You can learn more in this StackOverflow thread.

Beginner 'Guess my number' program. while loop not breaking when correct number guessed or when out of guesses

So I'm learning python and I'm trying to code a simple guess my number game where you only have 5 guesses or the game ends. Im really having trouble with the while loop not recognising that the number has been guessed or the guess limit has been reached. Is there a better way of formatting my functions also. Thanks for any and all help, first time using this site.
# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
GUESS_LIMIT = 5
# functions
def display_instruct():
"""Display game instructions."""
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.")
print("\nHARDCORE mode - You have 5 tries to guess the number!\n")
def ask_number(question, low, high, step = 1):
"""Ask for a number within a range."""
response = None
while response not in range(low, high, step):
response = int(input(question))
return response
def guessing_loop():
the_number = random.randint(1, 100)
guess = ask_number("\nTake a guess:", 1, 100)
tries = 1
while guess != the_number or tries != GUESS_LIMIT:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = ask_number("Take a guess:", 1, 100)
tries += 1
if tries == GUESS_LIMIT:
print("\nOh no! You have run out of tries!")
print("Better luck next time!")
else:
print("\nYou guessed it! The number was", the_number)
print("And it only took you", tries, "tries!")
def main():
display_instruct()
guessing_loop()
# start the program
main()
input("\n\nPress the enter key to exit")
Your while condition will be true as long as you haven't hit the guess limit.
while guess != the_number or tries != GUESS_LIMIT:
You should join those conditions with and, not or. The way you have it now, the entire condition will be true because tries != GUESS_LIMIT is true, even if guess != the_number is false.
Or you can break your cycle explicitly with break statement. But previous answer is more correct in a sense you should really understand conditions you're setting for the loop.

Python 3.1 number guessing game higher or lower loop

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.

Categories