Loops: Course #8: You Own While/Else(The previous one doesn't really help!)


#1

My Code:
from random import randint

You have to declare the =guesses_left=

guesses_left = 3

You will have to declare the =random_number=

random_number = int(randint(1,10))
print random_number

while guesses_left > 0:
guess = int(raw_input("Your guess: \n"))
guesses_left -=1
if guess == random_number:
print 'You win!'
guesses_left = 0
break

if guesses_left == 0:
print 'You lose'
break

End of WHILE loop was reached

end of program

`python

Help me!


#2

this is my code

from random import randint

Generates a number from 1 through 10 inclusive

random_number = randint(1, 10)

guesses_left = 3

Start your game!

while guesses_left > 0:
guess = int(raw_input("Your guess: "))
if guess == random_number:
print 'You win!'
break
guesses_left -= 1
else:
print 'You lose.'


#3

Congratulations, nice code, I don't see any answer or explanation though :frowning:


#4

I need you to format your code properly, otherwise I cannot see your exact mistakes.
My best guess is that you fail to understand the philosophy of the while loop.

You don't need an if statement to exit the while loop if guesses are equal to 0. This will happen because that's how the while loop works. It is executed while the statement following it is True. When it's False, it "brakes". Now, guesses_left, will inevitably end up equal to 0, since you are also taking 1 out of guesses_left each time the loop executes.

So, get rid of the if guesses_left == 0.

Instead, add an else statement that executes when while doesnt like so:

else:
    print "You lose"

Another error you made is subtracting 1 from guesses_left right before you check if the answer given by the user is correct. I'll explain where it should go later on...

And, why would you set the guesses_left to 0 afterwards? Just brake the loop, when you brake a loop, the else statement after it does not execute, so you'll be fine.

Also, HUUUGE logical error. What happens if the user is wrong? You should add an else statement, under the while, under the if(but not nested under the if) where you will type guesses_left -= 1

Then, and only then, will the program subtract 1 from the guesses_left

How the whole code should look:

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
    guess = int(raw_input("Enter guess: "))
    if guess == random_number:
        print "You win!"
        break
    else:
        guesses_left -= 1
else:
    print "You lose"

IMPORTANT: Your code looks real bad, almost like you jumped from the first chapter to this one, it has too many logic and syntax errors, while the whole lesson takes you by the hand and shows you everything. Consider revising.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.