What is wrong with this Python game code? - python

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.

Related

How do you use an if statment to only except integers and give an invalid entry message?

I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True

This is the error I get after making the following code: TypeError: unorderable types: str() > method()

import random
SecretNumber=(random.randint)
Guess=input("Please enter your guess: ")
NumberofGuesses=1
while Guess != SecretNumber:
NumberofGuesses=NumberofGuesses+1
if Guess>SecretNumber:
print("Please insert a smaller number")
else:
print("Please insert a bigger number")
print("Number of Guesses: {0}".format(NumberofGuesses))
from random import *
secretnumber = randint(0,10)
numberofGuesses += 1
guess = int(input())
just a few things to clean up the code, and fix the str problem
also, put the guessing part in the while loop
You never convert the user's guess into an integer. That takes care of the str part. Use Guess = int(input("Please enter your guess: ")).
You never actually call the random.randint function, with random.randint(). That means SecretNumber is a function, not an integer, which takes care of the method part. Use SecretNumber = random.randint(1, 10) (for a random number between 1 and 10, inclusive).
You never have another prompt for input. Either add another Guess =... at the end of the loop, or move the one you already have to the beginning of the loop and use a while True: with a break on a matching number (in an else branch for the if structure you already have - the current else should be an elif; see below).
If the guess is too big, you state as much. However, you say the guess is too small in every other case, even though the guess might actually match. Replace that else with elif Guess < SecretNumber.

Python "guess the number" game always returns the same answer

I wrote this script but it always returns the same answer ("Your guess is too high"), no matter what the user inputs. Any insight would be helpful.
import random
number = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
if type(guess == int):
print(number) # this prints the randint to show the code isn't working
while(number != 0):
if(guess > number):
print("Your guess is too high!")
break
elif(guess < number):
print("That's too low.")
break
elif(guess == number):
print("Thats's right!")
break
else:
print("Please enter a number.")
Your while loop is useless, the problem of testing the input as an int is better handled with a try/except.
All together the correct answer is in Python3 :
import random
number = random.randint(1, 10)
found = False
while not found:
try:
guess = int(input("Guess a number between 1 and 10: "))
if guess > number:
print("Your guess is too high!")
elif guess < number:
print("That's too low.")
elif guess == number:
print("Thats's right!")
found = True
except ValueError:
print("Please enter a number.")
if type(guess == int):
This isn't doing what you expect. It always returns True because it's the equivalent to bool(type(False)). First make sure to convert your input to an int
guess = int(input("Guess a number between 1 and 10: "))
and then remove this if statement:
if type(guess == int):
Your problem is that this code:
if(guess > number)
is always comparing a string to an int, so once you correct that your code will be fixed.
I have just copied and pasted your code and it seems to function mostly correctly. There are some issues with it though. First, it appears that this is written for python 2 based on the way you are using the input function. However this is bad practice as the input() function in python 2 includes an implicit call to the eval() function which could allow for arbitrary code to be run.
In python 2 the better practice would be to use guess = int(raw_input("Guess a number between 1 and 10: ")).
In python 3, raw_input() has been removed and input() replaces it. So in python 3 you would use guess = int(input("Guess a number between 1 and 10: ")).
Your final else block is also indented where it should not be, although if you revise your code to make use of the advice given above, your if...else block is no longer necessary.
That's because input returns a string in Python 3. You need to call int() to make it an integer type:
guess = int(input("Guess a number between 1 and 10: "))
You're also using the type() function incorrectly. You probably want the function isinstance(): if isinstance(guess, int):
Also, in Python, we don't need parentheses like you've used. You can simply do if guess > number:

Python While Loop woes

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)

Python example repeating answer during quiz and not at end

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

Categories

Resources