my apologies if I'm asking a silly question, but I'm a bit confused...
I've been doing the MIT6.00X course at edx and one of the exercises is to use bisection search algorithm to find the secret number. It took me about 4 hours to finish the exercise (Yeah I'm a noob) but I managed to build this code:
numGuesses = 0
lo = 0
hi = 100
mid = (hi + lo)/2
num = raw_input( "Input a number between 0 and 100 ")
if num > 0 or num < 100:
while mid != num:
print ("Is your number " + str(mid) + "?")
userinput = raw_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 userinput == 'h':
hi = mid
mid = (hi + lo)/2
elif userinput == 'l':
lo = mid
mid = (hi + lo)/2
elif userinput == 'c':
print ("Game over. Your secret number was:" + str(mid))
break
else:
print ("Sorry, I did not understand your input.")
else:
print ("You should use a number between 0 and 100")
While testing it by hand it works just fine, although in the exercise there are a few questions that don't go through mainly because the site instead of keep guessing if it's higher or lower sometimes it presses the wrong key and I fail the exercise.
After trying to change the code I wasn't able to finish the course so I've seen the answer, and this is were I did wrong, I should had use a boolean to keep the code flowing until it finds the correct number.
My question is: Is my code that wrong? Also is there any mistake I did that's preventing the site to press the correct letter? Just curious
Many thanks
this is one of the MITx finger exercise that I just finally solved it today. here is my method:
print('Please think of an integers BETWEEN 0 and 100!')
#Define variable
x=100
low=0
high=x
ans=0
#Guessing code part
while ans<=x:
print'Is your secret number:', str((low+high)/2), '?'
s=raw_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 s!='h' and s!='l' and s!='c':
print'Sorry I did not understand your input.'
elif s=='h':
high=(low+high)/2
elif s=='l':
low=(low+high)/2
elif s=='c':
print'Game over. Your secret number is:', str((low+high)/2)
break
lo = 0
hi = 100
mid = (hi + lo)/2
print 'Please think of a number between 0 and 100!'
while True:
print ("Is your number " + str(mid) + "?")
userinput = raw_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 userinput == 'h':
hi = mid
mid = (hi + lo)/2
elif userinput == 'l':
lo = mid
mid = (hi + lo)/2
elif userinput == 'c':
print ("Game over. Your secret number was:" + str(mid))
break
else:
print ("Sorry, I did not understand your input.")
Related
need help with a higher or lower game I think the problem has something to do with the loop. I have been told been told to add an except but I have no idea where to add it
print('Welcome to higher or lower game')
input('press enter to start.\n')
import random
Max = 10
Min = 0
num = random.randint(1, 10)
print('your starting number is a ' + str(num))
while 'well done.\n' :
guess = input('higher (h) or lower (l).\n')
new_num = random.randint(1, 10)
print('your new number is a ' + str (new_num))
try :
if new_num > num and guess == 'h':
print('well done.\n')
elif new_num < num and guess == 'l':
print('well done.\n')
break
if num and guess == 'l' and new_num > num and guess:
print('game over')
elif num and guess == 'h' and new_num < num and guess:
print('game over')
else:
print('game over you got a score of ' + str(score))
You do not have an except clause in the try statement. That clause is required unless you have a finally clause.
You really shouldn't have a try statement there. You could take it out and just go with some if and elif statements.
Example:
import random
number = random.randint(1,10)
lives = 3
Success = False
while lives > 0:
guess = int(input("What is your guess between 1 and 10? \r\n"))
if guess > number:
print("Too high! Go lower. \r\n")
lives -= 1
elif guess < number:
print("Too low! Go higher. \r\n")
lives -= 1
elif guess == number:
print("Congratulations, you win!")
global Success = True
break
if Success != True:
print("Sorry. Try again! The number was ", number, ".")
As far as I understand, try statements are mainly used for error handling.
I wrote the Python code below that is supposed to "guess" a number between 1 and 100, you just have to tell it if the number you're thinking of is higher or lower. But for some reason when I try playing it, it always gets stuck when I tell it that my number is higher after telling it that it's lower or vice versa:
import random
import time
import math
correct = 0
goon = 'yes'
biggest = 100
smallest = 1
tries = 10
print 'Hi!'
time.sleep(0.5)
print 'I´m going to try and guess your number'
time.sleep(0.5)
print 'Just tell me if your number is bigger or smaller than what I guessed'
time.sleep(0.5)
print 'And of course you have to tell me when I´m right, ok?'
time.sleep(0.5)
print 'Type "b" if your number is smaller than what I guessed and type "s" if it´s bigger. When I´m right, type "r".'
time.sleep(0.5)
print 'Oh by the way, your number should be between 1 and 100.'
if goon == 'no' or goon == 'No' or goon == 'n':
print 'Ok, see you soon!'
else:
while goon == 'yes' or goon == 'Yes' or goon == 'y':
guess = random.randint(1,100)
print guess
answer = raw_input()
while correct == 0:
if answer == 'r':
correct = 1
endhooray = random.randint(1, 3)
if endhooray == 1:
print 'Yay, I got it!'
elif endhooray == 2:
print 'Finally!'
elif endhooray == 3:
print 'See, I´m good at this!'
elif answer == 'b':
smallest = guess
difference = 100 - guess
add = random.randint(1, difference)
guess = guess + add
if guess < biggest:
print guess
answer = raw_input()
elif guess > biggest:
while tries == 10:
add = random.randint(1, difference)
guess = guess + add
if guess < biggest:
print guess
answer = raw_input()
tries == 1000000
elif answer == 's':
biggest = guess
difference = guess - 100
difference = difference * -1
subtract = random.randint(1, difference)
guess = guess - subtract
if guess > smallest:
print guess
answer = raw_input()
elif guess < smallest:
while tries == 10:
subtract = random.randint(1, difference)
guess = guess - subtract
if guess > smallest:
print guess
answer = raw_input()
tries = 100000
else:
print 'Oops, I don´t know what that means'
break
I took the liberty to simplify your code. This should do the job:
import random
import time
# your intro here
correct = False
min_, max_ = 0, 100
while not correct:
guess = random.randint(min_, max_)
answer = raw_input("Is your number %d? (b/s/r): " % guess)
if answer == "b":
min_ = guess+1
print "Ok, I'll aim higher!"
elif answer == "s":
max_ = guess
print "Ok, I'll aim lower!"
elif answer == "r":
hooray = random.choice(["Yay, I got it!", "Finally!", "See, I'm good at this!"])
print hooray
correct = True
else:
print "Oops, I don't know what that means!"
My issue is that python script ends when I get the number right, but doesn't print: You win!
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
if guess == number :
print('You win!') # Why doesn't this work?
#Python ends at this line if I get it right, but doesn't print: You win!
else :
guess = input('Try Again: ')
guess = float(guess)
pass # WHILE*
I'm only 11, and just started programming a couple months ago, please help me!
Your code fails the first condition if a guess is correct:
while guess != number and tries > 0 :
If a guess is complete the loop will break after your else statement and never returns to the if condition checking for a guess.
Since you can't continue past the loop until a correct answer is inputted you could always write this as follows:
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
else :
guess = input('Try Again: ')
guess = float(guess)
print('You win!')
Bear in mind there's a bug in this that will cause you win to also be printed after the user runs out of guesses. I've decided to leave this here as I think it's easy to fix and would be good for you to resolve yourself to learn from. Feel free to write in the comments if you want me to do that for you however.
I would also recommend using code comments on your posts. In this case I would have presented the code for your question as follows:
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
if guess == number :
print('You win!') # Why doesn't this work?
# Python ends at this line if I get it right, but doesn't print: You win!
else :
guess = input('Try Again: ')
guess = float(guess)
pass # WHILE*
When doing comparisons in your code, it is often best to try and only ask a particular question (do a comparison) once. Here I showed a way to restructure your two questions (correct guess & out of tries) to only do the questions once.
import random
number = random.randint(1, 100)
guess = input('Guess a number between 1 and 100: ') # Asks question
guess = float(guess)
tries = 10
while True:
tries -= 1
if guess < number:
print('Too low')
print('You have %s tries left' % (tries))
elif guess > number:
print('Too high')
print('You have %s tries left' % (tries))
else:
print('You win!')
break
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
break
guess = input('Try Again: ')
guess = float(guess)
hint = str
low = 0
high = 100
guess = (high + low)/2
answer = int(raw_input("Please think of a number between 0 and 100: "))
while (True):
print "Is your secret number " + str(guess) + "?"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
while (hint != "h" and hint != "l" and hint != "c"):
print "invalid option"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
if (hint == "h"):
low = guess
print "newlow: " + str(low)
print "newGuess: " + str(guess)
elif (hint == "l"):
high = guess
elif (hint == "c"):
print "Correct, the answer was " + str(answer)
break
Why is the variable guess not being changed, i'm expecting low to change to 50, therefore newGuess would become 75, correct?
From the moment when your program enters the while loop, all variables are set unless otherwise reassigned.
What you've done is reassigned your low variable. But, because the loop already has the value of guess in it using the old value for low, you would need to re-assign guess again, using the new one. Try putting your definition for guess inside the first while loop, perhaps.
Your problem is that guess is never changed. In order to have it change you would have to put the declaration of guess in the while loop. For instance:
hint = str
low = 0
high = 100
guess = (high + low)/2
answer = int(raw_input("Please think of a number between 0 and 100: "))
while (True):
print "Is your secret number " + str(guess) + "?"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
while (hint != "h" and hint != "l" and hint != "c"):
print "invalid option"
hint = raw_input("H, L, or C: ")
hint = hint.lower()
if (hint == "h"):
low = guess
print "newlow: " + str(low)
print "newGuess: " + str(guess)
elif (hint == "l"):
high = guess
elif (hint == "c"):
print "Correct, the answer was " + str(answer)
break
guess = (high + low)/2#For instance here
This would refresh the variable guess every time the loop loops.
In this sample I made it so guess refreshes after you declare low and high as guess, if you wanted low and high to be declared as the new value of guess you would put the declaration before the if statements.
If you have any questions feel free to ask in the comments.
Hope this helps.
For some reason when I select "run module", IDLE won't run the first line of code until I press "enter". It's not a huge problem for this type of program, but I'm confused why this is happening. Can anyone clear this up for me? Here's the code:
print("Please think a number between 0 and 100!")
guess = 50
upper = 100
lower = 0
status = ""
while status != "c":
print("Is your secret number ") + str(guess) + ("?")
print ("Lower: ") + str(lower)
print ("Upper: ") + str(upper)
status = raw_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 status == "h":
upper = guess
guess = guess - (guess - lower)/2
elif status == "l":
lower = guess
guess = guess + (upper - guess)/2
elif status == "c":
break
else:
print("Sorry, I did not understand your input.")
print("Game over. Your secret number was: ") + str(guess)
Thanks so much!
See http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/execution.html (see section 1.9.2). It's a bug that occurs sometimes if the previous program was interrupted.