Function Basics

Simple Function

  1. # define and call function
  2. def greet():
  3. print("Hello!")
  4. greet()
  5. #ans: Hello!

Function with Parameter

  1. # function with one parameter
  2. def greet_person(name):
  3. print(f"Hello, {name}!")
  4. greet_person("Alice")
  5. #ans: Hello, Alice!

Function with Multiple Parameters

  1. # multiple parameters
  2. def add(a, b):
  3. return a + b
  4. result = add(5, 3)
  5. #ans: result is 8

Function with Return

  1. # return value
  2. def square(x):
  3. return x ** 2
  4. result = square(5)
  5. #ans: result is 25

Function Without Return

  1. # no return (returns None)
  2. def print_message(msg):
  3. print(msg)
  4. result = print_message("Hi")
  5. #ans: Hi (printed)
  6. #ans: result is None

Exercises - Part 1

  1. # what is returned?
  2. def func():
  3. x = 5
  4. func()
  5. #ans: None (no return statement)

Exercises - Part 2

  1. # what is result?
  2. def add(a, b):
  3. return a + b
  4. result = add(10, 20)
  5. #ans: 30

Exercises - Part 3

  1. # function call without ()?
  2. def greet():
  3. return "Hello"
  4. x = greet
  5. #ans: x is the function object, not "Hello"

Exercises - Part 4

  1. # what happens?
  2. def multiply(x, y):
  3. return x * y
  4. multiply(5, 3)
  5. #ans: 15 (but not stored)

Exercises - Part 5

  1. # can you call before defining?
  2. result = add(1, 2)
  3. def add(a, b):
  4. return a + b
  5. #ans: NameError (function not defined yet)

Exercises - Part 6

  1. # function with print vs return?
  2. def func1():
  3. print(5)
  4. def func2():
  5. return 5
  6. x = func1()
  7. y = func2()
  8. #ans: 5 (printed)
  9. #ans: x is None, y is 5

Exercises - Part 7

  1. # nested function call?
  2. def double(x):
  3. return x * 2
  4. result = double(double(5))
  5. #ans: 20

Exercises - Part 8

  1. # what is printed?
  2. def test():
  3. return 5
  4. print("After return")
  5. test()
  6. #ans: 5 (return exits function, print never runs)

Exercises - Part 9

  1. # function name case?
  2. def MyFunction():
  3. return 1
  4. myfunction()
  5. #ans: NameError (names are case-sensitive)

Exercises - Part 10

  1. # redefining function?
  2. def func():
  3. return 1
  4. def func():
  5. return 2
  6. func()
  7. #ans: 2 (second definition overwrites first)

Google tag (gtag.js)