A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly
brackets, and they have keys and values.
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python,
which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the
mutable data-structure. The dictionary is defined into element Keys and values.
Syntax: my_dict = {
"name": "John",
"age": 25,
"city": "Agra"
}
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following way.
1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
2. print(type(Employee))
3. print("printing Employee data..")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company:GOOGLE
Functions are the most important aspect of an application. A function can be defined as the organized block of
reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a function. A function can be
called multiple times to provide reusability and modularity to the Python program.
Types of function:
o User-define functions - The user-defined functions are those define by the user to perform the specific task.
o Built-in functions - The built-in functions are those functions that are predefined in Python.
Defining a Function:
def greet():
print("Hello, Shivanshu!")
Function Calling: In Python, after the function is created, we can call it from another function. A function must be
defined before the function call; otherwise, the Python interpreter gives an error. To call the function, use the
function name followed by the parentheses.
Example: def greet():
print("Hello, Shivanshu!")
# Calling the function
greet()
Function Arguments: The arguments are types of information which can be passed into the function. The arguments
are specified in the parentheses. We can pass any number of arguments, but they must be separate them with a
comma.
Example
1. #defining the function
2. def func (name):
3. print("Hi ",name)
4. #calling the function
5. func("Devansh")
Output:
Hi Devansh
Types of arguments:
1. Required arguments: These are passed in the correct position/order.
The function receives arguments in the order they are defined.
Example: 1. def func(name):
2. message = "Hi "+name
3. return message
4. name = input("Enter the name:")
5. print(func(name)
) Output:
Enter the name: John
Hi John
2. Keyword arguments: While calling a function, you can specify arguments using key=value format.
This allows passing values in any order.
def student(name, age):
print("Name:", name)
print("Age:", age)
student(age=25, name="John")
3. Default arguments: You can assign a default value to a parameter in the function definition.
If the caller doesn’t provide that argument, the default value is used.
Example
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john")
Output:
My name is John and age is 22
3. Variable Length Arguments: Sometimes you don’t know in advance how many arguments you want to pass to a
function. Python allows you to handle this with:
1. *args – for non-keyword variable arguments:
Allows you to pass any number of positional arguments.
Internally, args is treated as a tuple.
Example: def add_numbers(*args):
total = 0
for num in args:
total += num
print("Sum:", total)
# Calling function with different number of arguments
add_numbers(10, 20)
add_numbers(5, 10, 15, 20)
Output
Sum: 30
Sum: 50
2. **kwargs – for keyword variable arguments:
Allows you to pass any number of keyword arguments.
Internally, kwargs is treated as a dictionary.
Example: def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
# Calling function with keyword arguments
print_info(name="John", age=25, city="Los Angles")
Output
name: John
age: 25
city: Los Angles
Anonymous functions: Python Lambda function is known as the anonymous function that is defined without a
name. Lambda functions can accept any number of arguments, but they can return only one value in the form of
expression. The anonymous function contains a small piece of code. It simulates inline functions of C and C++, but it
is not exactly an inline function.
Syntax: lambda arguments: expression
Example: Square of a Number
square = lambda x: x * x
print(square(5)) # Output: 25
Local Variable: A variable declared inside a function
Can be accessed only within that function.
Example: def show():
x = 10 # Local variable
print("Inside function:", x)
show()
# print(x) ❌ Error: x is not defined outside the function
Global Variable: A variable declared outside all functions
Can be accessed inside any function.
Example: x = 20 # Global variable
def display():
print("Inside function:", x)
display()
print("Outside function:", x)
Module: A python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is
treated as the module. We may have a runnable code inside the python module.
Importing Modules
Syntax: import module_name
Example: import math
print([Link](16)) # Output: 4.0
1. MATH MODULE: The math module provides mathematical functions.
Example: import math
print([Link](9)) # Square root
print([Link](2, 3)) # Power
print([Link](5)) # Factorial
print([Link]) # π value
print([Link]([Link]/2)) # Trigonometry
Functions:
[Link](x)- Square root of x. Ex: [Link](16) → 4.0
2. [Link](x, y)- x raised to the power y Ex: [Link](2, 3) → 8.0
3. [Link](x)- Factorial of x Ex: [Link](5) → 120
4. [Link]- Value of π (constant) Ex: [Link] → 3.141592...
5. math.e- Value of e (Euler's number) Ex: math.e → 2.71828...
2. RANDOM MODULE: The random module is used for random number generation.
Example: import random
print([Link](1, 10)) # Random integer
print([Link](['a', 'b'])) # Random choice from list
print([Link]()) # Random float between 0 and 1
Functions:
1. [Link]()- Random float between 0.0 and 1.0 Ex: [Link]() → 0.367...
2. [Link](a, b)- Random integer between a and b (inclusive) Ex: [Link](1, 6) → 3
3. [Link](a, b)- Random float between a and b Ex: [Link](1, 5) → 2.78
4. [Link](seq)- Random item from a sequence (list, tuple, etc.) Ex: [Link](['a', 'b']) → 'b'
Packages: The packages in python facilitate the developer with the application development environment by
providing a hierarchical directory structure where a package contains subpackages, modules, and sub-modules. The
packages are used to categorize the application.
File handling in Python is a powerful and versatile tool that can be used to perform a wide range of operations.
However, it is important to carefully consider the advantages and disadvantages of file handling when writing Python
programs, to ensure that the code is secure, reliable, and performs well.
Opening a File
Syntax: file = open("[Link]", "mode")
Reading From a File
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Writing to a File
f = open("[Link]", "w")
[Link]("Hello Shivanshu!")
[Link]()
Appending to a File
f = open("[Link]", "a")
[Link]("\nNew Line added.")
[Link]()