Nov-03-2017, 03:28 AM
You write a function when you have to repeat a block of code more than once.
The functions are objects too like everything in Python and they can be passed as a parameter to another function. Or you could do something like this.
number = int(input("> ")) if number % 2 == 0: print("even") else: print('odd') if number % 2 == 0: print(number * 2) else: print(number ** 2)You can write a function to check if the number is even:
def is_even(num): # here you define a function if num % 2 == 0: return True else: return False number = int(input("> ")) if is_even(number): # here you call the function and it returns True or False print('even') else: print('odd')Or:
even = is_even(number) if even: print('even') else: print('odd')As you can see in the definition, the function can take a parameter ( 'num' ) which you can use inside the function. Also. the function returns True or False. It actually can take and return any Python object. If you don't specify the return object it returns None.
The functions are objects too like everything in Python and they can be passed as a parameter to another function. Or you could do something like this.
def say_hello(text): print('Hello', text) def bye_bye(text): print("Bye bye,", text) say = print # the print() Python built-in function functions = {'world': say_hello, 'happiness': bye_bye} # here the values are function objects word = input("A word please: ") word = word.lower() if word in functions: functions[word](word) # here functions[word] holds an function and we call it adding () with a parameter - 'word' else: say('Unknown word!')Both 'print' and 'say' are just pointers to a function and you call them adding () at the end of the name just like 'function[word]' is a pointer ( its value ) to a function.