Reputation:
and I apologies for the simple nature of my question.
Im working my way through "Hello World", Computer programming for Kids and Beginners - By Warren and Carter Sande.
The first chapters second example is this numeric example, of a pirate number quiz. Programming language is Python.
Its supposed to allow 6 guesses, unless the correct number is guessed first. I guess for you people the code would be self explanatory.
import random
secret = random.randint(1,99)
guess = 0
tries = 0
print "AHOY! I'm the dread Pirate Roberts, and I have a secret!"
print "It's a number from 1 to 99. I'll give you 6 tries."
while guess != secret and tries < 6:
guess = input("What's yer guess? ")
if guess < secret:
print "Too low, ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries +1
if guess == secret:
print "Avast! Ye got it! Found my secret, ye did!"
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret
But when I run it, it tells me what the answer is after each guess, which its not supposed to. Its supposed to wait until the end.
I just cant figure out what I have done wrong. I have checked each line, or at least, I think I have.
If someone could point out where I have gone wrong, that would be great.
Upvotes: 2
Views: 947
Reputation: 304175
A nicer way to write this might be. Then you don't have to set guess
to 0
outside the loop
for tries in range(1, 6):
guess = input("What's yer guess? ")
if guess < secret:
print "Too low, ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
else:
print "Avast! Ye got it! Found my secret, ye did!"
break
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret
Upvotes: 0
Reputation: 361615
Proper indentation is key. Make sure you indent the stuff inside the loop, and leave the stuff after the loop un-indented.
while guess != secret and tries < 6:
guess = input("What's yer guess? ")
if guess < secret:
print "Too low, ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries + 1
if guess == secret:
print "Avast! Ye got it! Found my secret, ye did!"
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret
Upvotes: 3