0% found this document useful (0 votes)
2 views54 pages

Introduction to Python

Python is a high-level, interpreted, and object-oriented programming language known for its simplicity and versatility. It features easy syntax, dynamic typing, automatic memory management, and a large standard library, making it suitable for various applications. Python supports multiple programming paradigms, including procedural and object-oriented programming, and has a vast community for support and resources.

Uploaded by

harmanjot.e19510
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views54 pages

Introduction to Python

Python is a high-level, interpreted, and object-oriented programming language known for its simplicity and versatility. It features easy syntax, dynamic typing, automatic memory management, and a large standard library, making it suitable for various applications. Python supports multiple programming paradigms, including procedural and object-oriented programming, and has a vast community for support and resources.

Uploaded by

harmanjot.e19510
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Python

What is Python?
Python is a high-level, interpreted and object-oriented programming
language. It is one of the most popular programming languages in the world
because it is easy to learn, powerful, and versatile. Python allows
programmers to write clear and concise code, making software development
faster and easier.

Python was created by Guido van Rossum and was first released in 1991. The
language was designed with the philosophy that code should be simple,
readable, and easy to understand.

Today, Python is used by students, beginners, researchers, software


developers, and large companies for developing a wide variety of applications.

Features of Python
Python is one of the most popular programming languages because of its
powerful and user-friendly features. Below is a detailed explanation of the
main features.

1. Simple and Easy to Learn

Python has a simple syntax that resembles the English language. It requires
fewer lines of code compared to many other programming languages, making
it easy for beginners to learn.

Advantages

 Easy to read and write

 Beginner-friendly

 Faster program development

 Easy debugging and maintenance

2. Interpreted Language

Python is an interpreted language, meaning the code is executed line by line


by the Python interpreter instead of being compiled into machine code before
execution.

Example

print("First")

print("Second")
print("Third")

The interpreter executes:

1. print("First")

2. print("Second")

3. print("Third")

Advantages

 No separate compilation step

 Easier debugging because errors are reported immediately

 Faster testing during development

3. High-Level Language

Python is a high-level language, which means programmers do not need to


manage hardware details such as memory addresses.

Example

a = 10

b = 20

print(a + b)

The programmer only writes the logic, while Python handles memory
management automatically.

Advantages

 Easier programming

 Less complex code

 Improved productivity

4. Free and Open Source

Python is available free of cost. Anyone can download, use, modify, and
distribute it under its open-source license.

Advantages

 No licensing fee

 Large community support

 Continuous improvements by developers worldwide


5. Portable (Platform Independent)

Python programs can run on different operating systems with little or no


modification.

Supported platforms include:

 Windows

 Linux

 macOS

Advantages

 Write once, run anywhere

 Saves development time

 Easy software deployment

6. Object-Oriented Programming (OOP)

Python supports Object-Oriented Programming, where programs are


organized using classes and objects.

Advantages

 Code reuse

 Better organization

 Easier maintenance

 Improved security through encapsulation

7. Dynamically Typed

In Python, you do not declare the data type of a variable. Python


automatically determines the type at runtime.

Example

x = 10

y = 5.5

name = "Python"

Python automatically identifies:

 10 as an integer (int)
 5.5 as a floating-point number (float)

 "Python" as a string (str)

Advantages

 Less code

 Faster development

 Easy to modify variables

8. Automatic Memory Management

Python automatically allocates and frees memory using Garbage Collection.

Example

a = [1, 2, 3]

a = None

When the list is no longer referenced, Python automatically removes it from


memory.

Advantages

 No manual memory management

 Reduces memory leaks

 Safer programming

9. Extensive Standard Library

Python provides a rich collection of built-in modules for many tasks.

Some commonly used modules are:

Module Purpose

math Mathematical operations

random Random number generation

datetime Date and time handling

os Operating system functions

sys System-specific parameters

statistics Statistical calculations

Example
import math

print([Link](25))

Output

5.0

Advantages

 Less coding effort

 Ready-made solutions

 Saves development time

10. Large Community Support

Python has one of the largest programming communities in the world.

Benefits include:

 Thousands of tutorials

 Free documentation

 Online discussion forums

 Open-source projects

 Community-contributed libraries

