简体   繁体   中英

Python Control Flow

For the following code:

def isString(x):
  if type(x)==str:
    return True
  return False

When I input a string into the parameter, after returning True, why wouldn't it also then return False? I'm new to Python and I'm confused because I assumed it would then return False because it is out of the for loop, however it doesn't.

The answer is the same for any language. The return statement means return from the function, giving an optional value back. It can only return once. In this case it returns out of the conditional statement.

BTW, for type checking like that use the is operator.

if type(x) is str:
    return True

But, in fact, the real recommended way to do string type checking is:

if isinstance(x, str):
    return True

However, since it's so short you don't really need t write your function for this at all (except for learning purposes). Just use isinstance(x, str) where you would have otherwise wrote isString(x) .

By the way, there is no for-loop in your code

When a function returns something - anything - it's done. The return statement means that the function exits; no more processing whatsoever.

If the type of x is str , then the function returns True . However, if the type of x is not str , then the if-statement is never entered, and True is not returned. Instead, the function continues to the next line after the if-statement, namely return False -- and the function returns False

The return statement terminates the function. Once you return, the function stops.

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