Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learn Python The Hard way 36 code efficiency

Tags:

python

Hello I'm studying the book "Learn Python The Hard Way" by Zed Shaw and I have reached exercise 36 where we right our own game from scratch using loops and if statements.

My game is finished and it's running however the code itself looks so messy and inefficient. The main problem is with trying to get the user's choice and having to rewrite the same code for the same word but with a capital letter, example:

    def puzzle1():
print "\"A cat had three kittens: January,March and May. What was the mother's name.\""

choice = raw_input("Mother's name?: ")
if "What" in choice:
    print "You are correct, the door opens."
    door2()
elif "what" in choice:
    print "You are correct, the door opens."
    door2()
elif "WHAT" in choice:
    print "You are correct, the door opens."
    door2()
elif "mother" in choice:
    print "Haha funny... but wrong."
    puzzle1()
else:
    print "You are not correct, try again."
    puzzle1()

I wonder if there is a way to have all these choices in one line, also if there is anything else I can make more efficient please let me know. Sorry for the silly question I'm new to programming.

like image 563
Budaika Avatar asked Mar 22 '26 10:03

Budaika


1 Answers

Use str.lower and remove the multiple if/elif's for what.

choice = raw_input("Mother's name?: ").lower()
if "what" in choice:
    print "You are correct, the door opens."
    door2()
elif "mother" in choice:
    print "Haha funny... but wrong."
    puzzle1()
else:
    print "You are not correct, try again."
    puzzle1()

I would also loop instead of repeatedly calling puzzle1, something like:

while True:
    choice = raw_input("Mother's name?: ").lower()
    if "what" in choice:
        print "You are correct, the door opens."
        return door2()
    elif "mother" in choice:
        print "Haha funny... but wrong."
    else:
        print "You are not correct, try again."
like image 52
Padraic Cunningham Avatar answered Mar 24 '26 22:03

Padraic Cunningham