Python Programming
Functions and Modules
What are Functions?
- Functions are reusable blocks of code that perform specific tasks. Instead of writing the same code repeatedly, write it once in a function!
- Think of functions as mini-programs within your program.
Creating Functions
- “`python
- def greet(name):
- print(f'Hello, {name}!')
- greet('Ahmed') # Prints: Hello, Ahmed!
- greet('Sara') # Prints: Hello, Sara!
- “`
- With Return Value:
- “`python
- def add_numbers(a, b):
- return a + b
- result = add_numbers(10, 20)
- print(result) # Prints: 30
- “`
Function Parameters
- Required Parameters:
- `def calculate_tax(amount):`
- Optional Parameters (with default values):
- “`python
- def greet(name, greeting='Hello'):
- print(f'{greeting}, {name}!')
- greet('Ali') # Uses default: Hello, Ali!
- greet('Sara', 'Hi') # Uses custom: Hi, Sara!
- “`
Using Built-in Modules
- Python comes with many pre-built modules (libraries) you can use:
- Math Module:
- “`python
- import math
- print(math.sqrt(16)) # Square root: 4.0
- print(math.pi) # 3.14159…
- “`
- Random Module:
- “`python
- import random
- print(random.randint(1, 100)) # Random number between 1-100
- “`
- Datetime Module:
- “`python
- import datetime
- print(datetime.datetime.now()) # Current date and time
- “`
Real Example: Temperature Converter
- “`python
- def celsius_to_fahrenheit(celsius):
- return (celsius * 9/5) + 32
- def fahrenheit_to_celsius(fahrenheit):
- return (fahrenheit – 32) * 5/9
- temp_c = 25
- temp_f = celsius_to_fahrenheit(temp_c)
- print(f'{temp_c}°C = {temp_f}°F')
- “`