6
\$\begingroup\$

I am new to Python and I have tried to come up with a code for the number guessing game. But I am pretty sure this is not the right way to do it. I am able to get the right output, however, my code is pretty long. Any ideas on using a different logic or to reduce the code size would help.

I also would like to know how to code profile a python code for performance.

I am using IDLE and Python 3.+

import random

def main():
    while(True):
        inputchoice = input("Are you ready? Y/N : ")    
        if(inputchoice.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
            print("Ok. Lets begin")
            randomnumberguessinggame()
            break
        elif(inputchoice.strip() in ("no","No","NO","nO","n","N")):    
            print("Let me know when you are ready")
            break
        else:
            print("Invalid Entry. Try again")

def randomnumberguessinggame():
    print("Get ready to start guessing")
    actualnumber = random.randrange(0,1000)
    #print("The number to be guessed is %d"%actualnumber)
    flag = True;
    while(flag):
        try:
            guessednumber = int(input("Enter your guess "))
            if(guessednumber > actualnumber):
                print("That was a wrong guess. Your guess is higher than my number")                
                while(True):
                    retry = input("Would you like to try again? Y/N : ")
                    if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
                        flag = True;
                        break
                    elif(retry.strip() in ("no","No","NO","nO","n","N")):
                        flag = False;
                        break
                    else:
                        print("Invalid Entry. Try again")
            elif(guessednumber < actualnumber):
                print("That was a wrong guess. Your guess is lower than my number")                
                while(True):
                    retry = input("Would you like to try again? Y/N : ")
                    if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
                        flag = True;
                        break
                    elif(retry.strip() in ("no","No","NO","nO","n","N")):
                        flag = False;
                        break
                    else:
                        print("Invalid Entry. Try again")
            else:
                print("You've got it right. Congratulations!!")
                flag = False;
        except ValueError:
            print("Your guess is invalid. Kindly guess again.")
            flag = True;

main()

print("Exiting the game...")
\$\endgroup\$
  • 4
    \$\begingroup\$ Small point: Why not replace the inputchoice.strip() in ("y","Y","yes"," ...) by just inputchoice.strip().lower().startswith('y')? \$\endgroup\$ – John Coleman Feb 4 '17 at 13:40
  • 1
    \$\begingroup\$ @JohnColeman Feel free to point that out in an answer. As for the reason? Beginners usually don't know such thing :-) \$\endgroup\$ – Mast Feb 4 '17 at 18:17
3
\$\begingroup\$

Advice 1

I would not abuse the user with the question whether he wants to continue; just have a command (say, quit) for quitting the game while still guessing.

Advice 2

randomnumberguessinggame

The Python way is random_number_guessing_game.

Advice 3

You don't have to use parentheses in the branch and loop conditionals.

Summa summarum

I had this in mind:

import random


def main():
    actual_number = random.randrange(0, 1000)
    while True:
        guess = input("Enter your guess: ")

        if guess.strip().lower() == "quit":
            print("Bye!")
            return

        try:
            guess_number = int(guess)
        except ValueError:
            print(guess, "is not an integer!")
            continue

        if guess_number < actual_number:
            print("Your guess is too small.")
        elif guess_number > actual_number:
            print("Your guess is too large.")
        else:
            print(guess_number, "Excellent!")
            return

main()

Hope that helps.

\$\endgroup\$
2
\$\begingroup\$

For starters, remove all the semicolons, this is not Java or C#. Furthermore, You can extract a function that handles all the questions for confirmation. Next, why not consider every answer that is not a confirmation as a 'no' if you choose to ask that many times which I wouldn't.

I'd write it as follows:

import random

def play():
    print("Get ready to start guessing!")
    guessing_game(random.randrange(0, 1000))
    print("Congratulations!! Exiting the game...")

def guessing_game(number):
    try:
        guess = int(input("Enter your guess: "))
        if guess == number:
            return
        print(["Higher!", "Lower!"][guess > number])
    except ValueError:
        print("Invalid!")
    guessing_game(number)

if __name__ == '__main__':  # this the proper way
    play()
\$\endgroup\$
  • \$\begingroup\$ @Graipher I wouldn't argue with the loop ;-) But since the OP asked to reduce code size (not to improve performance, memory footprint or readability), I went with the recursion. \$\endgroup\$ – schwobaseggl Feb 4 '17 at 15:38
  • \$\begingroup\$ Fair enough. Anyways, you already got my +1 for your first sentence. \$\endgroup\$ – Graipher Feb 4 '17 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.