Program stuck on reverse python guessing game - python

My program is stuck while it tells you to think of a number in the range of selected numbers and I'm unsure how to fix this.
I'm not entirely sure what I'm doing even but the start of the program works properly.
from random import randrange
import time
def guessNumber(min_no, max_no):
try:
return randrange(min_no, max_no)
except ValueError:
return min_no
left = 0
right = len(L)-1
while left<=right:
m = (left+right)//2
if x == L[m]:
return m
elif x < L[m]:
right = m-1
else: # L[m] < x
left = m+1
def userNoInput(msg):
while 1:
try:
return int(input(msg))
except:
print("Numbers Only !")
sys.exit(0)
print("Enter two numbers, low then high.")
min_no = userNoInput("low = ")
max_no = userNoInput("high = ")
print ("Think of a number in the range %d and %d."%(min_no, max_no))
max_no += 1
while True:
guess = guessNumber(min_no, max_no)
count = 0
L = []
for i in range(low, high+1):
L.append(i)
while True:
print("Is your number Less than, Greater than, or Equal to %d ?") % (L[(int(len(L)/2))])
guess = guessNumber(low, high)
guess = input("Type 'L', 'G' or 'E': ")
guess = guess.upper()
if guess == 'E':
break
elif guess == 'L': guess < number
elif guess == 'G': guess > number
else:
print (guess)
print ("Your number is" + guess + "." + "I Found it in" + number + "guesses.")
desired output:
Enter two numbers, low then high.
low = 2
high = 18
Think of a number in the range 2 to 18.
Is your number Less than, Greater than, or Equal to 10?
Type 'L', 'G' or 'E': g
Is your number Less than, Greater than, or Equal to 14?
Type 'L', 'G' or 'E': L
Is your number Less than, Greater than, or Equal to 12?
Type 'L', 'G' or 'E': L
Your number is 11. I found it in 3 guesses.

Yep, the infinite loop in over first guessing caused program to hang.
There should be only one event loop, something like this:
from random import randrange
import time
def guess_number(min_no, max_no):
return randrange(min_no, max_no)
def user_num_input(msg):
try:
return int(raw_input(msg))
except ValueError:
print('Numbers Only!')
sys.exit(1)
def get_hint(current_guess):
return raw_input('Is your number Less than, Greater than, or Equal to %d? (L, G, E): ' % current_guess)
print('Enter two numbers, low then high.')
min_no = user_num_input('low = ')
max_no = user_num_input('high = ')
assert max_no >= min_no
print ('Think of a number in the range %d and %d.' % (min_no, max_no))
iteration = 1
while True:
guess = guess_number(min_no, max_no)
hint = get_hint(guess)
while hint not in ['E', 'L', 'G']:
print('You gave unknown answer. Please retry.')
hint = get_hint(guess)
if hint == 'E':
break
elif hint == 'L':
max_no = guess
elif hint == 'G':
min_no = guess
else:
raise ValueError('Unreachable!')
iteration += 1
print ('Your number is %d. I found it in %d guesses.' % (guess, iteration))

This code will do it for you . There were many mistakes in that code of yours :-
1.) Infinite While loop ( while True:
guess = guessNumber(min_no, max_no) ) .
2.) You dont need lists/arrays for this problem.
3.) while True:
guess = guessNumber(min_no, max_no) , this function is wrong . since you are returning the value ,it is not going past the except statement.
4.) No need of def userNoInput(msg): function , anyways no issues.
5.) The last line ( Print statement is wrong too )
Hoping this will help you
P.S:- Just a suggestion , whenever you get an infinite loop or some issues like that , you should firstly try yourself by printing statements inside loop and see where the issue is .
from random import randrange
import time
def guessNumber(min_no, max_no):
left = min_no
right = max_no
if left == right:
return left
m = (left+right)/2
return m
def userNoInput(msg):
while 1:
try:
return int(input(msg))
except:
print("Numbers Only !")
sys.exit(0)
print("Enter two numbers, low then high.")
min_no = userNoInput("low = ")
max_no = userNoInput("high = ")
# print min_no,max_no
print ("Think of a number in the range %d and %d."%(min_no, max_no))
max_no += 1
count = 0
while True:
count+=1
guess = guessNumber(min_no, max_no)
print("Is your number Less than, Greater than, or Equal to %d ?") %guess
temp = raw_input("Type 'L', 'G' or 'E': ")
temp = temp.upper()
if temp == 'E':
break
elif temp == 'L':
max_no = guess-1;
elif temp == 'G':
min_no = guess+1;
print "Your number is %r . I Found it in %r guesses." %(guess,count)

Related

This is a number guessing game the num_check function works just fine the first time but won't run any second attempts. Does anyone know why?

