E-Books

⚙️ Functions in Python

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.


  def function_name():
      # Code block          
            

⚙️ Creating a Function in Python

In Python a function is defined using the def keyword:


  def my_function():
      print("Hello from a function")
            

⚙️ Calling a Function in Python

To call a function, use the function name followed by parenthesis:


  def my_function():
      print("Hello from a function")

  my_function()
            

⚙️ Types of Functions in Python

Python comes preloaded with many function definitions that you can use or create new functions.

1. Module Functions 2. Built-in Functions 3. User-Defined Functions

⚙️ Module Functions in Python

A module is a Python file with the .py extension that contains a collection of functions, classes, and variables. You can import and use functions from a module.


  import math
  print(math.sqrt(16))  # Output: 4.0
  print(math.factorial(5))  # Output: 120
  print(math.pi)  # Output: 3.141592653589793              
            

⚙️ Built-in Functions in Python

Built-in functions are the functions that are always available in Python — no need to import any module.


  name = input("Enter your name: ")
  print("Hello,", name)
  print("Length of your name:", len(name))
          

⚙️ User-Defined Functions in Python

User-defined functions in Python are functions that are created by the user to perform specific tasks.


  def function_name(parameters): # Function Header
      # Function body
      # Code to execute
      return result
            

⚙️ Function Parameters and Arguments in Python

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.


  def greet(name):   # 'name' is a parameter
      print("Hello", name)

  greet("Deepak")     # "Deepak" is an argument
            

⚙️ Types of User-Defined Functions in Python

1. Takes Nothing, Returns Nothing Function does not take parameters and does not return a value. Only performs a task.


  def add_numbers():
      a = 5
      b = 3
      print("Sum =", a + b)
          
  add_numbers()          
            


Takes Something, Returns Nothing Function takes parameters but does not return any value. Used for processing input.


  def add_numbers(a, b):
      sum = a + b
      print("Sum =", Sum)
                    
  add_numbers(5, 3)            
            


Takes Nothing, Returns Something Function doesn’t take input, but returns a value. Used when logic is inside function.


  def add_numbers():
      a = 5
      b = 3
      return a + b
                    
  sum = add_numbers()        
  print("Sum =", Sum)
            


Takes Something, Returns Something Function takes input and returns a value. Most common and useful type.


  def add_numbers(a, b):
      return a + b
                    
  sum = add_numbers(5, 3)        
  print("Sum =", Sum)
            


⚙️ Types of Parameters / Arguments in Python

In Python, there are five main types of parameters/arguments used in functions.

1. Required Positional Arguments

2. Keyword Arguments

3. Default Arguments

4. Variable-length Positional Arguments (*args)

5. Variable-length Keyword Arguments (**kwargs)

⚙️ Python Function – Required Positional Arguments

A required positional argument is an argument that must be passed to the function

If any required argument is missing Python will raise an error.


  def display(name, age):
      print("Name:", name)
      print("Age:", age)

  display("Riya", 21)   # ✅ Correct
  display(21, "Riya")   # ⚠️ Wrong Order – Incorrect Output
  display("Amit")       # ❌ Error – Missing Argument
            

⚙️ Python Function – Keyword Arguments

Keyword arguments allow you to pass values to function parameters by name instead of by position.


  def display(name, age):
      print("Name:", name)
      print("Age:", age)
          
  # ✅ Correct: Using keyword arguments in order
  display(name="Riya", age=21)
  
  # ✅ Correct: Order doesn't matter with keyword arguments
  display(age=21, name="Riya")
  
  # ✅ Correct: Positional first, then keyword
  display("Riya", age=21)
  
  # ❌ Error: Keyword cannot come before positional
  display(name="Riya", 21)   # SyntaxError: positional argument follows keyword argument          
            

⚙️ Python Function - Default Arguments

In Python, default arguments allow you to assign a default value to a function parameter that is used if no value is given during the call.


  def display(age=18, name):  # ❌ SyntaxError: non-default argument follows default argument 
      # Function body

  def display(name, age=18):  # Default value for age is 18
      print("Name:", name)
      print("Age:", age)

  # ✅ Both arguments provided
  display("Riya", 21)

  # ✅ Only one argument: 'age' uses default value (18)
  display("Amit")

  # ✅ Keyword argument used for default parameter
  display("Amit", age=25)
            

⚙️ Python Function Variable-length Positional Arguments (*args)

