Why condition “else” doesn't work in my python code

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!

Answers


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

Need Your Help

Use diferent methods based on parameter from constructor

java constructor polymorphism

I have a class that should have slightly diferent method implementations based on a parameter I would pass to the class constructor. However, I would like to select which implementation to run at the

Importing a CSV file in pandas into a pandas dataframe

python csv pandas

I have a CSV file taken from a SQL dump that looks like the below (first few lines using head file.csv from terminal):

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.