import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After getting input from console, you should create a loop which breaks when guessed number equal to input. For example:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After revision, code seems like:
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
It's because python programs runs from top to bottom, and when it reaches the bottom it's done and stops running. To stop this order we have multiple different ways:
We can call a function, as you do in you're program.
Selection Control Structures: As if statements
Iteration Control Structures: As loops
The last one is the one you need in this solution. Wrap code in a while loop, with the correct condition, in you're example, this would be
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
The best way woul be to use a will loop as follow:
while guess != num:
You should use while True:, because your guessing code runs only once without it
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 10)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
att = 1
num = num_gen()
while True:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
print('Your guess was HIGH! Please guess another number between 1 and 100: ')
att += 1
elif result == 'low':
print('Your guess was LOW! Please guess another number between 1 and 100: ')
att += 1
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
break
how can you expect it to run more than 1 time if you have not used any loop in the program. For example in this case you should use a while loop, then only it will prompt the user again and again and will check for the conditions, set a game variable to be True. When the number is matched then simply set the game variable to be False and it will end the loop.
import random
# Set the game variable initially to be True
game = True
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while game:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
game = False

How do I stop redefining a variable after every loop of a function?

I am relatively new to Python, but I tried making random number generator guessing game where you just guess the number and if it's right you win and if you lose the attempt counter decreases, like this:
import random
a = random.randint (1, 20)
c = input('Select difficulty (1, 2, 3, 4) : ')
d = int(c)
def main():
if d == 1:
tries = e = 15
elif d == 2:
tries = e = 10
elif d == 3:
tries = e = 5
elif d == 4:
tries = e = 3
else:
tries = e = 1
for tries in range(tries, -1, -1):
tries -= 1
b = int(input('Pick a number from 1-20 : '))
if a == b:
print('Congratulations!')
print('# of tries : ', e - tries)
exit()
elif tries == 0:
print('No more attempts left, game over')
exit()
else:
print('Incorrect')
print('Attempts left : ', tries)
restart = input("Play again? (y/n)")
if restart == "y":
main()
else:
exit()
main()
So this program doesn't make sense unless you guess correctly on the first try because the attempt counter always stays the same. I think it's because everytime it goes back to the main() it redefines 'tries' as 15, 10, etc. The problem is if I put the 'if d == 1' section before def main() then it will say that 'tries' was referenced before assignment. There's probably a simple solution that I'm not seeing here and it's going way over my head, so hopefully what I'm asking makes sense. Feedback on the code irrelevant to the issue also appreciated.
Thanks.
The other answers will work just fine, but as a side note, you're calling main() inside main() which creates a recursive function. Unless you have a particular reason to do this, it should be avoided. Every previous attempt at the game will be held in memory until the user opts not to retry, and if you go far enough you'll run into a RecursionError. Try wrapping the whole program in a while loop, something like this:
import random
def main():
retry = True
while retry:
answer = random.randint(1, 20)
tries = 5 # Insert your own logic for num of tries
while tries > 0:
guess = int(input('Pick a number between 1 and 20: '))
if guess == answer:
print('Correct!')
break
else:
print('Incorrect')
tries -= 1
retry = input("Play again? (y/n)") == 'y'
main()
It's a little confusing to me why you're doing tries = e = num
A much cleaner way to do it would be to have a while loop that runs while the number of tries hasn't run out. You could set that number of tries to a variable based on the selected difficulty
One way to do it could be like this:
import random
# set number of tries based on difficulty chosen first, then all this
number = random.randint(1,50)
number_of_guesses = 0
while number_of_guesses < tries:
guess = input("Take a guess ")
guess = int(guess)
number_of_guesses = number_of_guesses + 1;
guesses_left = tries - number_of_guesses;
if guess < number:
print("Your guess is too low! You have " + str(guesses_left) + " guesses left")
if guess > number:
print("Your guess is too high! You have " + str(guesses_left) + " guesses left")
if guess == number:
break
if guess == number:
print("Good job! You guessed the number in " + str(number_of_guesses) + " tries :)")
if guess != number:
print("Sorry. The number I was thinking of was " + str(number) + " :)")
I changed the for loop to a while loop, removed the "tries = e = 15" and moved the "tries -= 1"
import random
a = random.randint (1, 20)
c = input('Select difficulty (1, 2, 3, 4) : ')
d = int(c)
def main():
if d == 1:
tries = 15
elif d == 2:
tries = 10
elif d == 3:
tries = 5
elif d == 4:
tries = 3
else:
tries = 1
while tries > 0:
b = int(input('Pick a number from 1-20 : '))
if a == b:
print('Congratulations!')
print('# of tries : ', tries)
exit()
else:
print('Incorrect')
tries -= 1
print('Attempts left : ', tries)
restart = input("Play again? (y/n)")
if restart == "y":
main()
else:
exit()
main()

Why does this guessing code in python keep stopping

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!"

Data being Stored in wrong Object

