1

I got the idea for this guessing game from a book, Invent With Python. I didn't like that the original script didn't cover the possibilities of re-guessing a number or incorrectly using a number not in 1 - 20, so I modified it. The program works great, however, I'm just wrapping my head around if/elif/else code blocks.

I'd like to rewrite the script without having to nest and if inside of an if. I can't even begin to wrap my head around how to do that. Can anyone please help me--just one example of how this program could work without nesting would be great!

Here's the little script in its entirety:

from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)

guesses_left = 6
already_guessed = []

while guesses_left > 0:
    try:
        guess = int(raw_input("Take a guess: "))

        if guess >= 1 and guess <= 20 and guess not in already_guessed:
            already_guessed.append(guess)
            guesses_left -= 1

            if guess == secret_number:
                print "You win! %d was my secret number!" % secret_number
                exit(0)
            elif guess < secret_number:
                print "Your guess is too low!"
            elif guess > secret_number:
                print "Your guess is too high!"

        elif guess in already_guessed:
            print "You already guessed that!"

        else:
            print "Not a number between 1 - 20!"
            print "Please try again!"

        print "You have %d guesses left!" % guesses_left

    except ValueError:
        print "Invalid input! Please try again!"    
1
  • 1
    You can make use of the continue statement, which will also help unnest everything but the input from the try. Commented Aug 14, 2016 at 23:49

2 Answers 2

5

Try it like this, using continue to exit the current iteration of the loop and start again at the top of the loop.

You also had a logic bug here:

if guess <= 1 and guess >= 20 and guess not in already_guessed:

A number cannot possibly be both less than or equal to 1, and greater than or equal to 20. Your and should have been an or like this:

if (guess <= 1 or guess >= 20) and guess not in already_guessed:

Or simpler:

if 1 <= guess <= 20 and guess not in already_guessed:

Also, keep your try/except only around the things that can actually raise an exception (or shouldn't happen if an exception occurs:

from random import randint
import sys

name = raw_input("Hello! What's your name? ")
print "Well {}, I'm thinking of a number between 1 and 20.".format(name)
print "Since I'm a benevolent computer program, I'll give you 6 guesses."

secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []

while guesses_left > 0:
    print "You have {} guesses left!".format(guesses_left)

    try:
        guess = int(raw_input("Take a guess: "))
    except ValueError:
        print "Invalid input! Please try again!\n"
        continue

    # If the number is not between 1 and 20...
    if not (1 <= guess <= 20):
        print "Not a number between 1 - 20!"
        print "Please try again!\n"
        continue

    if guess in already_guessed:
        print "You already guessed that!\n"
        continue

    guesses_left -= 1
    already_guessed.append(guess)

    if guess == secret_number:
        print "You win! {} was my secret number!".format(secret_number)
        sys.exit(0)
    elif guess < secret_number:
        print "Your guess is too low!\n"
    elif guess > secret_number:
        print "Your guess is too high!\n"

Here's an example run:

Hello! What's your name? :)
Well :), I'm thinking of a number between 1 and 20.
Since I'm a benevolent computer program, I'll give you 6 guesses.
You have 6 guesses left!
Take a guess: 2
Your guess is too low!

You have 5 guesses left!
Take a guess: 2
You already guessed that!

You have 5 guesses left!
Take a guess: 3
Your guess is too low!

You have 4 guesses left!
Take a guess: 7
Your guess is too high!

You have 3 guesses left!
Take a guess: 5
Your guess is too high!

You have 2 guesses left!
Take a guess: 4
You win! 4 was my secret number!
Sign up to request clarification or add additional context in comments.

4 Comments

I liked this one the best, thank you! I especially liked the pointer on the try/except block--I must have misunderstood the on line python documentation about the try/except block--it looked like everything needed to be nested inside of it.
No problem, glad to help :) Yeah, think of try: ... except: ... as "run the code in this block, and if any of the code inside this block fails, immediately jump to the code in the except: and run it". So since the except: (in my example above) does a continue, the rest of the code in the loop will never execute. The code in the rest of the loop will never raise a ValueError. Sometimes, you actually do want to put code that won't raise an error inside the try: block, for example if you can't continue, break, or return, and you don't want the code to continue executing.
Also if this solves your problem, please click the checkmark next to the answer to mark the question as resolved :) Thanks!
Just hit the check button; again thanks! Also, the logic bug wasn't in my original script but an editing error here, one that I fixed.
1

Just change the nested if statements to elif like so:

from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)

guesses_left = 6
already_guessed = []

while guesses_left > 0:
    try:
        guess = int(raw_input("Take a guess: "))

        if guess <= 1 and guess >= 20 and guess not in already_guessed:
            already_guessed.append(guess)
            guesses_left -= 1

        elif guess == secret_number:
            print "You win! %d was my secret number!" % secret_number
            exit(0)
        elif guess < secret_number:
            print "Your guess is too low!"
        elif guess > secret_number:
            print "Your guess is too high!"

        elif guess in already_guessed:
            print "You already guessed that!"

        else:
            print "Not a number between 1 - 20!"
            print "Please try again!"

        print "You have %d guesses left!" % guesses_left

    except ValueError:
        print "Invalid input! Please try again!" 

This would be simplest way i see to solve your dilema

1 Comment

This fundamentally changes the control flow of the program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.