0

How can I use the variable 'guess' in my guessfunction() in the main function (for i in range (1,6)? I get the error that guess is not defined. Initially everything worked fine without the guessfunction, but I wanted to add the possiblity of wrong input from the user and that got me stuck. I saw on stackexchange that it is bad practice to use global inside a function, but even with global I don't know how to solve my issue. Is there also a way to change the int(guess) if it is possible to get the variable from the function? Thank you!

import random, sys

print("Hello. What is your name?")
name = str(input())
print("Well, " + name + ", I am thinking of a number between 1 and 20.")
number = random.randint(1, 20)

def guessfunction():
    print("Take a guess.")
    guess = input()
    for number_attempts in range(0,3):
        try:
            return guess
        except ValueError:
            print("Please enter a number in figures not as a word")
    print("You didn't enter a number in figures after 3 tries, program ended")
    sys.exit()
    
for i in range(1,6):
    guessfunction()
    if int(guess) != number:
        if int(guess) < number:
            print("Your guess is too low")
        else:
            print("Your guess is too high")
    elif int(guess) == number:
        print("Good job, " + name + "! You guessed my number in " + str(i) + " guesses")
        sys.exit()
print("Nope. The number I was thinking of was " +str(number))
1
  • 1
    save what you return into a variable. e.g. guess = guessfunction() Commented Aug 5, 2020 at 11:17

1 Answer 1

0

you need to initialise it in your for loop:

guess = guessfunction()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.