Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Hi, can anyone tell me where have I gone wrong in this number game task? Thanks!

import random
secret_num = random.randint(1,10)
i = 0
num = 0

def get_guess():
    num = int(input("Hey enter a number between 1 and 10 "))

while True:
    i = i + 1
    get_guess()
    if num == secret_num:
        print ("Spot on! You got that after {} goes!".format(i))
        break
    elif num > secret_num:
        print ("Too big! Try again!")
        continue
    elif num < secret_num:
        print ("Too small! Try again!")
        continue

2 Answers

Hi Nick

I have amended your code a bit and it works now. Get the your function get_guess to return the user input. Then call the function inside the while loop rather than setting num = 0. See below

import random
secret_num = random.randint(1,10)
i = 0

def get_guess():
    num = int(input("Hey enter a number between 1 and 10 "))
    return num


while True:
  num = get_guess()
  i = i + 1
  if num == secret_num:
    print ("Spot on! You got that after {} goes!".format(i))
    break
  elif num > secret_num:
    print ("Too big! Try again!")
    continue
  elif num < secret_num:
    print ("Too small! Try again!")
    continue 

Aha! I see! Thanks very much for you help Andreas!

Hi Nick

Indent the while loop so its part of the function get_guess. This enables you to run the entire app by calling the get_guess function.

Hi Andreas, thanks for your reply. The thing is get_guess is called in my loop. What happens is that num is always set to zero even after get guess is called, so that it always says "too small". Doesn't calling get_guess mean that num would be updated?