This makes it easy to find help when solving programming problems.

11. Extensible and Embeddable

Python can work together with other programming languages.

 Extensible: You can write performance-critical parts in C or C++ and


use them from Python.

 Embeddable: Python can be embedded into applications written in


other languages.

Advantages

 Improved performance

 Easy integration with existing software

 Flexible application development

12. Huge Collection of Third-Party Libraries


Python has thousands of external packages that can be installed using pip.

Popular libraries include:

Library Purpose

NumPy Numerical computing

Pandas Data analysis

Matplotlib Data visualization

TensorFlow Artificial Intelligence

Flask Web development

Django Web development

OpenCV Image processing

Advantages

 Rapid application development

 Specialized tools for different domains

 Saves time by avoiding reinventing common functionality

Tokens in Python
What are Tokens?

A token is the smallest meaningful unit of a Python program that the Python
interpreter recognizes.

Example

a = 10 + 20

This statement contains the following tokens:

Types of Tokens in Python

Python tokens are mainly divided into the following categories:

1. Keywords

2. Identifiers

3. Variables

4. Literals (Constants)

5. Operators
6. Delimiters (Separators)

1. Keywords

Definition

Keywords are reserved words in Python that have predefined meanings. They
are used to define the syntax and structure of the language.

Since keywords have special meanings, they cannot be used as identifiers


(variable names, function names, or class names).

Examples of Python Keywords

Some commonly used keywords are:

False None True

and as assert

break class continue

def del elif

else except finally

for from global

if import in

is lambda nonlocal

not or pass

raise return try

while with yield

match case

Example

age = 20

if age >= 18:

print("Eligible to Vote")

Here:

 if is a keyword.

 print is a built-in function (not a keyword).


Invalid Example

if = 10

This is invalid because if is a reserved keyword.

2. Identifiers

Definition

Identifiers are the names given to variables, functions, classes, modules, or


objects.

Rules for Naming Identifiers

1. Can contain letters (A–Z, a–z), digits (0–9), and underscore (_).

2. Must start with a letter or underscore.

3. Cannot start with a digit.

4. Cannot be a keyword.

5. Are case-sensitive.

Valid Identifiers

student

student1

total_marks

_name

Marks

Invalid Identifiers

1student

total marks

class

for

Example

student_name = "Rahul"

marks = 95

Here:
 student_name and marks are identifiers.

Naming Conventions (Best Practice)

Use meaningful names:

total_marks

student_age

employee_salary

Avoid:

a1

abc123

3. Variables

Definition

A variable is a named memory location used to store data. In Python,


variables are created automatically when a value is assigned.

Syntax

variable_name = value

Example

name = "Amit"

age = 20

salary = 35000.50

Output

print(name)

print(age)

Output:

Amit

20

Characteristics of Variables
 No need to declare the data type.

 Data type is assigned automatically.

 Variable values can be changed during program execution.

Example:

x = 10

x = 25

The value of x changes from 10 to 25.

4. Literals (Constants)

Definition

A literal is a fixed value written directly in the program.

Types of Literals

(a) Numeric Literals

10

25

3.14

(b) String Literals

"Python"

'Hello'

(c) Boolean Literals

True

False

(d) Special Literal

None

Example

name = "Python"

age = 20

pi = 3.14
Here:

 "Python"

 20

 3.14

are literals.

5. Operators

Definition

Operators are symbols used to perform operations on variables and values.

Types of Operators

(a) Arithmetic Operators

Operator Meaning Example

+ Addition 10 + 5

- Subtraction 10 - 5

* Multiplication 10 * 5

/ Division 10 / 5

% Modulus 10 % 3

// Floor Division 10 // 3

** Exponent 2 ** 3

Example

a = 10

b=3

print(a + b)

print(a % b)

Output

13

1
(b) Comparison Operators

Operator Meaning

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Example

a = 10

b = 20

print(a < b)

Output

True

(c) Assignment Operators

+=

-=

*=

/=

%=

Example

x = 10

x += 5

print(x)
Output

15

(d) Logical Operators

and

or

not

Example

age = 20

print(age > 18 and age < 60)

Output

True

(e) Membership Operators

in

not in

in Operator

