Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Python Functions: Guide to def
and Function Calls
Functions are one of the most essential building blocks in Python programming. Whether you are writing a small script or building a large-scale application, functions help you organize, reuse, and simplify your code. In Python, defining functions is straightforward thanks to the def
keyword. This guide is designed to help beginners understand the concept, syntax, and use cases of Python functions, all in simple terms.
📌 Why Are Functions Important in Python?
Functions allow you to encapsulate code logic into a reusable unit. Instead of writing the same code again and again, you define it once in a function and call it whenever needed.
Benefits of Using Functions:
- ✅ Code Reusability: Write once, use many times.
- ✅ Better Readability: Organize complex tasks into manageable blocks.
- ✅ Debugging Ease: Isolate issues inside specific functions.
- ✅ Modularity: Split your application into independent chunks.
- ✅ Improved Collaboration: Makes code easier to maintain and share in teams.
🧠 Prerequisites
Before diving into defining and calling functions, you should be familiar with:
- Basic Python syntax
- Variables and data types
- Indentation in Python (functions use indentation to define their block)
- Using the terminal or a Python IDE like VS Code, PyCharm, or Jupyter
🔍 What Is a Function?
A function is a named block of code designed to do a specific job. In Python, functions are defined using the def
keyword, followed by the function name and parentheses.
Here’s a basic function structure:
def greet(): print("Hello, welcome to Python!")
To call this function, simply write:
greet()
Output:
Hello, welcome to Python!
✏️ Defining a Function with def
To define a function:
- Use the
def
keyword - Write the function name (following naming rules)
- Add parentheses
()
— include parameters if needed - End with a colon
:
- Indent the body of the function
Example:
def say_hello(): print("Hello there!")
To execute this function:
say_hello()
🔁 Parameters and Arguments
Functions can accept inputs, called parameters or arguments, which allow them to process different values dynamically.
Example:
def greet_user(name): print(f"Hello, {name}!")
Calling the function with an argument:
greet_user("Alice")greet_user("Bob")
Output:
Hello, Alice!Hello, Bob!
You can pass multiple parameters too:
def add(a, b): print("Sum:", a + b)
add(5, 10)
🎯 Returning Values
Sometimes, you need the function to give you a result. That’s where the return
statement comes in.
Example:
def square(x): return x * x
result = square(4)print("Result:", result)
Output:
Result: 16
The return
statement sends back the result to the caller. If you don’t use return
, the function will return None
.
🧭 Calling Functions
Once defined, a function can be called as many times as needed.
def welcome(): print("Welcome to npblue.com!")
welcome()welcome()
Output:
Welcome to npblue.com!Welcome to npblue.com!
🌐 Scope: Local and Global Variables
Variables declared inside a function are local—they only exist within that function.
def demo(): x = 10 # local variable print(x)
demo()# print(x) # This would raise an error
Global variables are declared outside all functions and can be accessed globally.
y = 5
def show(): print(y) # accessing global variable
show()
🎛️ Default Parameter Values
You can assign default values to parameters.
def greet(name="Guest"): print("Hello,", name)
greet("Mark")greet() # Uses default value
Output:
Hello, MarkHello, Guest
🔑 Keyword Arguments
You can pass arguments in the form of key=value
.
def profile(name, age): print(f"Name: {name}, Age: {age}")
profile(age=30, name="Sam")
Order doesn’t matter when using keyword arguments.
🧪 Real-World Examples
1. Login Simulation
def login(username, password): if username == "admin" and password == "1234": return "Login successful" else: return "Invalid credentials"
2. Math Operation
def multiply(a, b): return a * b
3. Temperature Conversion
def celsius_to_fahrenheit(c): return (c * 9/5) + 32
4. Greeting Bot
def greet_by_time(name, hour): if hour < 12: return f"Good morning, {name}" elif hour < 18: return f"Good afternoon, {name}" else: return f"Good evening, {name}"
5. Check Even or Odd
def is_even(n): return n % 2 == 0
🛠️ Best Practices
- Use meaningful function names (
calculate_salary()
instead ofcs()
) - Keep functions short and focused on a single task
- Add comments or docstrings to describe functionality
- Reuse functions wherever possible
- Avoid using too many global variables
Functions are like the engine of your Python programs. Once you master defining and calling them using def
, your code becomes more organized, reusable, and readable. This guide has walked you through the fundamentals with plenty of practical examples. Whether you’re building a web app or a small script, knowing how to use functions properly will make your life as a Python developer much easier.