Python While Loop woes - python

I am a brand new programmer, and I have been trying to learn Python (2.7). I found a few exercise online to attempt, and one involves the creation of a simple guessing game.
Try as i might, I cannot figure out what is wrong with my code. The while loop within it executes correctly if the number is guessed correctly the first time. Also, if a lower number is guessed on first try, the correct code block executes - but then all subsequent "guesses" yield the code block for the "higher" number, regardless of the inputs. I have printed out the variables throughout the code to try and see what is going on - but it has not helped. Any insight would be greatly appreciated. Thanks! Here is my code:
from random import randint
answer = randint(1, 100)
print answer
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print "Top of Loop"
print guess
print answer
i = i + 1
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
else:
print "else statement"
print "Congratulations! You got it in %r guesses." % i
print "Time to play a guessing game!"
print "Enter a number between 1 and 100:"
guess = raw_input()
guess = int(guess)
logic(guess, answer, i)
I'm sure it is something obvious, and I apoloogize in advance if I am just being stupid.

You've noticed that raw_input() returns a string (as I have noticed at the bottom of your code). But you forgot to change the input to an integer inside the while loop.
Because it is a string, it will always be greater than a number ("hi" > n), thus that is why "Too high. Try again:" is always being called.
So, just change guess = raw_input() to guess = int(raw_input())

Try this:
guess = int(raw_input())
As raw_input.__doc__ describes, the return type is a string (and you want an int). This means you're comparing an int against a string, which results in the seemingly wrong result you're obtaining. See this answer for more info.

Ok, I found your problem. The problem is in this Code:
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
In the code above you are getting your input as string, but you try to compare it with integer. All you need to do is to convert the input to integer, like this:
guess = raw_input()
guess = int(guess)
This should solve your problem :)

