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.
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
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
Related
The code allows me more than six times for input and also it did not print the else statement. My code is:
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ('AHOY! I am the Dread Prites Roberts , and i have a secret!')
print ('It is a number from 1 to 99. I\'ll give you 6 tries ')
while guess != secret and tries < 6:
guess = int(input('What is your guess? '))
if guess < secret:
print ('Too Low, you scurvy dog!')
elif guess > secret:
print ('Too high, boy')
tries = tries + 1
elif guess == secret:
print ('Avast! you got it ! Found my seceret , you did!')
else:
print ('No more guess! Better Luck next time')
print ('The secret number was',secret)
I tried the code in Python 3.4. It prints the result more than six times. While guess is not equal to secret and tries... after 6 tries it will print 'No more guess better luck next time' but is executing again and again
your have an indentation problem (i guess happened by pasting) but your main problem is, that you are only incrementing tries when the guess was too high. Also you should move the last if else out of the while block, since the while condition is already taking care of vars.
Your implementation should look like this:
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ('AHOY! I am the Dread Prites Roberts , and i have a secret!')
print ('It is a number from 1 to 99. I\'ll give you 6 tries ')
while guess != secret and tries < 6:
guess = int(input('What is your guess? '))
tries = tries + 1
if guess < secret:
print ('Too Low, you scurvy dog!')
elif guess > secret:
print ('Too high, boy')
if guess == secret:
print ('Avast! you got it ! Found my seceret , you did!')
else:
print ('No more guess! Better Luck next time')
print ('The secret number was',secret)
#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("You will choose a random number between 1-100")
print ("and the computer must guess what it is.")
print ()
number = int(input("Please choose a number between 1-100: "))
guesses = 0
guess = 0
while guess != number:
guess = ("My guess is: ",random.randint(1,100))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you") print ("guesses,"guesses!")
Basically you choose a number and the computer has to keep guessing until it gets it right but I can't seem to get it to work.
You should learn basic debugging skills. The simplest way to debug this program would be to add print() statements to see what values are in your variables.
Your basic problem is that you set guess to a tuple with two values: the string "My guess is: " and a random number from 1 to 100. You probably intended to set guess to just the number.
You probably want something like this:
guess = random.randint(1,100)
print("My guess is: {}".format(guess))
This will get you one step closer. Then you will need to figure out how to change the program so that it narrows down the guess range. If you have trouble with that, maybe you should find someone to tutor you a bit.
I am a brand new programmer, and I have been trying to learn Python (2.7). I found a few exercise online to attempt, and one involves the creation of a simple guessing game.
Try as i might, I cannot figure out what is wrong with my code. The while loop within it executes correctly if the number is guessed correctly the first time. Also, if a lower number is guessed on first try, the correct code block executes - but then all subsequent "guesses" yield the code block for the "higher" number, regardless of the inputs. I have printed out the variables throughout the code to try and see what is going on - but it has not helped. Any insight would be greatly appreciated. Thanks! Here is my code:
from random import randint
answer = randint(1, 100)
print answer
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print "Top of Loop"
print guess
print answer
i = i + 1
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
else:
print "else statement"
print "Congratulations! You got it in %r guesses." % i
print "Time to play a guessing game!"
print "Enter a number between 1 and 100:"
guess = raw_input()
guess = int(guess)
logic(guess, answer, i)
I'm sure it is something obvious, and I apoloogize in advance if I am just being stupid.
You've noticed that raw_input() returns a string (as I have noticed at the bottom of your code). But you forgot to change the input to an integer inside the while loop.
Because it is a string, it will always be greater than a number ("hi" > n), thus that is why "Too high. Try again:" is always being called.
So, just change guess = raw_input() to guess = int(raw_input())
Try this:
guess = int(raw_input())
As raw_input.__doc__ describes, the return type is a string (and you want an int). This means you're comparing an int against a string, which results in the seemingly wrong result you're obtaining. See this answer for more info.
Ok, I found your problem. The problem is in this Code:
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
In the code above you are getting your input as string, but you try to compare it with integer. All you need to do is to convert the input to integer, like this:
guess = raw_input()
guess = int(guess)
This should solve your problem :)
I updated the program. You came out of the while loop because after you get guesss as input inside elif group, you forget to convert that to int, so it throwed back error. Now, corrected but you can also optimise it.
import sys
from random import randint
answer = randint(1, 100)
'''randint(1, 100)'''
print (answer)
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print ("Top of Loop")
print (guess)
print (answer)
i = i + 1
if guess < answer:
print ("Too low. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
elif guess > answer:
print ("Too high. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
else:
print ("else statement")
print ("Congratulations! You got it in %r guesses." % i)
print ("Time to play a guessing game!")
print ("Enter a number between 1 and 100:")
guess = input()
guess = int(guess)
logic(guess, answer, i)
I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"
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 is 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, landrubber!")
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)
I keep getting this error: if guess < secret:
TypeError: unorderable types: str() < int()
guess = input ("What's yer guess? ")
Calling input gives you back a string, not an int. When you then compare guess using <, you need an int in order to compare a numerical value. Try doing something along the lines of:
try:
guess = int(input("What's yer guess? "))
except ValueError:
# Handle bad input
Because Python is strongly typed, you can't compare string and an int. What you get back from input() is a str not an int. So, you need to convert the str to an int before comparison is possible.
guess = int(input("What's yer guess"))
You should also handle the possible exception thrown when the input is not convertable to an int. So, the code becomes:
try:
guess = int(input("What's yer guess"))
except ValueError:
print ('Arrrrr... I said a number ye lily-livered dog')
In addition, input() is unsafe, at least in Python 2.x. This is because input() accepts any valid Python statement. You should use raw_input() instead if you're using Python 2.x. If you're using Python 3, just disregard this bit.
try:
guess = int(raw_input("What's yer guess"))
except ValueError:
print 'Arrrrr... I said a number ye lily-livered dog'
You spelled "landlubber" wrong.
A landrubber is a person who caresses the ground.
A landlubber is a person who doesn't know their way around a ship.
And you need to parse your input to an int before you can compare it to an int.