-1

The condition is simple. If sum<=20 then print sum or else loop the starting from the input. However, this is looping even if the input is valid. How should I fix this? My code is in the picture

code in the picture

1 Answers1

0

You need to specify that you wish to update the global variable.

invalid_input = True

def start():
  x = int(input("number1: "))
  y = int(input("number2: "))
  z = int(input("number3: "))
  sum = x + y + z
  if (sum <= 20):
    global invalid_input
    invalid_input = False
    print(sum)
  else:
    print("return and give valid input")

while invalid_input:
  start()

Alternatively, you could return a boolean from the function.

def start():
  x = int(input("number1: "))
  y = int(input("number2: "))
  z = int(input("number3: "))
  sum = x + y + z
  if (sum <= 20):
    print(sum)
    return True
  else:
    print("return and give valid input")

while True:
  if start(): break

Related post: python-function-global-variables

M4C4R
  • 356
  • 4
  • 13