*args allows you to pass a variable number of positional arguments to a function. These arguments are collected into a tuple.


  def add(*args):
      total = 0
      for num in args:
          total += num
      print("Sum:", total)
          
  # ✅ Passing multiple numbers
  add(10, 20, 30)
  
  # ✅ Passing no arguments
  add()
  
  # ✅ Passing any number of values
  add(5, 15, 25, 35, 45)          
            

⚙️ Python Function – Variable-length Keyword Arguments (**kwargs)

**kwargs lets you pass any number of keyword arguments to a function. These are stored as a dictionary.


  def display_details(**kwargs):
      for key, value in kwargs.items():
          print(key + ":", value)

  # ✅ Passing multiple keyword arguments
  display_details(name="John", age=25, course="Python")

  # ✅ Passing no arguments
  display_details()

  # ✅ Passing keyword arguments in any order
  display_details(course="Java", city="Delhi", name="Amit")
            

⚙️ Python Function – return Statement

The return statement return a value back from a function to the place where it was called. It ends the function's execution.

In Python, if a function does not have a return statement, it is considered a void function. By default, such functions return None.


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

  # ✅ Store returned value
  sum = add(10, 20)
  print("Sum:", sum)

  # ✅ Use directly in expression
  print("Double of sum:", add(10, 20) * 2)
            

⚙️ Python anonymous - lambda Functions

A lambda function is a small anonymous function defined using the lambda keyword. It can take any number of arguments but has only one expression.


  # ✅ Lambda function to add two numbers
  add = lambda a, b: a + b
  print("Sum:", add(10, 5)) 

  # ✅ Lambda function to find square
  square = lambda x: x * x
  print("Square:", square(4))

  # ✅ Lambda function inside another function
  def multiply(n):
      return lambda a: a * n

  double = multiply(2)
  print("Double:", double(5))
            

⚙️ Python Function – Local and Global Variables

Local Variable: Defined inside a function and accessible only within that function.


  def show():
      x = 50  # Local variable
      print("Inside function:", x)

  show()
  print("Outside function:", x) # ❌ Not accessible
            


Global Variable: Defined outside the functions and accessible throughout the program.


  x = 100  # Global variable

  def show():
      print("Inside function:", x)

  show()
  print("Outside function:", x) # ✅ Accessible
            

⚙️ Python Function – global Keyword

The global keyword is used to access and modify a global variable from inside a function.

⚠️ Without global Keyword x = x + 10 ❌ UnboundLocalError: local variable 'x' referenced before assignment


  x = 5  # Global variable

  def update():
      global x
      x = x + 10
      print("Inside function:", x)

  update()
  print("Outside function:", x)
            

⚙️ Python – Lifetime and Scope of Variables

Scope: Scope refers to where a variable can be accessed in the program.

Lifetime: Lifetime refers to how long a variable exists in memory during program execution.


  # Variable a is created when the function starts and destroyed when it ends — this is its lifetime.

  def my_function():
      a = 10  # Local variable
      a = a + 1
      print("Inside function:", a)
          
  # Calling the function multiple times
  my_function()
  my_function()
  my_function()
            

⚙️ Python – Recursive Functions

A recursive function is a function that calls itself to solve a smaller instance of the same problem until a base condition is met.


  def factorial(n):
      if n == 0:  # Base case
          return 1
      else:
          return n * factorial(n - 1)  # Recursive call

  # Calling the recursive function
  print(factorial(5)) 
            

⚙️ Python – Library Functions

Library functions are predefined functions provided by Python's standard libraries. You can directly use them without defining them yourself.

Function Description Example
print() Prints output to the screen print("Hello")
input() Takes input from the user input("Enter name: ")
len() Returns length of string/list len("Python") → 6
type() Returns data type type(10) → int
str() Converts to string str(100) → '100'
int() Converts to integer int("5") → 5
float() Converts to float float("2.5") → 2.5
bool() Converts to boolean bool(0) → False
abs() Absolute value abs(-4) → 4
max() Maximum value max(2, 5, 9) → 9
min() Minimum value min(3, 1, 7) → 1
sum() Sum of list elements sum([1,2,3]) → 6
round() Rounds number round(3.6) → 4
sorted() Sorted list sorted([3,1,2]) → [1,2,3]
reversed() Reversed list iterator list(reversed([1,2,3]))
enumerate() Adds index to items list(enumerate(['a','b']))
range() Sequence of numbers range(1, 5)
eval() Evaluates string as code eval("5+3") → 8
id() Object memory address id(5)
chr() Unicode to character chr(65) → 'A'
ord() Character to Unicode ord('A') → 65
bin() Decimal to binary bin(5) → '0b101'
hex() Decimal to hexadecimal hex(10) → '0xa'