I updated the program. You came out of the while loop because after you get guesss as input inside elif group, you forget to convert that to int, so it throwed back error. Now, corrected but you can also optimise it.
import sys
from random import randint
answer = randint(1, 100)
'''randint(1, 100)'''
print (answer)
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print ("Top of Loop")
print (guess)
print (answer)
i = i + 1
if guess < answer:
print ("Too low. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
elif guess > answer:
print ("Too high. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
else:
print ("else statement")
print ("Congratulations! You got it in %r guesses." % i)
print ("Time to play a guessing game!")
print ("Enter a number between 1 and 100:")
guess = input()
guess = int(guess)
logic(guess, answer, i)

Related

Python; How do I test if something is in a list?

I was writing a code that will ask you to play a guessing game. It will ask you whether you want to play or not and proceed.
It was supposed to ask a number again if the entered value is not in the list but It is not working. I couldn't get it. Thx by now!
import random
import math
import time
repeat=True
numbers = ["1","2","3","4","5"]
gamestart=False
gamecontinue=True
def guess():
chosennumber=random.choice(numbers)
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber==chosennumber and guessnumber in numbers:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
print
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
elif not guessnumber in numbers:
while not guessnumber in numbers:
guessnumber=raw_input(">Please enter a number between 0 and 6:")
if raw_input(">Do you want to play guessing game? Y or N:") == "Y":
gamestart=True
else:
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
while gamestart==True and gamecontinue==True:
guess()
if raw_input (">Do you want to play again? Y or N:") == "N":
gamecontinue=False
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
so you figured out what was the issue, good! but i have one more tip for you, a better approach to achieve this is check if the input is correct as soon is readed, if it is correct you keep going, if it not, you ask for it again right there:
while True:
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber in numbers:
print "good!"
break
else:
print "bad!"
and now you're sure that the input is correct so you only check:
if guessnumber==chosennumber:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
else:
print "That is not right."
print "I chose %d." % (int(chosennumber))
if number not in numbers
That will do the trick
It checks if it is true that the selected number is in the list
The problem is that if you put two elif statements the first one will proceed first.
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
This condition will be asked first. But if you look again at it whether the input (guessnumber) is in the list or not it will proceed. So if we want it to become a condition which we enter a number that is in a list but not matching with the chosen number, we will add another condition to elif statement.
code will be like this
elif guessnumber!=chosennumber and guessnumber in numbers:
Slight detail but good to keep in mind I think.

Guessinggame (replace variable issue)

so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to
1) prompt the user to enter a guess and store the value in the "guess" variable,
2) if guess is greater than goal print...
3) if guess is lower than goal... print...
4) if guess is same as goal, print...
Unsure how to fix this. Any help will be greatly appreciated. Code as below.
#Author: Anuj Saluja
#Date: 17 October 2016
import random
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
print()
inputguess = int(input("Please guess the number: ")
while (guess != goal):
if inputguess > goal
print ("Too high, try again.")
if inputguess < goal
print ("Too low, try again.")
if inputguess == goal:
break
if inputguess == goal:
print ("Well done!")
print ("See you later.")
The code is only asking for a guess once before the while loop. You need to update the guess variable inside the while loop by asking for input again.
I think you are looking for this. hope this will work.
import random
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
inputguess = int(input("Please guess the number: "))
while True:
if inputguess > goal:
inputguess = int(input("Too high, try again: "))
elif inputguess < goal:
inputguess = int(input("Too low, try again: "))
elif inputguess == goal:
print ("Well done!")
print ("See you later.")
break
Put this line :
inputguess = int(input("Please guess the number: ")
inside the while loop. The code is only asking the user input once, user input must be in the loop.
Have you read your stack trace in detail? It's very easy to just skim over them, but stack traces can actually provide a lot of very useful information. For instance, the message is probably complaining that it was expecting a closing parenthesis. The line:
inputguess = int(input("Please guess the number: ")
should actually be
inputguess = int(input("Please guess the number: "))
The stack trace says the error is on line 16 because that's where the interpreter realized something was wrong. More often than not, the buggy code will be in the last line of code before the line it gives you.
also as other people stated, you need to put the input statement within the while loop in order to update the variable.
You should also consider replacing tab characters with 4 spaces so it displays consistently no matter where you read it. Usually the text editor or IDE will have tab settings that you can change when you hit tab, it will type 4 spaces. A quick Google search along the lines of "{text editor} change tab settings" will usually bring up results on how to change it, where {text editor} is the name of the editor/IDE you're using.
You should also consider indenting the code within your if statements as it improves readability
So I had someone help me irl and this works perfectly for anyone interested. Thanks everyone for help. :) Appreciate it.
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
print()
while guess != goal:
guess = int(input("Please guess the number: "))
if guess > goal:
print ("Too high, try again.")
if guess < goal:
print ("Too low, try again.")
if guess == goal:
break
if guess == goal:
print ("Well done!")
print ("See you later.")

Whats wrong with this guess the number game code?

#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("You will choose a random number between 1-100")
print ("and the computer must guess what it is.")
print ()
number = int(input("Please choose a number between 1-100: "))
guesses = 0
guess = 0
while guess != number:
guess = ("My guess is: ",random.randint(1,100))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you") print ("guesses,"guesses!")
Basically you choose a number and the computer has to keep guessing until it gets it right but I can't seem to get it to work.
You should learn basic debugging skills. The simplest way to debug this program would be to add print() statements to see what values are in your variables.
Your basic problem is that you set guess to a tuple with two values: the string "My guess is: " and a random number from 1 to 100. You probably intended to set guess to just the number.
You probably want something like this:
guess = random.randint(1,100)
print("My guess is: {}".format(guess))
This will get you one step closer. Then you will need to figure out how to change the program so that it narrows down the guess range. If you have trouble with that, maybe you should find someone to tutor you a bit.

Display Variable value in Python using print Statement?

I have created a Python program that guesses the number programmer thinks in mind. Everything is working file but i don't know how to use guess in print statement in a way that print statement display number as well. I tried adding word "guess" but it is not working. I am C programmer and working with Python for the first time, so i am unable to figure it out.
hi = 100
lo = 0
guessed = False
print ("Please think of a number between 0 and 100!")
while not guessed:
guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = 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 user_inp == 'c':
guessed = True
elif user_inp == 'h':
hi = guess
elif user_inp == 'l':
lo = guess
else:
print ("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)
Just convert it to string.
print ("Game over. Your secret number was: " + str(guess))
You could also use string formatting.
print("Game over. Your secret number was {}".format(guess))
Or, since you come from a C background, old style string formatting.
print("Game over. Your secret number was %d." % guess)
Try this in your print statement and let me know if it works.
str(guess)
Python has very nice string formatting, which comes in handy when you need to insert multiple variables:
message = "Game over after {n} guesses. Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)

Guessing game in python

I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"

Categories

Resources