I'm trying to get my number-guessing game to work and I got it but I just don't understand why it doesn't work, when I have my guess input as a function. Here is the original code where it doesn't work
import random
targetMin = int(input("Enter your range's minimum number: "))
targetMax = int(input("Enter your range's maximum number: "))
targetNum = int(random.randint(targetMin, targetMax))
def takeGuess():
guess = int(input("Enter your guess: "))
return guess
def startGame():
guess = 0
while guess != targetNum:
takeGuess()
if guess > targetNum:
print("You guessed too high, guess again!")
elif guess < targetNum:
print("You guessed too low, guess again!")
elif guess == targetNum:
print("You win the game!")
break
startGame()
The code works perfectly when I replace takeGuess
in startGame
function with the guess input code.
Here it's working, but I am confused why my first version doesn't work. I did some research and it's probably a return problem but I just couldn't figure out the syntax. Sorry.
import random
targetMin = int(input("Enter your range's minimum number: "))
targetMax = int(input("Enter your range's maximum number: "))
targetNum = int(random.randint(targetMin, targetMax))
def startGame():
guess = 0
while guess != targetNum:
guess = int(input("Enter your guess: "))
if guess > targetNum:
print("You guessed too high, guess again!")
elif guess < targetNum:
print("You guessed too low, guess again!")
elif guess == targetNum:
print("You win the game!")
break
startGame()
CodePudding user response:
You are calling takeGuess()
, and takeGuess()
is returning a value, but you aren't doing anything with the result. To make it work, you need to store the result of takeGuess()
in guess
. Like this:
import random
targetMin = int(input("Enter your range's minimum number: "))
targetMax = int(input("Enter your range's maximum number: "))
targetNum = int(random.randint(targetMin, targetMax))
def takeGuess():
guess = int(input("Enter your guess: "))
return guess
def startGame():
guess = 0
while guess != targetNum:
guess = takeGuess()
if guess > targetNum:
print("You guessed too high, guess again!")
elif guess < targetNum:
print("You guessed too low, guess again!")
elif guess == targetNum:
print("You win the game!")
break
startGame()
Just because you return a variable doesn't mean the caller will be able to access it. I think this is what is throwing you off. For simplicity, your takeGuess()
function can be rewritten as this:
def takeGuess():
return int(input("Enter your guess: "))