Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page

Was this helpful?

  1. Python
  2. Basics

Functions

Functions in Python are blocks of reusable code that perform specific tasks. They allow you to break down your program into smaller, more manageable pieces, making your code more organized, modular, and easier to maintain. Functions are a fundamental concept in Python and are used extensively in Python programming. Here's how functions work in Python:

  1. Defining a Function: To create a function, you use the def keyword, followed by the function name, a pair of parentheses (), and a colon : to indicate the beginning of the function block. The function block is indented to define the scope of the function.

    def greet(name):   # <-Function Header
        # Function Documentation, i.e. Docstring
        """This function greets the person passed in as a parameter.""" 
        print(f"Hello, {name}!")   # <-Function Body

    In the above example, we've defined a function called greet that takes one parameter name.

  2. Calling a Function: To execute a function and perform the tasks defined inside it, you call the function by its name, passing any required arguments within the parentheses.

    greet("Alice")

    This call to the greet function with the argument "Alice" will print "Hello, Alice!" to the console.

  3. Function Parameters: Functions can accept zero or more parameters (also known as arguments) that are used to pass data into the function. Parameters are defined within the parentheses when defining the function.

    def add_numbers(a, b): 
        """This function adds two numbers and returns the result."""
        result = a + b 
        return result

    In this example, the add_numbers function takes two parameters, a and b, and returns their sum.

  4. Function Return Values: Functions can return values using the return statement. The value returned by the function can be assigned to a variable or used directly.

    result = add_numbers(5, 3)

    The add_numbers function returns 8, which is then assigned to the variable result.

  5. Docstrings: It's a good practice to include a docstring (a triple-quoted string) at the beginning of your function to provide documentation and describe the purpose of the function and its parameters.

    def multiply(a, b): 
    """This function multiplies two numbers and returns the result."""
        result = a * b 
        return result

    Docstrings are used to generate documentation using tools like Python's help() function.

  6. Scope: Variables defined inside a function have local scope, meaning they are only accessible within that function. Variables defined outside functions have global scope and can be accessed from anywhere in the code.

  7. Default Arguments: You can specify default values for function parameters, allowing you to call the function with fewer arguments if needed.

    def power(base, exponent=2): 
        """This function calculates the power of a number."""
        result = base ** exponent 
        return result

    In this example, the exponent parameter has a default value of 2, so you can call power(3) to calculate 3^2, or power(3, 4) to calculate 3^4.

  8. Arbitrary Argument Lists: You can use *args and **kwargs to pass a variable number of non-keyword and keyword arguments, respectively, to a function.

    def print_args(*args, **kwargs): 
        """This function prints the arguments passed to it."""
        print("Positional arguments:", args)
        print("Keyword arguments:", kwargs)

    *args allows you to pass a variable number of positional arguments, and **kwargs allows you to pass a variable number of keyword arguments.

Functions are a fundamental building block in Python programming and are essential for structuring your code, making it more readable, modular, and maintainable. They allow you to encapsulate logic, promote code reusability, and simplify complex tasks. Understanding how to define, call, and work with functions is a key skill for Python developers.

Last updated 1 year ago

Was this helpful?

Page cover image