The in operator returns True if the specified value is found in the sequence;
otherwise, it returns False.

Syntax

value in sequence

Example 1: String

print("P" in "Python")

Output

True

Explanation:
The character "P" exists in the string "Python", so the result is True.

Example 2: List
numbers = [10, 20, 30]

print(20 in numbers)

Output

True

Since 20 is present in the list, the result is True.

(f) Identity Operators

is

is not

is Operator

The is operator returns True if both variables refer to the same object in
memory.

Syntax

object1 is object2

Example

a = [1, 2]

b=a

print(a is b)

Output

True

Explanation:

 b = a means both a and b refer to the same list object.

 Therefore, a is b returns True.

Another Example

x = [1, 2]
y = [1, 2]

print(x is y)

Output

False

Explanation:

 Although x and y have the same values, they are different objects in
memory.

 Therefore, x is y is False.

is not Operator

The is not operator returns True if two variables refer to different objects in
memory.

Syntax

object1 is not object2

Example

x = [1, 2]

y = [1, 2]

print(x is not y)

Output

True

Explanation:

 x and y are stored at different memory locations.

 Hence, x is not y returns True.

6. Delimiters (Separators)

Definition

Delimiters are symbols that separate different parts of a Python program.

Common Delimiters
Delimiter Purpose

() Function call, grouping expressions

[] Lists, indexing

{} Dictionaries, sets

, Separate values

: Start a code block (if, for, while, def, etc.)

. Access object attributes and methods

; Separate multiple statements on one line (rarely used)

''/"" Define string literals

Scope and Lifetime of Variables


What is Scope?

Scope is the area of a program where a variable can be accessed.

Python mainly has the following scopes:

1. Local Scope

2. Global Scope

A) Local Variable

A variable created inside a function is called a local variable.

def greet():

message = "Hello"

print(message)

greet()

Output

Hello

Trying to access message outside the function gives an error.

print(message)

Output
NameError: name 'message' is not defined

B) Global Variable

A variable declared outside all functions is called a global variable.

name = "Alice"

def display():

print(name)

display()

print(name)

Output

Alice

Alice

The global variable can be accessed throughout the program.

Lifetime of Variables

Lifetime means how long a variable exists in memory.

Local Variable

 Created when the function starts.

 Destroyed when the function ends.

def test():

x = 20

print(x)

test()

After the function finishes, x no longer exists.


Global Variable

 Created when the program starts.

 Exists until the program ends.

y = 100

print(y)

Conditional Statements
Conditional statements help the program make decisions.

A) if Statement

Syntax

if condition:

statement

Example

age = 20

if age >= 18:

print("Eligible to vote")

Output

Eligible to vote

B) if-else Statement

Used when there are two possible outcomes.

Syntax

if condition:

statements

else:
statements

Example

num = 7

if num % 2 == 0:

print("Even")

else:

print("Odd")

Output

Odd

C) if-elif-else Statement

Used when checking multiple conditions.

Example

marks = 75

if marks >= 90:

print("Grade A")

elif marks >= 70:

print("Grade B")

elif marks >= 50:

print("Grade C")

else:

print("Fail")

Output

Grade B

3. Concept of Indentation
Python uses indentation (spaces or tabs) to define blocks of code.

Usually 4 spaces are used.

Correct:

if 5 > 2:

print("Five is greater")

Incorrect:

if 5 > 2:

print("Five is greater")

Output

IndentationError

4. Switch Statement in Python

Python does not have a traditional switch statement like C, C++, or Java.

Instead, you can use:

A) if-elif-else

day = 2

if day == 1:

print("Monday")

elif day == 2:

print("Tuesday")

else:

print("Invalid")

B) match-case

day = 2

match day:
case 1:

print("Monday")

case 2:

print("Tuesday")

case _:

print("Invalid")

Output

Tuesday

Looping Statements
Loops repeat a block of code.

Python has two main loops:

 for

 while

A) for Loop

Used when the number of iterations is known.

Syntax

for variable in sequence:

statements

Example

for i in range(5):

print(i)

Output

3
4

Example

for letter in "Python":

print(letter)

Output

B) while Loop

Runs as long as the condition is True.

Syntax

while condition:

statements

Example

i=1

while i <= 5:

