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

Using import random?

Hi guys!

So I am trying to start working on the number guessing game. My code works great if I guess the number correcting right away and if I guess wrong it prints what I want, but it doesn't ever tell me I guess correctly even if I try all possible solutions. Does it choose a new random number every time I guess again and if so how do I stop that? I tried to google and read other posts, but haven't been able to figure it out. Any help would be great! Thank you!

""" import random

import sys

num = random.randint(1, 10)

welcome = input("Welcome! Wanna play a game? (yes/no) ")

if welcome.lower() == 'yes': print("Good choice! This game is called -Guess That Number!-") print("To play enter a number between 1-10 and try to guess what the computer choose!") else: sys.exit("Too bad..it would have been a fun game! Maybe next time!")

guess = input("What is your guess? ".format(num)) guess = int(guess)

while guess != num: print("oh so close!") guess = input("Guess again! ".format(num))

if guess == num:
print("Good guessing! Thanks for playing!") """

sorry about the format, I'm not sure yet how to copy my code!

2 Answers

Brandon White
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brandon White
Full Stack JavaScript Techdegree Graduate 35,771 Points

Hi Danielle,

The reason why the game doesn’t work as expected if you don’t guess the number correctly right away is because in the while loop you never convert the user's response (which is stored in the guess variable) from a string to an int.

You do that in the beginning with guess = int(guess), but later on you leave it as a string. And a string will never equal a number. For that reason, the game never ends.

Ah! Thank you! I totally didn't realize you had to convert it twice! Thank you!