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
Asked
Active
Viewed 17 times
-1
-
1You shouldn't post code as pictures. – M4C4R Apr 21 '22 at 18:22
-
Don't post code or error messages in images or links to external sites. All code should be provided as text in a code block. – Ted Klein Bergman Apr 21 '22 at 18:23
1 Answers
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