print(i)

i += 1

Output

3
4

6. Nested Loops

A loop inside another loop is called a nested loop.

Example

for i in range(3):

for j in range(2):

print(i, j)

Output

00

01

10

11

20

21

Jumping Statements
Jumping statements change the normal flow of a loop.

Python provides:

 break

 continue

 pass (placeholder statement)

Loop Control Statement: break


The break statement immediately exits the loop.

Example

for i in range(1, 6):


if i == 4:

break

print(i)

Output

The loop stops when i becomes 4.

Loop Control Statement: continue


The continue statement skips the current iteration and moves to the next one.

Example

for i in range(1, 6):

if i == 3:

continue

print(i)

Output

The number 3 is skipped.

Difference Between break and continue


Feature break continue

Purpose Stops the loop completely Skips only the current iteration

Loop Execution Ends immediately Continues with the next iteration

Example Output 1 2 3 1245


Feature break continue

Python Lists
A list is one of Python's most useful data structures. It allows you to store
multiple values in a single variable.

For example:

fruits = ["apple", "banana", "mango", "orange"]

Here, fruits is a list containing four elements.

Important characteristics of lists

Characteristics of Python Lists

1. Lists can contain different data types

data = [10, "Python", 3.14, True]

2. Lists can contain duplicate elements

numbers = [10, 20, 10, 30, 20]

3. Lists can be nested

matrix = [[1, 2], [3, 4], [5, 6]]

4. Lists support slicing

numbers = [1, 2, 3, 4, 5]

print(numbers[1:4])

# [2, 3, 4]

5. Lists can be used with the in and not in operators

fruits = ["apple", "mango"]

print("apple" in fruits) # True

print("banana" not in fruits) # True

6. Lists can be compared with other lists

a = [1, 2, 3]

b = [1, 2, 3]
print(a == b)

# True

7. Lists can be concatenated using +

list1 = [1, 2]

list2 = [3, 4]

result = list1 + list2

print(result)

# [1, 2, 3, 4]

8. Lists can be repeated using *

numbers = [1, 2]

print(numbers * 3)

# [1, 2, 1, 2, 1, 2]

9. Lists can be passed to functions

def display(items):

print(items)

fruits = ["apple", "banana"]

display(fruits)

1. Accessing Elements in a List

To access an element, use its index position inside square brackets [].

fruits = ["apple", "banana", "mango", "orange"]

print(fruits[0])

print(fruits[1])

print(fruits[2])
Output:

apple

banana

mango

Notice that the first element has index 0, not 1.

Index positions

For:

fruits = ["apple", "banana", "mango", "orange"]

The positions are:

Element Positive Index Negative Index

apple 0 -4

banana 1 -3

mango 2 -2

orange 3 -1

2. Index Position

Python uses zero-based indexing.

That means:

First element → index 0

Second element → index 1

Third element → index 2

Fourth element → index 3

Example:

names = ["Aman", "Riya", "Raj", "Neha"]

print(names[0]) # Aman

print(names[1]) # Riya

print(names[2]) # Raj
print(names[3]) # Neha

Negative indexing

Python also allows you to access elements from the end of a list.

names = ["Aman", "Riya", "Raj", "Neha"]

print(names[-1])

print(names[-2])

Output:

Neha

Raj

So:

-1 → last element

-2 → second-last element

-3 → third-last element

What happens if the index doesn't exist?

names = ["Aman", "Riya", "Raj"]

print(names[5])

This produces:

IndexError: list index out of range

Because there is no element at index 5.

3. Using Individual Values from a List

You can store an individual list element in another variable.

fruits = ["apple", "banana", "mango"]

favorite = fruits[2]
print(favorite)

Output:

mango

You can also perform operations on individual values.

names = ["Aman", "Riya", "Raj"]

message = "Hello " + names[0]

print(message)

Output:

Hello Aman

You can use methods on individual string values as well:

names = ["aman", "riya", "raj"]

print(names[0].title())

Output:

Aman

4. Changing Elements in a List

Lists are mutable, so you can change an element after creating the list.

Suppose:

colors = ["red", "blue", "green"]

We want to change "blue" to "yellow".

colors[1] = "yellow"

print(colors)

