Oct-24-2021, 09:42 PM
Here is an example of using a function
The code doesn't need to be changed much to turn it into a function
It can also be written as the more compact
def a_function(function_input): local_variable = "Local Variable" return f"{function_input} + {local_variable}" returned_from_function = a_function("Function Input") print(returned_from_function)
Output:Function Input + Local Variable
The code doesn't need to be changed much to turn it into a function
numbers = [1, 5, 3, 2] print(numbers) def get_odd_numbers(numbers): odd_numbers = [] for number in numbers: if number % 2: odd_numbers.append(number) return odd_numbers odd_numbers = get_odd_numbers(numbers) print(odd_numbers) print(sum(odd_numbers))
Output:[1, 5, 3, 2]
[1, 5, 3]
9
It can also be written as the more compact
def get_odd_numbers(numbers): return [number for number in numbers if number % 2]