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
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.
check_leap_year also assuming year will be a string? E.g. do you call isdigit() again?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
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)
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
except clause. (Or at least one that only prints the exception as an example.) Who says that an except needs to do anything? It is a simple example to show the OP an alternate way to code a simple function. What would YOU have the except do in this case? It is up to the OP what is to be done with a bad year string.try/except that the OP can choose to learn more about or not. Since what is to be done with a bad year string is not specified in the original, it makes no sense to specify it here. The second example I added (based on the OP's comments) does exactly what you say it should: die on a bad string.