⚙️ Python - String Methods

All string methods return new values. They do not change the original string.

Method Description Example
capitalize()Converts the first character to upper case"hello".capitalize() → "Hello"
lower()Converts a string into lower case"Hello".lower() → "hello"
upper()Converts a string into upper case"hello".upper() → "HELLO"
title()Converts the first character of each word to upper case"hello world".title() → "Hello World"
swapcase()Swaps cases, lower becomes upper and vice versa"HeLLo".swapcase() → "hEllO"
isalnum()True if all characters are alphanumeric"abc123".isalnum() → True
isalpha()True if all characters are alphabetic"abc".isalpha() → True
isdigit()True if all characters are digits"123".isdigit() → True
islower()True if all characters are lower case"hello".islower() → True
isupper()True if all characters are upper case"HELLO".isupper() → True
isspace()True if all characters are whitespace" ".isspace() → True
istitle()True if the string is titlecased"Hello World".istitle() → True
isnumeric()True if all characters are numeric"123".isnumeric() → True
isdecimal()True if all characters are decimal"123".isdecimal() → True
isprintable()True if all characters are printable"Hello".isprintable() → True
isidentifier()True if the string is a valid identifier"name1".isidentifier() → True
endswith()True if the string ends with specified value"hello.py".endswith(".py") → True
startswith()True if the string starts with specified value"hello.py".startswith("he") → True
find()Returns index of first match or -1"hello".find("e") → 1
replace()Replaces a value with another"hello".replace("l", "x") → "hexxo"
count()Counts number of times a value occurs"banana".count("a") → 3
index()Returns index of first match (error if not found)"hello".index("e") → 1
join()Joins elements with string",".join(["a","b"]) → "a,b"
split()Splits string into list"a,b,c".split(",") → ['a', 'b', 'c']
partition()Splits at first match into 3-part tuple"hello world".partition(" ") → ('hello', ' ', 'world')
strip()Removes whitespace from both ends" hello ".strip() → "hello"
lstrip()Removes whitespace from left" hello".lstrip() → "hello"
rstrip()Removes whitespace from right"hello ".rstrip() → "hello"
zfill()Fills string with zeros at the start"5".zfill(3) → "005"
format()Formats specified values"Name: {}".format("Raj") → "Name: Raj"
encode()Encodes the string into bytes using specified encoding"Hello".encode() → b'Hello'
decode()Decodes bytes into string using specified encodingb'Hello'.decode() → 'Hello'

⚙️ Python Pattern Matching Using Regular Expressions

Pattern matching in Python is done using the re module, which provides functions to search, match, and manipulate string patterns using regular expressions (regex).

import re

Method Description Example Code Output
re.match() Matches pattern at the beginning of a string re.match("Hello", "Hello World") Match object
re.search() Searches the string for a match anywhere re.search("World", "Hello World") Match object
re.findall() Returns all matches of the pattern re.findall("a", "banana") ['a', 'a', 'a']
re.sub() Replaces occurrences of the pattern with a replacement re.sub("a", "o", "banana") "bonono"
re.split() Splits the string using the pattern as a delimiter re.split("-", "2024-05-08") ['2024', '05', '08']


  import re
  
  # Sample text
  text = "Hello World! Welcome to the world of Python. Let's find patterns in this text."
  
  # re.match() - Matches pattern at the beginning of the string
  match = re.match(r"Hello", text)
  if match:
      print("Match found:", match.group())  # Output: Match found: Hello
  else:
      print("No match found with re.match()")
  
  # re.search() - Searches for the pattern anywhere in the string
  search = re.search(r"world", text, re.IGNORECASE)  # Case insensitive search
  if search:
      print("Search found:", search.group())  # Output: Search found: World
  else:
      print("No match found with re.search()")
  
  # re.findall() - Finds all occurrences of the pattern in the string
  findall = re.findall(r"world", text, re.IGNORECASE)
  print("All occurrences found with re.findall():", findall)  # Output: ['World', 'world']
  
  # re.sub() - Replaces occurrences of the pattern with a replacement
  sub = re.sub(r"world", "universe", text, flags=re.IGNORECASE)
  print("Text after re.sub():", sub)  # Output: Hello Universe! Welcome to the universe of Python. Let's find patterns in this text.
  
  # re.split() - Splits the string using the pattern as a delimiter
  split = re.split(r"\s", text)  # Splits by whitespace
  print("Text after re.split():", split)  # Output: ['Hello', 'World!', 'Welcome', 'to', 'the', 'world', 'of', 'Python.', 'Let's', 'find', 'patterns', 'in','th'text.']              
            

