Comprehensive Guide to Python Functions with Examples

Comprehensive Guide to Python Functions with Examples

Functions are one of the fundamental building blocks in Python programming. They allow you to organize your code into reusable blocks that perform specific tasks. In this guide, we will dive deep into how to create and use functions in Python, explore different types of arguments, and understand the difference between printing and returning values from functions.


1. What is a Function?

A function is a named block of code that performs a specific task. Once a function is defined, you can call (execute) it any number of times from different parts of your program. Functions help you avoid repetition, improve code readability, and organize your logic effectively.

Basic Syntax


def function_name(parameters):
    # function body (code)
    return value  # optional

Here:

  • def keyword is used to declare a function.
  • function_name is the name you give your function.
  • parameters are variables passed to the function to accept inputs (can be empty).
  • return is used to send a result back to the caller (optional).

Example 1: Simple Function Without Parameters


def greet():
    print("Hello, welcome to Python!")

greet()

Output:


Hello, welcome to Python!

Note: This function simply prints a message and does not return any value.


2. Parameters and Arguments

Functions can take inputs to perform tasks based on those inputs. These inputs are called parameters inside the function definition and arguments when you call the function.

Example 2: Function with a Parameter


def greet(name):
    print("Hello,", name)

greet("Ayush")
greet("Arun")

Output:


Hello, Ayush
Hello, Arun

Important: The order and number of arguments must match the parameters defined unless you use special types of arguments (explained below).


3. Different Types of Function Arguments

3.1 Positional Arguments

These are the most common arguments where values are passed in the same order as parameters.


def full_name(first, last):
    print("Full Name:", first, last)

full_name("John", "Doe")

Output:


Full Name: John Doe

3.2 Keyword Arguments

You can specify arguments by the parameter name, so the order doesn't matter.


full_name(last="Doe", first="John")

Output:


Full Name: John Doe

3.3 Default Arguments

Assign default values to parameters so if no argument is passed, the default is used.


def greet(name="Guest"):
    print("Hello", name)

greet()
greet("Arun")

Output:


Hello Guest
Hello Arun

3.4 Variable-Length Arguments

When you don’t know how many arguments might be passed, use *args and **kwargs.

  • *args β€” collects extra positional arguments into a tuple.
  • **kwargs β€” collects extra keyword arguments into a dictionary.

Example using *args


def add_numbers(*args):
    total = 0
    for num in args:
        total += num
    print("Sum is", total)

add_numbers(5, 10, 15)

Output:


Sum is 30

Example using **kwargs


def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Ayush", age=18, city="Delhi")

Output:


name: Ayush
age: 18
city: Delhi

4. Printing vs Returning Values

Understanding the difference between print() and return is crucial for writing effective functions.

4.1 Printing inside Functions

When you use print() inside a function, it outputs the data immediately to the console but the function itself returns None.


def show():
    print("Hello from function")

result = show()
print("Returned:", result)

Output:


Hello from function
Returned: None

4.2 Returning Values from Functions

return passes a value back to the caller and ends the function execution.


def add(a, b):
    return a + b

result = add(10, 5)
print("Sum is", result)

Output:


Sum is 15

Note: Returned values can be stored, manipulated, or used in expressions later, unlike printed values.


5. How to Return Multiple Values

You can return multiple values separated by commas β€” Python packs them into a tuple.


def get_name_and_age():
    name = "Ayush"
    age = 18
    return name, age

person_name, person_age = get_name_and_age()
print(person_name)
print(person_age)

Output:


Ayush
18

6. Complete Function Example: Simple Calculator


