Python Functions - Beginner Guide
What is a Function in Python?
A function is a reusable block of code that performs a specific task.
It helps reduce repetition, makes your code cleaner and more readable.
Syntax:
def function_name():
# code block
Example:
def say_hello():
print("Hello, L Lawliet!")
say_hello()
Why Use Functions?
- Avoid repeating code (DRY principle)
- Make code easier to manage and understand
- Divide complex problems into simpler parts
- Make your code reusable
Parts of a Function
1. def - defines the function
2. function_name - the name of the function
3. () - parentheses, where you can pass inputs
4. : - starts the function block
5. Indentation - the block of code inside
Function with Parameters and Return
You can pass inputs (called parameters) and return outputs.
Python Functions - Beginner Guide
Example:
def greet(name):
print("Hello, " + name + "!")
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
Beginner Function Examples
1. Say Hello
def say_hello():
print("Hello, friend!")
2. Add Numbers
def add_numbers(x, y):
return x + y
3. Square a Number
def square(n):
return n * n
4. Even or Odd
def even_or_odd(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
Python Functions - Beginner Guide
5. Multiply a List
def multiply_list(numbers):
result = 1
for num in numbers:
result *= num
return result
What are Built-in Functions?
Built-in functions are already provided by Python. You can use them directly without defining them.
Examples:
- print(), input(), len(), type()
- int(), float(), str(), bool()
- sum(), max(), min(), range()
- abs(), round(), sorted(), list(), set(), dict()
Useful Built-in Functions with Examples
1. print()
print("Hello")
2. input()
name = input("Your name: ")
print("Hi", name)
3. len()
print(len("Python")) # Output: 6
4. sum()
print(sum([1, 2, 3])) # Output: 6
Python Functions - Beginner Guide
5. type()
print(type(5)) # <class 'int'>
6. max(), min()
print(max([5, 10, 3])) # Output: 10
7. abs()
print(abs(-7)) # Output: 7
How to List All Built-in Functions?
Use this command:
print(dir(__builtins__))
Practice Ideas for You
- Take two numbers as input and print their sum
- Create a function to find area of rectangle
- Check if a number is positive or negative
- Make a list of 5 items and find its length using len()
- Use max(), min(), and sum() on a list of numbers