Why condition "else" doesn't work in my python code - python

here is my code.
highnum=100
lownum=0
guessnum=highnum/2
print "Please think of a number between 0 and 100!"
while True:
print "Is your secret number is "+str(guessnum)+"?"
print "Enter 'h' to indicate the guess is too high.",
print "Enter 'l' to indicate the guess is too low. ",
print "Enter 'c' to indicate I guessed correctly."
result=raw_input()
if result=="h":
highnum=guessnum
guessnum=int(highnum+lownum)/2
if result=="l":
lownum=guessnum
guessnum=int(highnum+lownum)/2
if result=="c":
break
else:
print "Sorry, I did not understand your input."
print "Game over. Your secret number was: "+str(guessnum)+" ."
Everytime I type the input, it prints out "Sorry, I did not understand your input." The condition "else" doesn't work.
I don't know why. Could anyone help me? Thank you very much!

Because as written, each of your if statements are independent, the else only corresponds to your last if result == 'c', so if they don't type 'c', they hit your else case.
Instead, you can use if/elif/else to try each of your cases.
if result=="h":
highnum=guessnum
guessnum=int(highnum+lownum)/2
elif result=="l":
lownum=guessnum
guessnum=int(highnum+lownum)/2
elif result=="c":
break
else:
print "Sorry, I did not understand your input."

Related

Why isn't my program noticing the equivalency between letters?

I am working on making a simple game of Hangman in Python 2. The code I have so far is the ground work I have for it, but it doesn't seem to be working. If I could have a simple wake-up call as to what about what code I made isn't working I would appreciate it.
Code:
secret_word = 'tracy'
secret_word_list = []
for letter in secret_word:
secret_word_list += letter
print secret_word_list
def get_guess(guess = input("Guess: ")):
while len(guess) != 1:
print "Your guess must be exactly one character!"
guess = input("Guess: ")
while guess.isalpha() == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
while guess.islower == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
else:
return guess
while True:
if str(get_guess) in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
get_guess(guess = input("Guess: "))
Output:
Output of the Code
You've got several problems here, but the big one is that you're not calling functions, so you compare the function itself to the secret.
Code with fixes:
secret_word = 'tracy' # Don't make secret_word_list, there's no point; just use the str itself since you only test len 1 strings against it anyway
print secret_word
def get_guess(guess): # Don't make the default call input, that'll prompt once for an input and store it as the permanent default
while True:
# Test each condition and break loop only if all past; original code would never
# recheck length if new value entered after testing isalpha
if len(guess) != 1:
print "Your guess must be exactly one character!"
elif not guess.islower(): # Add missing call parens on islower; use not, never compare to False; islower implicitly verifies isalpha, so avoid testing isalpha
print "Your guess must be a lowercase letter!"
else:
break # Passed all tests, break loop
# Get new guess if any test failed
guess = raw_input("Guess: ") # Use raw_input on Python 2, never input (which eval's the result of raw_input)
# Removed else (loop always ends by breaking, using else nonsensical but harmless in original code too
return guess
while True:
# Move guess getting to if, because having it in else case never actually checked it
if get_guess(raw_input("Guess: ")) in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
Try it online!
Note: I kept the kinda odd behavior of having get_guess take an argument, but then reprompt for guesses on failure. A saner solution would be to remove the guess argument entirely, and move the guess = raw_input("Guess: ") to the top of the while loop (removing the else block at the end).
get_guess is a function, you need to put () after it to call the function.
You shouldn't put the call to input() as a default argument. The default value is evaluated once, when the function is defined, not every time the function is called. You should assign guess inside the function.
You should test for all the invalid inputs in a single loop.
def get_guess():
while True:
guess = input("Guess:")
if len(guess) != 1:
print "Your guess must be exactly one character!"
continue
if not guess.isalpha() or not guess.islower():
print "Your guess must be a lowercase letter!"
continue
break
return guess
while True:
guess = get_guess()
if guess in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"

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.

Prompt error message for python

def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter")
if answer == 'a' or 'A':
print "You chose 'a'!"
elif answer == 'b' or 'B':
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()
This is my code. It's very simple, but for some reason it keeps returning and error message of reference error: 'prompt' is undefined
This is probably not going to solve the problem you are having (although the code worked for me in an iPython shell), there is an issue with your if/else statements. The following statement:
if answer == 'a' or 'A':
print "You chose 'a'!"
will always print "You chose 'a'!" regardless of the letter you enter upon prompting. In python, the or expression you are using asks the following question: Is the answer given equal to 'a' OR is the boolean value of "A" True? What you mean to ask is: Is the answer given equal to 'a' OR is the answer given equal to "A"? This is most concisely represented through:
if answer.lower() == 'a':
print "You chose 'a'!"
That should solve at least one problem that this code is having.
As #Bhargav Rao commented, your code does not match your error, when you run it you will get an output of a regardless of what you enter.
This is because if answer == 'a' or 'A': is the same as saying:
if answer == 'a': OR if 'A': <-- this is always true
To fix this you can use the condition in:
def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter: ")
if answer in ['a','A']:
print "You chose 'a'!"
elif answer in ['b','B']:
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()

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)

Python While Loop woes

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)

Categories

Resources