def calculator(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "sub":
        return a - b
    elif operation == "mul":
        return a * b
    elif operation == "div":
        if b != 0:
            return a / b
        else:
            return "Cannot divide by zero"
    else:
        return "Invalid operation"

print(calculator(10, 5, "add"))  # 15
print(calculator(10, 5, "sub"))  # 5
print(calculator(10, 5, "div"))  # 2.0
print(calculator(10, 0, "div"))  # Cannot divide by zero
print(calculator(10, 5, "xyz"))  # Invalid operation

Output:


15
5
2.0
Cannot divide by zero
Invalid operation

7. Important Notes and Best Practices

  • Use meaningful function names: Choose names that clearly describe what the function does.
  • Keep functions small: Each function should do one specific task.
  • Use return for reusable results: If you want to reuse the output later, return it instead of printing.
  • Use default arguments to make your functions flexible.
  • Use *args and **kwargs for functions with variable input.
  • Always test your functions with different inputs to avoid unexpected errors.

Summary Table

Term Description
Function Reusable block of code performing a specific task.
Parameter Variable in function definition to accept input.
Argument Value passed to function parameter during call.
Return Sends a value back to the caller and ends function.
Print Outputs data immediately but does not send back value.
*args Variable number of positional arguments packed into tuple.
**kwargs Variable number of keyword arguments packed into dict.

πŸ“š Practice Questions:


πŸ“š Related Topics:


πŸ“Œ Bookmark this blog or follow for updates!

Python Logo

πŸ‘ Liked this post? Share it with friends or leave a comment below!

β€œIn the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python

πŸ“Œ Follow Us And Stay Updated For Daily Updates

πŸ“– More Resources

πŸ“š Python Crash Course Chapter-wise Exercises
πŸ“š AI And MACHINE LEARNING ROADMAP: From Basic to Advanced
    Stage 1: Python & Programming Fundamentals
    
    ----------------------------------------
    1. Python & Programming Fundamentals
    ----------------------------------------
    1.1 Environment Setup
        β€’ Install Python 3.x, VS Code / PyCharm
        β€’ Configure linting, formatters (e.g., Pylint, Black)
        β€’ Jupyter Notebook / Google Colab basics
    
    1.2 Core Python Syntax
        β€’ Variables, Data Types (int, float, str, bool)
        β€’ Operators: arithmetic, comparison, logical, bitwise
        β€’ Control Flow: if / else / elif
        β€’ Loops: for, while, break/continue
    
    1.3 Functions & Modules
        β€’ Defining functions, return values
        β€’ Parameters: positional, keyword, default args
        β€’ *args, **kwargs
        β€’ Organizing code: modules and packages
        β€’ Standard library exploration (os, sys, datetime, random, math)
    
    1.4 Data Structures
        β€’ Lists, Tuples, Sets, Dictionaries
        β€’ List/dict comprehensions
        β€’ Built-in functions: map, filter, zip, enumerate
        β€’ When to use which structure
    
    1.5 File Handling & Exceptions
        β€’ Reading/Writing text and binary files
        β€’ Context managers (`with` statement)
        β€’ Exception handling: try/except/finally
        β€’ Custom exceptions
    
    1.6 Object-Oriented Programming (OOP)
        β€’ Classes, Instances, Attributes, Methods
        β€’ __init__, self, class vs instance attributes
        β€’ Inheritance, Polymorphism, Encapsulation
        β€’ Magic methods: __str__, __repr__, __add__, etc.
        β€’ Use-cases in structuring larger projects
    
    1.7 Virtual Environments & Package Management
        β€’ venv / pipenv / poetry basics
        β€’ Installing and managing dependencies
        β€’ requirements.txt and environment.yml
    
    πŸ›  Tools: VS Code, Git for version control, Jupyter/Colab
        
    Stage 2: Mathematics for Machine Learning
    
    ----------------------------------------
    2. Mathematics for Machine Learning
    ----------------------------------------
    2.1 Linear Algebra
        β€’ Scalars, Vectors, Matrices, Tensors
        β€’ Operations: addition, multiplication, dot product
        β€’ Matrix properties: transpose, inverse, rank
        β€’ Eigenvalues & Eigenvectors (intuition)
        β€’ Applications: data transformations, PCA
    
    2.2 Calculus
        β€’ Functions and limits (intuitive overview)
        β€’ Derivatives: gradient of single-variable and multi-variable functions
        β€’ Chain rule (key for backpropagation in neural networks)
        β€’ Partial derivatives
        β€’ Basic integration (overview; less often used directly)
    
    2.3 Probability & Statistics
        β€’ Basic probability theory: events, conditional probability, Bayes’ theorem
        β€’ Random variables, distributions (normal, binomial, Poisson, etc.)
        β€’ Descriptive statistics: mean, median, mode, variance, standard deviation
        β€’ Inferential statistics: hypothesis testing, p-values, confidence intervals
        β€’ Sampling methods, bias, variance concepts
    
    2.4 Optimization Basics
        β€’ Concept of optimization in ML (finding minima of loss functions)
        β€’ Gradient descent: batch, stochastic, mini-batch
        β€’ Learning rate intuition
    
    πŸ›  Tools / References: 
        β€’ Interactive calculators: Desmos, GeoGebra
        β€’ Python libraries: NumPy for experimentation
        
    Stage 3: Data Handling & Preprocessing
    
    ----------------------------------------
    3. Data Handling & Preprocessing
    ----------------------------------------
    3.1 NumPy Essentials
        β€’ ndarrays: creation, indexing, slicing
        β€’ Vectorized operations vs Python loops
        β€’ Broadcasting rules
        β€’ Random number generation
    
    3.2 Pandas for Tabular Data
        β€’ Series & DataFrame: creation and basic ops
        β€’ Reading data: CSV, Excel, JSON
        β€’ Indexing, selection (loc/iloc), filtering rows
        β€’ Handling missing values: dropna, fillna
        β€’ Detecting/removing duplicates
        β€’ Combining datasets: merge, join, concat
        β€’ GroupBy operations, aggregation, pivot tables
    
    3.3 Feature Engineering
        β€’ Feature scaling: normalization (Min-Max), standardization (Z-score)
        β€’ Encoding categorical variables: one-hot, ordinal encoding
        β€’ Date/time feature extraction (if applicable)
        β€’ Creating new features via domain knowledge
        β€’ Feature selection: variance threshold, correlation analysis
    
    3.4 Data Visualization
        β€’ Matplotlib basics: line plot, scatter plot, histograms, bar charts
        β€’ Seaborn overview: higher-level plots (heatmap, pairplot)
        β€’ Visualizing distributions, relationships, outliers
        β€’ Plot customization: titles, labels, legends
    
    3.5 Handling Real-World Data Challenges
        β€’ Imbalanced datasets: oversampling (SMOTE), undersampling, class weights
        β€’ Outlier detection and treatment
        β€’ Data leakage awareness
        β€’ Pipeline creation in scikit-learn
    
    πŸ›  Tools: NumPy, Pandas, Matplotlib, Seaborn, scikit-learn utilities
        
    Stage 4: Core Machine Learning
    
    ----------------------------------------
    4. Core Machine Learning
    ----------------------------------------
    4.1 ML Concepts & Workflow
        β€’ What is ML? Supervised vs Unsupervised vs Semi-supervised vs Reinforcement
        β€’ Training, Validation, Testing splits
        β€’ Overfitting vs Underfitting, bias-variance trade-off
        β€’ Cross-validation techniques: k-fold, stratified
    
    4.2 Supervised Learning: Regression
        β€’ Linear Regression: assumptions, cost function, normal equation
        β€’ Regularized Regression: Ridge, Lasso, Elastic Net
        β€’ Polynomial Regression
        β€’ Evaluation metrics: MSE, RMSE, MAE, RΒ²
    
    4.3 Supervised Learning: Classification
        β€’ Logistic Regression: sigmoid, decision boundary, loss
        β€’ k-Nearest Neighbors (KNN)
        β€’ Decision Trees: entropy/gini, pruning
        β€’ Ensemble Methods:
            - Bagging: Random Forest
            - Boosting: AdaBoost, Gradient Boosting, XGBoost (intro)
        β€’ Support Vector Machines (SVM): kernel trick overview
        β€’ Naive Bayes: Gaussian, Multinomial
        β€’ Evaluation: accuracy, precision, recall, F1-score, ROC-AUC
        β€’ Confusion matrix analysis
    
    4.4 Unsupervised Learning
        β€’ Clustering:
            - K-Means: elbow method, silhouette score
            - Hierarchical clustering: dendrograms
            - DBSCAN
        β€’ Dimensionality Reduction:
            - PCA: variance explained
            - t-SNE / UMAP (visualization-focused)
        β€’ Anomaly Detection overview
    
    4.5 Model Selection & Tuning
        β€’ Hyperparameter tuning: grid search, random search, Bayesian optimization (overview)
        β€’ Automated tuning libraries (e.g., scikit-learn’s GridSearchCV, RandomizedSearchCV)
        β€’ Pipeline building to avoid leakage
        β€’ Feature importance and model interpretability basics
    
    πŸ›  Tools: scikit-learn, pandas, NumPy
        
    Stage 5: Deep Learning Foundations
    
    ----------------------------------------
    5. Deep Learning Foundations
    ----------------------------------------
    5.1 Neural Network Basics
        β€’ Artificial neuron model, activation functions (ReLU, Sigmoid, Tanh)
        β€’ Architecture: input, hidden, output layers
        β€’ Forward propagation, loss functions (Cross-entropy, MSE)
        β€’ Backpropagation: gradient computation, chain rule
    
    5.2 Deep Learning Frameworks
        β€’ TensorFlow & Keras: Sequential and Functional APIs
        β€’ PyTorch basics: tensors, autograd, nn.Module
        β€’ Comparing TF/Keras vs PyTorch (choose one to start)
    
    5.3 Training Deep Models
        β€’ Optimizers: SGD, Adam, RMSprop
        β€’ Learning rate scheduling
        β€’ Regularization: Dropout, Batch Normalization, Weight Decay
        β€’ Handling overfitting: early stopping, data augmentation
    
    5.4 Basic DL Projects
        β€’ MNIST digit classification
        β€’ CIFAR-10 image classification (small CNN)
        β€’ Simple feedforward network on tabular data
    
    πŸ›  Tools: TensorFlow/Keras or PyTorch, GPU if available (Colab/GPU runtime)
        
    Stage 6: Advanced Deep Learning & Architectures
    
    ----------------------------------------
    6. Advanced Deep Learning & Architectures
    ----------------------------------------
    6.1 Convolutional Neural Networks (CNNs)
        β€’ Convolution operations, filters, feature maps
        β€’ Pooling layers, padding, stride
        β€’ Famous architectures overview: LeNet, AlexNet, VGG, ResNet (intuition)
        β€’ Transfer Learning: fine-tuning pre-trained models
    
    6.2 Recurrent Neural Networks (RNNs) & Sequence Models
        β€’ RNN basics: hidden states, vanishing gradients
        β€’ LSTM, GRU: gating mechanisms
        β€’ Sequence-to-sequence models (intro)
        β€’ Attention mechanism: intuition
    
    6.3 Transformers & Attention
        β€’ Self-attention mechanism
        β€’ Transformer architecture: encoder, decoder overview
        β€’ Pre-trained transformer models: BERT, GPT family (conceptual)
        β€’ Fine-tuning transformers for tasks
    
    6.4 Generative Models
        β€’ Autoencoders: basic, variational autoencoders (VAE) overview
        β€’ Generative Adversarial Networks (GANs): generator/discriminator intuition
        β€’ Applications and basic experiments
    
    6.5 Advanced Techniques
        β€’ Multi-task learning, meta-learning (intro)
        β€’ Few-shot learning, transfer learning deeper dive
        β€’ Neural architecture search (overview)
        β€’ Model compression, pruning, quantization (deployment considerations)
    
    πŸ›  Tools: TensorFlow / PyTorch, Hugging Face Transformers library
        
    Stage 7: Natural Language Processing (NLP) Advanced
    
    ----------------------------------------
    7. Natural Language Processing (NLP)
    ----------------------------------------
    7.1 Text Preprocessing & Representation
        β€’ Tokenization (word, subword/BPE)
        β€’ Stopwords removal, lemmatization vs stemming
        β€’ Word embeddings: Word2Vec, GloVe, FastText
        β€’ Contextual embeddings: ELMo, BERT embeddings
    
    7.2 Transformer-based NLP
        β€’ Pre-trained models: BERT, RoBERTa, GPT, T5
        β€’ Fine-tuning for classification, QA, summarization
        β€’ Sequence generation tasks using GPT-like models
    
    7.3 Specialized NLP Tasks
        β€’ Named Entity Recognition (NER)
        β€’ Machine Translation overview
        β€’ Question Answering pipelines
        β€’ Text Summarization (extractive vs abstractive)
        β€’ Sentiment Analysis deep dive
    
    7.4 Evaluation Metrics in NLP
        β€’ BLEU, ROUGE, METEOR (for generation)
        β€’ Accuracy, F1 for classification tasks
    
    πŸ›  Tools: Hugging Face Transformers, spaCy, NLTK
        
    Stage 8: Computer Vision Advanced
    
    ----------------------------------------
    8. Computer Vision (CV)
    ----------------------------------------
    8.1 Image Preprocessing & Augmentation
        β€’ OpenCV basics: reading, resizing, color conversions
        β€’ Data augmentation techniques: flips, rotations, crops, color jitter
    
    8.2 Advanced CNN Architectures
        β€’ Inception, ResNet, DenseNet, EfficientNet (conceptual)
        β€’ Transfer learning and fine-tuning advanced models
        β€’ Object detection frameworks: YOLOvX, SSD, Faster R-CNN (overview)
        β€’ Semantic segmentation: U-Net, Mask R-CNN
        β€’ Instance segmentation concepts
    
    8.3 Vision Transformers (ViT)
        β€’ Applying transformer concepts to images
        β€’ Fine-tuning ViT for classification
    
    8.4 Specialized CV Tasks
        β€’ Face recognition pipelines
        β€’ Video analysis basics: action recognition, object tracking
        β€’ 3D vision intro (depth estimation)
    
    πŸ›  Tools: OpenCV, TensorFlow/PyTorch, libraries like Detectron2 or YOLO implementations
        
    Stage 9: Reinforcement Learning & Advanced Topics
    
    ----------------------------------------
    9. Reinforcement Learning & Advanced Topics
    ----------------------------------------
    9.1 Reinforcement Learning Foundations
        β€’ Markov Decision Process (MDP)
        β€’ Value functions, policy functions
        β€’ Q-Learning, SARSA (tabular methods)
        β€’ Exploration vs Exploitation
    
    9.2 Deep Reinforcement Learning
        β€’ Deep Q-Networks (DQN)
        β€’ Policy Gradient Methods: REINFORCE, Actor-Critic
        β€’ Advanced: A3C, PPO, DDPG overview
    
    9.3 Other Advanced AI Topics
        β€’ Graph Neural Networks (GNNs): node/graph embeddings (overview)
        β€’ Time Series Forecasting with ML/DL: RNN/LSTM, Prophet intro
        β€’ Bayesian Methods overview
        β€’ AutoML and neural architecture search concepts
        β€’ Federated Learning basics (privacy-aware training)
        β€’ MLOps fundamentals:
            - Model versioning
            - Continuous integration/continuous deployment (CI/CD) for ML
            - Monitoring models in production
            - Tools: MLflow, Kubeflow (intro)
        β€’ Edge AI / TinyML overview (deploying models on devices)
    
    πŸ›  Tools: RL libraries (Stable Baselines3), MLflow, Kubernetes intro, Docker
        
    Stage 10: Deployment, Production & MLOps
    
    ----------------------------------------
    10. Deployment, Production & MLOps
    ----------------------------------------
    10.1 Model Serving & APIs
        β€’ REST API with Flask / FastAPI
        β€’ gRPC basics (overview)
        β€’ Dockerizing ML applications
        β€’ Serving with TensorFlow Serving or TorchServe
    
    10.2 Cloud Deployment
        β€’ Deploy on AWS Sagemaker / GCP AI Platform / Azure ML (basic workflow)
        β€’ Serverless deployments (AWS Lambda, Cloud Functions) for small models
        β€’ CI/CD pipelines for ML: GitHub Actions or Jenkins integration
    
    10.3 Monitoring & Maintenance
        β€’ Logging model inputs/outputs
        β€’ Drift detection (data/model drift)
        β€’ Retraining pipelines (automated or scheduled)
        β€’ Scaling considerations
    
    10.4 MLOps Tools & Practices
        β€’ Experiment tracking (MLflow, Weights & Biases)
        β€’ Data versioning (DVC)
        β€’ Model registry concepts
        β€’ Infrastructure as Code (Terraform intro)
    
    πŸ›  Tools: Docker, Kubernetes basics, CI/CD tools, cloud consoles
        
    Stage 11: Real-World Projects & Portfolio
    
    ----------------------------------------
    11. Real-World Projects & Portfolio
    ----------------------------------------
    11.1 Project Ideas by Domain
        β€’ Tabular Data: Predictive analytics (e.g., churn prediction)
        β€’ NLP: Chatbot, summarizer, translation prototype
        β€’ CV: Image classifier, object detector, image segmentation app
        β€’ Time Series: Forecasting stock or weather data
        β€’ RL: Simple game-playing agent
        β€’ Generative: GAN art generation or style transfer demo
    
    11.2 End-to-End Pipeline
        β€’ Data collection & preprocessing
        β€’ Model training & validation
        β€’ Deployment as API or web app (Streamlit/Flask)
        β€’ Monitoring & iteration
        β€’ Documentation & README
    
    11.3 Collaboration & Open Source
        β€’ Participate in Kaggle competitions (beginner β†’ intermediate)
        β€’ Contribute to open-source ML projects
        β€’ Write blog posts/tutorials documenting your projects
    
    11.4 Soft Skills & Communication
        β€’ Clear README, code comments
        β€’ Presentation slides or videos of project demos
        β€’ Networking: sharing work on LinkedIn, GitHub
    
    πŸ›  Tools: GitHub Pages, Streamlit, Heroku/Netlify, Docker
        
    Stage 12: Ethics, Explainability & Continuous Learning
    
    ----------------------------------------
    12. Ethics, Explainability & Continuous Learning
    ----------------------------------------
    12.1 AI Ethics & Responsible AI
        β€’ Bias & Fairness: identifying and mitigating bias
        β€’ Privacy concerns: GDPR, data protection best practices
        β€’ Transparency: documenting data sources and model decisions
    
    12.2 Explainable AI (XAI)
        β€’ Model interpretability: SHAP, LIME (basic usage)
        β€’ Interpreting black-box models vs inherently interpretable models
        β€’ Communicating explanations to stakeholders
    
    12.3 Continuous Learning & Staying Updated
        β€’ Following research: arXiv alerts, ML conferences (NeurIPS, ICML, CVPR summaries)
        β€’ Blogs, podcasts, newsletters (e.g., β€œThe Batch” by deeplearning.ai)
        β€’ Reading codebases of popular libraries, exploring new architectures
        β€’ Community involvement: forums, study groups
    
    12.4 Advanced Research Topics (Optional/For Aspirants)
        β€’ Research paper reading workflow
        β€’ Experimentation frameworks
        β€’ Contributing to academic research or advanced industrial research
    
    πŸ›  Tools: arXiv, Google Scholar alerts, RSS readers, community forums
        

Comments