1
\$\begingroup\$

I just started learning Python this week and put this together for my first program (outside of a Hello World one). Does anyone have any feedback/suggestions for improvement for this? I've tried to forsee potential user input issues but I'd love to hear some thoughts from people who know what they are doing!

import random
guessesTaken = 0
# sets the guess counter
print ('Hello! What is your name?')
name = input()
# intro for user
print ('Hi, ' + name + ', I am thinking of a number between 1 and 100.' "\n" 'Do you want to try to guess my number? Please type yes or no.')
play = input()
# user inputs whether or not they want to play

while play != 'yes' and play != 'no':
    print ("I'm sorry, I didn't understand that. Please type yes or no.")
    play = input ()
# provision for invalid user input: if the input is not yes or no, they will be prompted to re-enter

    while play == 'yes':
    # the game continues
        number = random.randint (1,100)
    # the number will be between 1 and 100
        while guessesTaken < 20:
            print ('Take a guess!')
    # sets a max of 20 guesses
            try:
                guess = int(input())
            except:
                print ("I'm sorry, I didn't understand that. Please type a number between 1 and 100.")
                continue
    # provision for invalid input - if input is not an integer, user will be prompted to re-enter input
            guessesTaken += 1 
    # adds to the guess counter
            if guess < number:
                print ('Your guess is too low!' "\n" 'Try again. You have ' + str(20-guessesTaken) + ' guesses left.')
            elif guess > number:
                print ('Your guess is too high!' "\n" 'Try again. You have ' + str(20-guessesTaken) + ' guesses left.')
            elif guess == number:
                break
    # if the guess is too high or too low, the loop continues. If the user guesses right, the loop ends
        if guess == number:
            print ('You got it right!' "\n" 'It only took ' + str(guessesTaken) + ' guesses!')
    # in case of correct guess within the allowed number of tries
        else:
            print ('Sorry, the number I am thinking of is ' + str(number) + '.')                
    # if the user exceeds the number of guesses allowed    
        guessesTaken = 0
    # resets guess counter
        print ('That was fun, ' + name + '! Want to play again?' "\n" 'Please type yes or no.')
        play = input ()

# asks if user wants to play again, with provision for invalid input
if play == 'no':
    print ("That's too bad, see you next time!")
# ends the game
\$\endgroup\$
  • \$\begingroup\$ Is the indentation of the second while loop and everything following it correct? \$\endgroup\$ – Graipher Nov 18 '16 at 16:39
  • \$\begingroup\$ @Graipher Yeah, I nested them so that the option to play again at the end would be within the first while loop. Is that a good way to do it? \$\endgroup\$ – Preeths Nov 18 '16 at 16:52
  • \$\begingroup\$ You may want to migrate your stanzas to functions, so that the logic of your main algorithm is clear (currently, one cannot see the wood for the trees). \$\endgroup\$ – boardrider Nov 18 '16 at 19:21
2
\$\begingroup\$

Commenting

Almost universally, comments go before the code they're commenting, rather than after. Conforming to what people expect will make it much easier to read.

Comments should describe why, not what.

# the game continues
while play == 'yes':

# sets a max of 20 guesses
while guessesTaken < 20:
        print ('Take a guess!')

# adds to the guess counter
guessesTaken += 1 

That's all examples of where you're describing something that's kind of obvious from looking at the code. This makes it harder to read, because they's more going on. Here's an example of a better comment:

try:
    # If the user enters a number out of range, still counts as a guess
    guess = int(input())
except:
    print ("I'm sorry...")
    continue

Code to show intentions

I'm guessing you haven't learned about functions, so I won't say too much here. They're a good tool that would help a lot to make things more clear. Instead, let's talk about your main loop.

while play != 'yes' and play != 'no':
    print ("I'm sorry, I didn't understand that. Please type yes or no.")
    play = input ()

This looks like a section to do input validation. This is why @Graipher asked if the indentation afterward was correct. To make it more clear, break up the continuation from the validation:

while play != "no":

    #Invalid input
    if play != "yes":
        print ("I'm sorry, I didn't understand that. Please type yes or no.")
        play = input ()
        continue

It's also common to do something like while True, then explicitly break out whenever you're done.

Now, guessesTaken is in a lot of places it doesn't really need to be, which makes it hard to keep track of. Instead of setting it at the beginning, just set it at the beginning of the loop.

while play == 'yes':
    number = random.randint (1,100)
    guessesTaken = 0

This way, your initialization happens in one place, when you use the variable you don't have to go back as far to see what it is, and you don't have to reset it at the end.

Everything is kind of running together. You can use blank lines (and functions!) to break it into logical sections. In the play loop, you can put a blank line in between when you get the guess, and when you check it. Indenting your comments to align with the rest of the code will also make it easier to see the blocks.

Finally, while play == 'yes': This should really be if instead of while. Right now, you have three different loops, which makes it hard to keep track of where the breaks and continues are sending you.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you so much!!! I'm still learning the very basics and want to make sure I'm moving forward in the best way, and this is extremely helpful! \$\endgroup\$ – Preeths Nov 19 '16 at 19:35

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.