Output:

['red', 'yellow', 'green']


General syntax

list_name[index] = new_value

Example:

numbers = [10, 20, 30, 40]

numbers[2] = 100

print(numbers)

Output:

[10, 20, 100, 40]

5. Adding Elements to a List

There are several ways to add elements.

A. append()

The append() method adds one element at the end of the list.

fruits = ["apple", "banana"]

[Link]("mango")

print(fruits)

Output:

['apple', 'banana', 'mango']

Another example:

numbers = [1, 2, 3]

[Link](4)

[Link](5)
print(numbers)

Output:

[1, 2, 3, 4, 5]

B. insert()

insert() allows you to add an element at a specific position.

Syntax:

list_name.insert(index, value)

Example:

fruits = ["apple", "mango"]

[Link](1, "banana")

print(fruits)

Output:

['apple', 'banana', 'mango']

Here:

[Link](1, "banana")

means:

Put "banana" at index 1.

C. extend()

extend() adds multiple elements to an existing list.

fruits = ["apple", "banana"]

[Link](["mango", "orange"])

print(fruits)
Output:

['apple', 'banana', 'mango', 'orange']

append() vs extend()

This difference is very important.

numbers = [1, 2]

[Link]([3, 4])

print(numbers)

Output:

[1, 2, [3, 4]]

The entire list [3, 4] becomes one element.

But:

numbers = [1, 2]

[Link]([3, 4])

print(numbers)

Output:

[1, 2, 3, 4]

extend() adds the individual elements.

6. Removing Elements from a List

Python provides several ways to remove elements.

A. del

You can remove an element using its index.

fruits = ["apple", "banana", "mango"]


del fruits[1]

print(fruits)

Output:

['apple', 'mango']

You can also delete a range:

numbers = [1, 2, 3, 4, 5]

del numbers[1:4]

print(numbers)

Output:

[1, 5]

7. pop()

pop() removes an element and returns the removed value.

fruits = ["apple", "banana", "mango"]

removed = [Link]()

print(fruits)

print(removed)

Output:

['apple', 'banana']

mango

By default, pop() removes the last element.

You can also specify an index:

fruits = ["apple", "banana", "mango"]


removed = [Link](1)

print(fruits)

print(removed)

Output:

['apple', 'mango']

banana

8. remove()

remove() removes an element by its value.

fruits = ["apple", "banana", "mango"]

[Link]("banana")

print(fruits)

Output:

['apple', 'mango']

Important difference

del fruits[1]

removes by index.

[Link]("banana")

removes by value.

9. clear()

clear() removes everything from the list.

numbers = [1, 2, 3, 4]

[Link]()
print(numbers)

Output:

[]

The list still exists, but it is empty.

10. Organizing a List

Python provides methods to organize or arrange list elements.

The most common methods are:

 sort()

 sorted()

 reverse()

A. sort()

sort() sorts the list permanently.

cars = ["BMW", "Audi", "Toyota", "Honda"]

[Link]()

print(cars)

Output:

['Audi', 'BMW', 'Honda', 'Toyota']

By default, strings are sorted alphabetically.

Numbers

numbers = [5, 2, 9, 1, 7]

[Link]()
print(numbers)

Output:

[1, 2, 5, 7, 9]

Descending order

Use:

[Link](reverse=True)

print(numbers)

Output:

[9, 7, 5, 2, 1]

11. sorted()

sorted() returns a new sorted list without changing the original list.

numbers = [5, 2, 9, 1, 7]

new_numbers = sorted(numbers)

print(new_numbers)

print(numbers)

Output:

[1, 2, 5, 7, 9]

[5, 2, 9, 1, 7]

Difference between sort() and sorted()

[Link]()

changes the original list.

sorted(numbers)

creates a sorted version while keeping the original unchanged.


12. Reversing a List

The reverse() method reverses the order of elements.

numbers = [1, 2, 3, 4, 5]

[Link]()

print(numbers)

Output:

[5, 4, 3, 2, 1]

Important:

reverse() does not mean "sort from largest to smallest."

For descending numerical order, use:

[Link](reverse=True)

13. Loop Through an Entire List

A for loop is commonly used to process every element in a list.

fruits = ["apple", "banana", "mango"]