⚙️ Python Numeric Functions

Includes built-in and math module functions for working with numbers.

Function Description Example Output
abs()Returns the absolute valueabs(-10)10
pow()Returns x raised to the power ypow(2, 3)8
round()Rounds a number to the nearest integerround(3.6)4
divmod()Returns quotient and remainderdivmod(9, 2)(4, 1)
max()Returns the largest valuemax(10, 20, 5)20
min()Returns the smallest valuemin(10, 20, 5)5
math.sqrt()Returns square rootmath.sqrt(16)4.0
math.ceil()Rounds up to the nearest integermath.ceil(3.2)4
math.floor()Rounds down to the nearest integermath.floor(3.8)3
math.factorial()Returns factorial of a numbermath.factorial(5)120
math.fabs()Returns absolute value (float)math.fabs(-7.5)7.5
math.exp()Returns e raised to the power xmath.exp(2)7.389
math.piReturns the value of πmath.pi3.141592653589793

⚙️ Python Random Module Functions

Includes functions for generating random numbers and selections

Function Description Example Output
random.random() Generates a random float between 0.0 and 1.0 random.random() 0.3745401188473625
random.randint() Generates a random integer within a given range random.randint(1, 100) 37
random.randrange() Returns a randomly selected element from the range(start, stop, step) random.randrange(0, 10, 2) 6
random.choice() Returns a random element from a non-empty sequence random.choice([1, 2, 3, 4, 5]) 3
random.shuffle() Shuffles a sequence in place random.shuffle([1, 2, 3, 4]) [3, 1, 4, 2] (order may vary)
random.sample() Returns a specified number of random elements from a sequence random.sample([1, 2, 3, 4], 2) [2, 3]
random.uniform() Generates a random float within a given range random.uniform(1.5, 10.5) 7.342901695992736

🧭 Python Date and Time Functions

Includes functions for working with dates and times.

Function Description Example Output
time() Returns the current time in seconds since the epoch time.time() 1715330590.123456
localtime() Converts seconds since epoch to a struct_time in local time time.localtime() time.struct_time(tm_year=2025, tm_mon=5, ...)
asctime() Converts a struct_time to a readable string time.asctime(time.localtime()) "Sat May 10 12:30:45 2025"
datetime.now() Returns current local date and time datetime.now() 2025-05-10 12:30:45.123456
date.today() Returns the current date date.today() 2025-05-10
datetime.date() Returns the date part of a datetime object datetime.now().date() 2025-05-10
dir() Returns all properties and methods of an object/module dir(time) ['asctime', 'ctime', 'sleep', ...]
timestamp() Returns POSIX timestamp (float) from datetime object datetime.now().timestamp() 1715330590.123456
strftime() Formats datetime object to a string datetime.now().strftime("%Y-%m-%d %H:%M:%S") 2025-05-10 12:30:45
sleep(secs) Suspends (delays) execution of the current thread for the given number of seconds. time.sleep(2) Pauses the program for 2 seconds

🧭 Python calendar Module Functions

Function Description Example Output
calendar.calendar() Returns a multi-line string of the calendar for an entire year. calendar.calendar(2025) Calendar for 2025
calendar.month() Returns a multi-line string for a single month's calendar. calendar.month(2025, 5) Calendar for May 2025
calendar.prcal() Prints the calendar for an entire year. calendar.prcal(2025) Printed calendar
calendar.prmonth() Prints a single month's calendar. calendar.prmonth(2025, 5) Printed May 2025
calendar.isleap() Returns True if the year is a leap year, else False. calendar.isleap(2024) True
calendar.leapdays() Returns the number of leap years between two years (exclusive of the second). calendar.leapdays(2000, 2025) 6
calendar.weekday() Returns the weekday (0=Monday to 6=Sunday) of a specific date. calendar.weekday(2025, 5, 10) 5
calendar.setfirstweekday() Sets the first day of the week (0=Monday, 6=Sunday). calendar.setfirstweekday(6)
calendar.firstweekday() Returns the current setting for the first day of the week. calendar.firstweekday() 0 (default Monday)
Previous Next