Reputation: 31
I've been trying to understand this for a while now and I don't get why the true while loop doesn't exit when the check()
function returns False
value and asks input(i.e "enter input")
again and again but it exits when else statement of func()
function returns False
value. No matter what,as far as I know, the while loop should stop or exit when the value returned is false, but that isn't the case here. I don't intend to modify the code but would just like to understand the concept behind this. please help me. Thanks! in advance.
def check(num):
if(num%2==0):
return True
else:
return False
def func():
temp=[str(i) for i in range(1,51)]
while True:
c=input("enter input: ")
if c in temp:
c=int(c)
if check(c):
print(c)
break
else:
print("input invalid, enter only digits from 1 to 50")
return False
Upvotes: 0
Views: 271
Reputation: 43
It would most likely be due to the fact that the while true loop being used in the func() function is local to that function and so when you try to use the other function check() to actually change the value, it cannot do so. It would only be able to return false or true for a while loop that is included in the same function.
Upvotes: 1
Reputation: 43
You could try doing this:
loop = True
def check(num):
global loop
if(num%2==0):
loop = False
else:
loop = False
def func():
global loop
temp=[str(i) for i in range(1,51)]
while loop:
c=input("enter input: ")
if c in temp:
c=int(c)
if check(c):
print(c)
loop = False
else:
print("input invalid, enter only digits from 1 to 50")
loop = False
Upvotes: 0
Reputation: 190
The blank return that you have doesn't actually do anything.
You will have to break
from the loop.
It works in the second case as you actually return a value like False
Upvotes: 0
Reputation: 301
To exit a loop (for or while) outside a function or exit within the funtion but only exiting the loop you should use break
instead of return
.
Upvotes: 0