0

i want to end the while True loop if num4 == number but break stops the loop from repeating and not making the if statement a part of the while True loop makes the code inaccessible. the code is below:

number = 50
count = 0
num4 = int(input("Enter a number: "))
while True:
    if num4 > number:
        print("Too high")
        num4 = int(input("Try again: "))

    elif num4 < number:
        print("Too low")
        num4 = int(input("Try again: "))

    elif num4 == number:
        print("Well done, you took", count, "attempts")
Dom
  • 1
  • 1
  • Just add a `break` to that statement – anarchy Oct 12 '22 at 16:49
  • You say "i want to end the while True loop". OK, fine. Use `break`. Then you say "but break stops the loop from repeating". Yes, it does. That's what you asked for. Now you complain that the loop ends? Could you please clarify this? – Matthias Oct 12 '22 at 17:21

1 Answers1

0

Add break statement to break out of a while or for loop. Also looks like you need to increment count variable inside the loop whenever user enters a new number.

while True:
    count += 1
    if ...
        ...
    elif num4 == number:
        print("Well done, you took", count, "attempts")
        break  # <======
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75