4. Funzioni#

#> Define a function to tell if a number is positive or not
def is_positive(x):
    """ Function returning True if x>0, False if x<=0 """
    return x > 0

#> User input to test the function: tuple of numbers
n_tuple = [ -1, 2., .003, 1./3., -2.2, 0, -7.4 ]

#> Test function on all the elements in the user-defined tuple
for n in n_tuple:
    if ( is_positive(n) ): 
        string = ''
    else:
        string = 'not '
        
    print(f'{n} is '+string+'positive')
-1 is not positive
2.0 is positive
0.003 is positive
0.3333333333333333 is positive
-2.2 is not positive
0 is not positive
-7.4 is not positive

4.1. Default value of function arguments#

#> Define a user function to tell is the first argument is greater than the second.
# If no second argument is given, it's set = 0 (default value, defined in the function)
def is_greater_than(x, y=0):
    """  """
    return is_positive(x-y)

a, b = -2, -3
print(f"Is {a} greater than {b}? is_greater_than({a}, {b}):"+str(is_greater_than(a, b)))
print(f"Is {a} greater than  0 ? is_greater_than({a},    ):"+str(is_greater_than(a)))

    
Is -2 greater than -3? is_greater_than(-2, -3):True
Is -2 greater than  0 ? is_greater_than(-2,    ):False