J.Doe
J.Doe

Reputation: 27

For loop ends before condition is reached

I am trying to make a number guessing game and the rules is that you get 10 guesses to find the randomly generated number. It will show if your guess is too high/low and if it is correct the program ends. But for some reason, the program ends even though I didn't guess correctly. If someone can troubleshoot my problem it will be appreciated.

import random  


rand = random.randint(1,100)  
guesses = 0  

for i in range(10):  
    guess = int(input("Guess the secret number"))  
    if guess > rand:  
        print("your guess is too high")  
        guesses += 1  
        print("number of guesses",guesses,"/10")  
    if guess < rand:  
        print("your guess is too low")  
        guesses +=1  
        print("number of guesses",guesses,"/10")  
    if guess == rand:  
        print("you won")  
    break

Upvotes: 1

Views: 398

Answers (2)

ngShravil.py
ngShravil.py

Reputation: 5058

break statements are used to terminate the current loop. So, when you use this it will end the current loop and the control will be passed to the statement which is after the loop.

In your case, since you have put break statement at the end of the for loop, so the loop gets terminated in the first iteration.

So, all you can do is put the break statement inside the last if condition, like below

import random  


rand = random.randint(1,100)  
guesses = 0  

for i in range(10):  
    guess = int(input("Guess the secret number"))  
    if guess > rand:  
        print("your guess is too high")  
        guesses += 1  
        print("number of guesses",guesses,"/10")  
    if guess < rand:  
        print("your guess is too low")  
        guesses +=1  
        print("number of guesses",guesses,"/10")  
    if guess == rand:  
        print("you won")  
        break

Upvotes: 0

Fabian
Fabian

Reputation: 1150

break will leave the loop directly

import random  


rand = random.randint(1,100)  
guesses = 0  

for i in range(10):  
    guess = int(input("Guess the secret number"))  
    if guess > rand:  
        print("your guess is too high")  
        guesses += 1  
        print("number of guesses",guesses,"/10")  
    if guess < rand:  
        print("your guess is too low")  
        guesses +=1  
        print("number of guesses",guesses,"/10")  
    if guess == rand:  
        print("you won")
        break # <- move break under the correct if statement

Upvotes: 2

Related Questions