SORRY FOR THE MESSY AND INEFFICIENT CODE
Let me start with the basic rules for the code. A bag is stored under a mattress and each bag can only contain coins. Individually they can only contain a single type of coin. So the pennies bag cannot contain dimes or any other coin, only pennies.
Ok so, the Issue I have here is that when I deposit money it doesn't matter what "Bag" I deposit into, the coins automatically go to the Dime bag and I can't find where in the code this is happening. From my viewpoint, the code makes sense(Which it would to me but not the computer). I really think I just need a second set of eyes looking at it. I'm also not a python programmer which doesn't really help
import os
class Bags:
def __init__(self, nOC, n, v):
self.name = n
self.numOfCoins = nOC
self.value = v
self.SetBal()
# Setters
def SetBal(self):
self.amount = self.numOfCoins * self.value
def SetCoin(self, coin):
self.numOfCoins += coin
self.SetBal()
# Getters
def GetBal(self):
return self.amount
class Mattress:
def __init__(self):
self.pBag = Bags(0, "Pennies", 0.01)
self.dBag = Bags(0, "Dimes", 0.05)
self.nBag = Bags(0, "Nickles", 0.10)
self.qBag = Bags(0, "Quarters", 0.25)
self.boBag = Bags(0, "Bug-Out-Bag", 0.00)
# Setters
# Getters
def GetBalances(self):
pen = self.pBag.GetBal()
print("Balance of pennies : $%.2f. %d pennies" % (pen, self.pBag.numOfCoins))
print("Balance of dimes : $%.2f. %d dimes" % (self.dBag.GetBal(), self.dBag.numOfCoins))
print("Balance of nickles : $%.2f" % self.nBag.GetBal())
print("Balance of quarters: $%.2f" % self.qBag.GetBal())
total = self.pBag.GetBal() + self.qBag.GetBal() + self.dBag.GetBal() + self.nBag.GetBal()
print("Total : $%.2f" % total)
def main ():
# Check laod or what not for what you have to do and all that good stuff
userMain = Mattress()
mainLoop = True
menu = '''What would you like to do?
D. Deposit Money
W. Withdraw Money
T. Transfer Funds
S. Show Balances
E. Exit'''
diffBags = '''
P. Pennies
D. Dimes
N. Nickles
Q. Quarters
C. Cancel'''
while(mainLoop):
print(menu)
action = input("Select an option: ")
if action == 'D' or action == 'd' :
depositMenu = "What bag would you like to deposit into? " + diffBags
depLoop = True
while(depLoop):
print(depositMenu)
depAction = input("Select an option: ")
depAmt = "How much would you like to deposit? "
if depAction == 'P' or action == 'p':
while True:
try:
depCoin = int(input(depAmt))
if depCoin < 1:
print("Invalid. Please enter a positive number")
continue
break
except ValueError:
print("Invalid. Please enter a positive number")
userMain.pBag.SetCoin(depCoin)
depLoop = False
elif depAction == 'D' or action == 'd':
while True:
try:
depCoin = int(input(depAmt))
if depCoin < 1:
print("Invalid. Please enter a positive number")
continue
break
except ValueError:
print("Invalid. Please enter a positive number")
userMain.dBag.SetCoin(depCoin)
depLoop = False
elif depAction == 'N' or action == 'n':
while True:
try:
depCoin = int(input(depAmt))
if depCoin < 1:
print("Invalid. Please enter a positive number")
continue
break
except ValueError:
print("Invalid. Please enter a positive number")
userMain.nBag.SetCoin(depCoin)
depLoop = False
elif depAction == 'Q' or action == 'q':
while True:
try:
depCoin = int(input(depAmt))
if depCoin < 1:
print("Invalid. Please enter a positive number")
continue
break
except ValueError:
print("Invalid. Please enter a positive number")
userMain.qBag.SetCoin(depCoin)
depLoop = False
elif depAction == 'C' or action == 'c':
depLoop = False
elif action == 'W' or action == 'w':
print ("working on it")
elif action == 'T' or action == 't':
print ("working on it")
elif action == 'S' or action == action == 's':
userMain.GetBalances()
elif action == 'E' or action == 'e':
print("Have a great day")
mainLoop = False
else:
print ("Incorrect value")
if __name__ == "__main__":
main()
I found your problem.
Let me explain to you how I found your problem, so next time you can find it.
I added a line to your code
print("Q")
userMain.qBag.SetCoin(depCoin)
Given what your program was trying to do I expected that to be printed when I tried to add quarters. But it was never printed, indicating that something had gone before that point.
Next I added another line:
depAction = input("Select an option: ")
print("GOT", depAction)
Then I ran the program again, and it printed.
Now I know the problem is somewhere between the two print statements. Given that the program ends up adding it to the dimes, it makes it look like somehow we ended up running the dimes-adding code even though I had entered q. I look at the code which checked for entry into the dimes section and saw the problem.
I see the problem, but the for sake of a didactic exercise I think you should find it yourself.

Is my Bisection Search Algorithm so wrong?

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.")

Categories

Resources