Reputation: 23
I'm trying to get the user guess the number the computer is producing randomly. When passing the return function nothing shows up.
user = 0
result = ""
import random
print ("Welcome to Guess My Number Game")
def main():
#user input
computer = random.randint(1,100)
print(computer)
user=int(input("Guess the number:"))
return (result)
def results(result):
computer = random.randint(1,100)
diff = 0
diff = user - computer
if diff < -10:
result = ("Too Low")
elif diff > 10:
result = ("Too High")
elif diff < 0:
result = ("Getting warmer, but still low")
elif diff > 0:
result = ("Getting warmer, but still high")
else:
guesses = str(guesses)
result = ('Good job, you guessed correctly in,',guesses,'guesses!')
Upvotes: 0
Views: 63
Reputation: 52203
There are couple of problems in your indentation however, if I can understand the logic correctly, you can do something similar to the below in order to keep user asking for a guess till getting a match;
import random
def results(val):
guesses = 0
while True:
user = int(input("Guess the number: "))
guesses = guesses + 1
diff = user - computer
if diff < -10:
print("Too Low")
elif diff > 10:
print("Too High")
elif diff < 0:
print("Getting warmer, but still low")
elif diff > 0:
print("Getting warmer, but still high")
else:
print('Good job, you guessed correctly in {} guesses!'.format(guesses))
break
return guesses
def main():
computer = random.randint(1, 100)
number_of_guesses = results(computer)
>>> results()
Guess the number: 2
Too Low
Guess the number: 10
Too Low
Guess the number: 50
Too High
Guess the number: 40
Too High
Guess the number: 30
Getting warmer, but still high
Guess the number: 25
Getting warmer, but still low
Guess the number: 26
Getting warmer, but still low
Guess the number: 28
Getting warmer, but still low
Guess the number: 29
Good job, you guessed correctly in 9 guesses!
9
Upvotes: 1
Reputation: 808
I'm going to assume that you are trying to print the result variable from the results method
If my above statement is correct you have a misunderstanding about what return
does. return
is usually placed in a function to that will return some value. So you should make your code into this.
computer = random.randint(1,100)
print(computer) #if you print this guessing the number will be very easy
user=int(input("Guess the number:"))
print(results(computer, user))
def results(computer, user):
results = ""
# computer = random.randint(1,100) #you wont need this either
diff = 0
diff = user - computer
if diff < -10:
result = ("Too Low")
elif diff > 10:
result = ("Too High")
elif diff < 0:
result = ("Getting warmer, but still low")
elif diff > 0:
result = ("Getting warmer, but still high")
else:
guesses = str(guesses)
result = ('Good job, you guessed correctly in,',guesses,'guesses!')
return result
Upvotes: 0