for a in fruits:

print(a)

Output:

apple

banana

mango

Python takes each element one by one and stores it temporarily in a.

You can perform operations on every element:

names = ["aman", "riya", "raj"]


for name in names:

print([Link]())

Output:

Aman

Riya

Raj

14. Avoiding Indentation Errors

Indentation is extremely important in Python.

Python uses indentation to determine which statements belong to a block of


code.

Correct:

fruits = ["apple", "banana", "mango"]

for fruit in fruits:

print(fruit)

The print() statement is indented, so Python knows it belongs to the for loop.

Incorrect:

fruits = ["apple", "banana", "mango"]

for fruit in fruits:

print(fruit)

This causes an:

IndentationError

Another example

Correct:

age = 20
if age >= 18:

print("You are an adult.")

Incorrect:

age = 20

if age >= 18:

print("You are an adult.")

Best practice

Use 4 spaces for each indentation level.

for number in numbers:

if number > 5:

print(number)

Here there are two levels:

for

if

print

15. Numerical Lists

A list can contain numbers.

numbers = [10, 20, 30, 40, 50]

You can perform mathematical operations using individual elements:

numbers = [10, 20, 30]

print(numbers[0] + numbers[1])

Output:

30

You can also use Python's built-in functions.

min()
Finds the smallest value.

numbers = [10, 5, 20, 3, 15]

print(min(numbers))

Output:

max()

Finds the largest value.

print(max(numbers))

Output:

20

sum()

Adds all the values.

print(sum(numbers))

Output:

53

16. Using range() to Create Numerical Lists

The range() function is very useful for creating sequences of numbers.

numbers = list(range(1, 6))

print(numbers)

Output:

[1, 2, 3, 4, 5]

Example

numbers = list(range(1, 11))

print(numbers)
Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(start, stop)

Remember that the stop value is not included.

list(range(1, 5))

gives:

[1, 2, 3, 4]

17. range() with a Step

You can specify how much the number should increase each time.

numbers = list(range(2, 11, 2))

print(numbers)

Output:

[2, 4, 6, 8, 10]

Here:

start = 2

stop = 11

step = 2

Another example:

numbers = list(range(10, 0, -2))

print(numbers)

Output:

[10, 8, 6, 4, 2]

18. Sublist

A sublist is a smaller portion of an existing list.


Python uses slicing to obtain a sublist.

Syntax:

list[start:stop]

The stop index is not included.

Example:

fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[1:4])

Output:

['banana', 'mango', 'orange']

Why?

Index: 0 1 2 3 4

apple banana mango orange grapes

↑ ↑

start stop

The elements from index 1 through 3 are selected.

19. Other List Slicing Examples

From the beginning

numbers = [1, 2, 3, 4, 5]

print(numbers[:3])

Output:

[1, 2, 3]

From a position to the end

print(numbers[2:])

Output:

[3, 4, 5]
Copying the entire list

print(numbers[:])

Output:

[1, 2, 3, 4, 5]

Using a step

numbers = [1, 2, 3, 4, 5, 6]

print(numbers[::2])

Output:

[1, 3, 5]

Reverse a list using slicing

numbers = [1, 2, 3, 4, 5]

print(numbers[::-1])

Dictionaries in Python
[Link]:
A dictionary is a data structure that stores information in key-value pairs.

Think of it like a real dictionary:

 Word → key

 Meaning → value

Creating a dictionary

student = {

"name": "Rahul",

"age": 20,

"course": "Python"

}
print(student)

Output:

{'name': 'Rahul', 'age': 20, 'course': 'Python'}

Here:

 "name" is a key and "Rahul" is its value.

 "age" is a key and 20 is its value.

 "course" is a key and "Python" is its value.

Accessing values

We use the key to access its value:

