Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding Functions
#4
You write a function when you have to repeat a block of code more than once. 
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
Understanding Functions - by Dez - Nov-03-2017, 12:26 AM
RE: Understanding Functions - by Larz60+ - Nov-03-2017, 12:43 AM
RE: Understanding Functions - by metulburr - Nov-03-2017, 12:48 AM
RE: Understanding Functions - by wavic - Nov-03-2017, 03:28 AM
RE: Understanding Functions - by Dez - Nov-04-2017, 12:33 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Improving my understanding of functions and methods menator01 2 2,238 Apr-24-2020, 06:26 AM
Last Post: menator01
  Need help understanding a couple of functions (encrypt,decrypt, int_to_bytes) xoani 0 2,046 Jun-09-2019, 03:25 PM
Last Post: xoani
  i have problems understanding 2 functions,look for help. Tony 2 2,697 Dec-05-2018, 12:35 PM
Last Post: Tony
  Help in understanding scope of dictionaries and lists passed to recursive functions barles 2 3,296 Aug-11-2018, 06:45 PM
Last Post: barles

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020