简体   繁体   中英

True while loop python

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(ie "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

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.

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM