简体   繁体   中英

Python function

I have this function:

def check_if_year(years):
    if years.isnumeric():
        year = int(years)

How would I recall year in that function to use it outside of the function and into another function? Thanks in advance.

You should recall that function using return

def check_if_year(years):
    if years.isnumeric():
        year = int(years)
        return year

This returns/recalls year

def check_if_year(years):
    if years.isnumeric():
        year = int(years)
        return year

You should return from the function:

def check_if_year(years):
    if years.isnumeric():
        return int(years)

You can then assign year as:

year = check_if_year(somestring)

outside that function.

You can return the value of year as input to another funcion.

def check_if_year(years):
    if years.isnumeric():
        year = int(years)
        return year # function returns year 

y = check_if_year(years) # Call the check_if_year function and store the result in y

another_function(y) # Pass the return value year to another function 

I would propose that EAFP is more Pythonic than the LBYL approach you have:

def check_if_year(years):
    try:
        return int(years)
    except ValueError as e:
        print e
        # do something with the fact you have a bad date...

Interact this way:

>>> check_if_year('1999')
1999
>>> check_if_year('abc')
invalid literal for int() with base 10: 'abc'

Then if you wanted to 'put inside another function' you could do something like this:

def leap_year(st):
    def check_if_year(year):
        try:
            return int(year)
        except ValueError as e:
            raise

    n=check_if_year(st)
    if n % 400 == 0:
        return True
    if n % 100 == 0:
        return False
    if n % 4 == 0:
        return True
    # else    
    return False        

print leap_year('1900')        # False
print leap_year('2000')        # True
print leap_year('next year')   # exception  
def remember_year( year ): # Return a function that 'remembers' the value of year
    return lambda x: x + year

plus10 = remember_year( 10 )
print plus10( 5 )
>> 15

Your function is actually mostly useless - what are you going to do if year is not numeric anyway ?

The simplest solution is to just try to build an int from whatever year is and handle the exception (how you want to handle it depends on the context) :

try:
    year = int(year)
except ValueError as e:
    handle_the_problem_one_way_or_another(year, e)
else:
    call_some_other_func(year)

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