student = {

"name": "Rahul",

"age": 20

print(student["name"])

print(student["age"])

Output:

Rahul

20

Adding a new item

student = {

"name": "Rahul",

"age": 20

fdx

print(student)
Output:

{'name': 'Rahul', 'age': 20, 'city': 'Delhi'}

Changing a value

student = {

"name": "Rahul",

"age": 20

student["age"] = 21

print(student)

Output:

{'name': 'Rahul', 'age': 21}

Removing an item

student = {

"name": "Rahul",

"age": 20,

"city": "Delhi"

del student["city"]

print(student)

Output:

{'name': 'Rahul', 'age': 20}

Another useful method is pop():

[Link]("age")

print(student)
2. Working with Dictionaries
Python provides several useful dictionary methods.

keys()

Returns all keys:

student = {

"name": "Rahul",

"age": 20,

"course": "Python"

print([Link]())

values()

Returns all values:

print([Link]())

items()

Returns key-value pairs:

print([Link]())

Example output:

dict_items([('name', 'Rahul'), ('age', 20), ('course', 'Python')])

Checking whether a key exists

student = {

"name": "Rahul",

"age": 20

if "name" in student:

print("Name exists")
Output:

Name exists

3. Looping Through Dictionaries


A loop allows us to process every item in a dictionary.

Loop through keys

student = {

"name": "Rahul",

"age": 20,

"course": "Python"

for key in student:

print(key)

Output:

name

age

course

You can also write:

for key in [Link]():

print(key)

Loop through values

for value in [Link]():

print(value)

Output:

Rahul

20

Python
Loop through keys and values

The most common method is using items():

for key, value in [Link]():

print(key, ":", value)

Output:

name : Rahul

age : 20

course : Python

Another example

marks = {

"Math": 85,

"English": 78,

"Science": 92

for subject, mark in [Link]():

print(subject, "=", mark)

Output:

Math = 85

English = 78

Science = 92

4. Nesting in Python
Nesting means putting one data structure inside another.

For example:

 list inside a dictionary

 dictionary inside a dictionary


 dictionary inside a list

Dictionary inside a dictionary

students = {

"student1": {

"name": "Rahul",

"age": 20

},

"student2": {

"name": "Priya",

"age": 21

print(students)

Here, student1 and student2 each contain another dictionary.

Accessing nested values

print(students["student1"]["name"])

Output:

Rahul

And:

print(students["student2"]["age"])

Output:

21

List inside a dictionary

student = {

"name": "Rahul",

"subjects": ["Math", "English", "Science"]


}

print(student["subjects"])

Output:

['Math', 'English', 'Science']

To access one subject:

print(student["subjects"][0])

Output:

Math

Looping through nested dictionaries

students = {

"student1": {

"name": "Rahul",

"marks": 85

},

"student2": {

"name": "Priya",

"marks": 92

for student_id, student_info in [Link]():

print(student_id)

print("Name:", student_info["name"])

print("Marks:", student_info["marks"])

Output:

student1
Name: Rahul

Marks: 85

student2

Name: Priya

Marks: 92

5. print() Function
The print() function is used to display information on the screen.

Basic example

print("Hello, Python!")

Output:

Hello, Python!

Printing variables

name = "Rahul"

age = 20

print(name)

print(age)

Printing multiple values

name = "Rahul"

age = 20

print("Name:", name)

print("Age:", age)

Output:

Name: Rahul

Age: 20

Using f-strings
A very convenient way is an f-string:

name = "Rahul"

age = 20

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Rahul and I am 20 years old.

6. input() Function
The input() function allows the user to enter information while the program
is running.

name = input("Enter your name: ")

print("Hello", name)

If the user enters:

Rahul

Output:

Enter your name: Rahul

Hello Rahul

Important: input() returns a string

For example:

age = input("Enter your age: ")

print(type(age))

Even if the user enters 20, Python treats it as a string.

Output:

<class 'str'>

If you want an integer, use int():


age = int(input("Enter your age: "))

print(age + 1)

If the user enters 20:

21

Example: adding two numbers

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

result = num1 + num2

print("Sum:", result)

If the user enters 10 and 20:

Sum: 30

7. Comments in Python
Comments are notes written inside code to explain what the code does.

Python ignores comments when running the program.

A single-line comment starts with #.

# This program calculates the sum of two numbers

num1 = 10

num2 = 20

# Add the numbers

result = num1 + num2

print(result)
Comments are useful because they make code easier to understand.

Good comment

# Calculate the student's average marks

average = total / 5

Unnecessary comment

# Store 10 in x

x = 10

The second comment doesn't provide much useful information.

You might also like