8/19 - "Your own while/else"


#1

According to the program, I solved this exercise, but the perfectionist in me doesn’t accept that.
When I guess correctly, it still tells me I’ve guessed incorrectly.
Instructions:
image

My code (including a print statement so I know what the correct answer is):

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
print random_number
guesses_left = 3
while guesses_left > 0:
  guess = raw_input("Pick a number: ")
  if guess == random_number:
    print "You win!"
    break
  guesses_left -= 1
else:
  print "You lose."

The console:
image

And after I changed it to let me have ten guesses:
image

I think this game is rigged.


#2

i ran your code here:

https://repl.it/@stetim94/RedOverdueAndalusianhorse

doesn’t appear to be rigged at all


#3

When I ran my code at your link, it did the same thing. The correct answer was 2 but it still told me “You lose.” despite 2 being one of my answers:
image

I mean it’s not that important, I just feel a little dissatisfied not knowing what I did wrong.


#4

it is important, and i missed it :wink:

what data type does raw_input store the result entered by user? Is this the same data type as random_number?


#5

Ohhhhh! Thank you! The information before the instructions even reminded me specifically to use int() but I forgot! Thank you.

image


#6

there is a good reason to use int(). If you want a challenge, see if you can figure out a way to handle invalid user input (for example if the user enters hello) or that the user guess is within range (0 till 10)


#7

That sounds stimulating, but I’m not sure it’s something I can accomplish.
I mean, raw_input() always produces strings, so on the condition guess = raw_input("Pick a number: ") I can’t just say if type(guess) != int because it’ll never be int; but if I use if type(int(guess)) != int then I’ll still get an error if guess is anything but a whole number.
I tried Googling how to do this, but the solution apparently involves some kind of code that’s pretty foreign to me, involving tags like in HTML: <var>.
This one might be a little over my head for the time being.


#8

If someone writes something on a piece of paper, how do you determine whether it’s a number? It consists of characters 0…9
…Do the same thing in your program.

Testing the type would only be useful if you did something where the value was either turned into a string or a number.
Such an action would still have to determine whether it’s a number or not, so assuming it’s already in the code doesn’t solve the problem.

As for debugging, add some print statements to write out what was being done and find out where it goes wrong. You’re not supposed to get these things right all the time, you’re supposed to be able to track it down and fix it.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.