-1

I want the inner while loop to be broken when the input data is 5, but if the input is other than 5, the loop will be executed again. In this code, the input value of each number I enter is printed as X = 1:

x = 1
while True:
    def state():
        x = input("Enter Your number:")

    while True:
        print(x)
        if x==5:
            print('x=5')
            break
        state() 

In this code, I tried to solve the problem but it didn't work too.

condition = True
x = 1
while True:
    def state():
        x = input("Enter Your number:")

    while condition:
        print(x)
        if x==5:
            print('x=5')
            condition = False
        state() 

Is there anyone to help me?

  • 4
    There are multiple problems here. 1) the scope of ``x`` in state() is limited to that function (better work with a return value or use the ``global`` keyword). 2) ``input`` returns a string and ``"5"`` is never equal to the number ``5``. – Mike Scotty Apr 06 '21 at 16:18

3 Answers3

0
  • you are defining your function in while loop.
  • also the scope of x in your function is local, return the value or use the input in while loop
  • and the expression x==5 will never be true

try this:

    while True:
       x = input("Enter Your number:")
       if x=="5":
          print('x=5')
          break
user_na
  • 2,154
  • 1
  • 16
  • 36
Mahsa
  • 41
  • 9
0

I am assuming that you want your program to ask the user continuously to enter the number and if he enters 5, the loop breaks.

The input function stores the entered value as a string so you have to use int() to convert it to int.

You can use a single while loop to achieve this. Try this:-

while True:
    x = int(input("Enter Your number:"))
    print(x)
    if x==5:
        print('x=5')
        break
Aaditya Joshi
  • 122
  • 10
0

If you want to make sure the input is a number you should try to cast it to an int:

while True:
    inpt = input("Enter Your number:")
    try:
        x = int(inpt)
    except:
        print('Not a number.')
    print(f'x = {x}')
    if x==5:
        break
         
user_na
  • 2,154
  • 1
  • 16
  • 36