Reputation: 141
def guess(n):
import random
x = random.randint(1,1000000)
while n != x:
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
if n == x :
print("Congrats")
again = print(input(str("Play Again Y/N?: ")))
if again == Y:
n = print(input(str("Input Number 'n': ")))
print(guess(n))
elif again == N:
print("Goodbye")
How do i make the while loops stop looping if the condition is matched and move onto the next condition that i have stated. Thank you!
Upvotes: 0
Views: 106
Reputation: 1500
Use the break
statement (it terminates the nearest enclosing loop), e.g.
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
break
Upvotes: 1
Reputation: 43
As previously stated,your indentation is incorrect for the statement "while..." and also for the "if x==n" .Move it to two tabs to the right,as you want to run the loop till the player wants to play the game.In your given code, the loop is running where there is no increment in x .Now regarding the break condition you can try something like this.
else:
print("Goodbye")
break
Upvotes: 0
Reputation: 4177
I'd write something like this:
import random
def guess():
x = random.randint(1,1000000)
n = x + 1 # make sure we get into the loop
while n != x:
n = input(str("Input Number 'n': "))
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
print("Congrats")
break
if __name__ == '__main__':
while True:
guess()
again = input(str("Play Again Y/N?: ") == 'N'
if not again:
break
Upvotes: 0
Reputation: 1122
You need to call a new input to change n
. In your while
statement, n is never redefined.
Try:
def guess(n):
import random
x = random.randint(1,1000000)
while n != x:
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
n = print(input(str("Input Number 'n': ")))
and if you want to stop the loop... Use break
if my_condition:
break
will stop your loop. It also works with for loops.
But asking for a new value of n
will result, when x ==n
, to end your while
statement.
Upvotes: 0
Reputation: 5673
You can exit a loop early using break
. I am not sure what you mean by "the next condition", but after a normal "break" excution will just start immediately after the loop. Python also has a nice construct where you can put an "else" clause after the loop which run only if the Loop exits normally.
Upvotes: 0