While and for loop iterating twice without prompting for input


#1
from random import randint

random_guess = random.randint(1, 10)
guesses_left = 3

while guesses_left > 0:
     guess = int(raw_input("Enter your number: ")
     if guess == random_guess:
           print "You win"
     guesses_left -= 1
else:
     print "You lose"       

It prints Enter your number:and when you enter a number this happens:
Enter your number: Enter your number: You lose

I researched a bit, it seems that when I press enter a code enters /n, but I don’t know how to remove it.
It’s not that critical, but I would like to know how to solve this.


#2

What if you write,

    if guess == random_guess:
        print "You win"
        break
    else:
        guesses_left -= 1

#3

It makes the same result.
I tried this on 3 different ways.

And this code I wrote up there is not copied.
Break statement actually existed.
The code was fine. The point is the if you hit the correct number than the code worked either way.
But if you need to keep on inputting the numbers, the problem appears.
I checked on Stack Overflow, they say that the /n enters when you press enter, which why you need to use something like:

while ((stop = getchar()) == '\n'); // loops until it reads a non-newline
                                               // character
or 

scanf(" %c", &stop);

#4

Please remember to include a link to the exercise when asking a question in Q&A. Thanks.

How about,

    if guess == random_guess:
        print "You win"
        break
    guesses_left -= 1

You still need the while-else.


#5

Hi @yzanamy ,

Make sure that all your parentheses are closed. Check this line, for example …

guess = int(raw_input("Enter your number: ")

#6

It worked out.

Sometimes, it doesn’t seem logical to me the way computer works.

For instance, look at this and how is it possible.

def anti_vowel(text):
  text_list = list(text)
  for char in text_list:
    for vchar in "aeiouAEIOU":
      if char == vchar:
        text_list.remove(char)
  return "".join(text_list)

It returns this:

Your function fails on anti_vowel(“Hey look Words!”). It returns “Hy lk Words!” when it should return “Hy lk Wrds!”.

How is it possible that it didn’t iterate through the whole text, or removed the vchar in this case?
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/antivowel?action=lesson_resume&link_content_target=interstitial_lesson

It also seems that it works on PyCharm


#7