When I try to compare two integers I am getting an int error. Saying that it can't compare an int and a string but I am casting the input(string) to an int. Can someone explain why this happened?
I tried to int cast userInput = int(input(PROMPT) then I returned userInput. Then I try to compare my computerChoice to userInput and am getting an error.
def userInput():
userInput = int(input(PROMPT))
return userInput
Here is entire code: Python3 btw:
PROMPT = "Please enter an integer: "
WELCOME = "THE GUESSING GAME"
#get input
def userInput():
userInput = int(input(PROMPT))
return userInput
#get computer guess
def computerGuess():
import random
computerGuess = (int)(random.random()*6)
return computerGuess
def game(userInput, computerInput):
while userInput != computerInput:
print("Try again")
userInput()
if userInput == computerInput:
print("You win!!")
def main():
#get user Input in main
theInput = userInput()
#computer input
computer = computerGuess()
#launch game
game(theInput, computer)
main()
CodePudding user response:
The name you choose for the argument representing the user's input (userInput
) in your game
function is the same name as the function to capture user's input. So, in the scope of the game
function, userInput
is integer, but the you try to use it as a function (and int
type is not callable).
Moreover, the return value of the userInput()
function is not used to update the value of the variable userInput
, so if the first value provided by the user is different from computerInput
, the loop will continue forever.
If you change the name of the argument in the game
function and update the value provided by the user, the program works as expected:
def game(user_input, computer_input):
while user_input != computer_input:
print("Try again")
user_input = userInput()
if user_input == computer_input:
print("You win!!")
Otherwise, you can change a little bit your code, removing the user input from the arguments of the game function:
def game(computer_input):
while userInput() != computer_input:
print("Try again")
print("You win!!")
Obviously, you must remove also theInput = userInput()
from the main
function. Actually, you can get rid of your main function, using directly the game
function instead:
game(computerGuess())
However, also the choice of the names of the variables in the userInput
and computerGuess
functions is not wise: you should avoid naming variables inside a function with the same name of the function because it is confusing and makes your code more prone to errors.
Another suggestion: you can easily improve your program by limiting the range of the values: for instance, generate a random integer between 1 and 10 and ask the user to guess it. You can modify the computerGuess
using random.randint
instead of random.random
and adding a check that does not allow to the user to input values outside the range [1; 10].