0% found this document useful (0 votes)
15 views58 pages

History of Python Programming Language

Python is a widely used programming language created by Guido van Rossum in 1989, known for its simplicity and versatility. It has evolved through major versions: Python 1.x, 2.x, and 3.x, with Python 3.x being the current standard. Python is supported by the Python Software Foundation and is popular in various fields such as web development, data science, and automation.

Uploaded by

nallareddy2711
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)
15 views58 pages

History of Python Programming Language

Python is a widely used programming language created by Guido van Rossum in 1989, known for its simplicity and versatility. It has evolved through major versions: Python 1.x, 2.x, and 3.x, with Python 3.x being the current standard. Python is supported by the Python Software Foundation and is popular in various fields such as web development, data science, and automation.

Uploaded by

nallareddy2711
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

1(a). Write about the History of Python programming language.

Ans.
History of Python Programming Language
Python is one of the most popular and widely used programming languages in the world
today. It is known for its simplicity, readability, and versatility.
The history of Python dates back to the late 1980s, when it was first conceived by
Guido van Rossum.

1. Origin and Creation


 Creator: Guido van Rossum
 Country: Netherlands
 Year of Inception: December 1989
 First Release: February 1991

Guido van Rossum was working at CWI (Centrum Wiskunde & Informatica) in the Netherlands when he
began developing Python.
He wanted to create a language that was:

 Easy to learn and use


 Had clear and readable syntax
 Supported exception handling and dynamic typing
 Could handle system administration and scripting tasks

He started developing Python as a hobby project during his Christmas holidays in 1989.

2. Inspiration Behind Python


Python was inspired by two major programming languages:

1. ABC Language – A teaching and prototyping language developed at CWI.


o Python borrowed features like simplicity, readability, and exception handling from ABC.
2. C and Unix Shell – Python was designed to be powerful and flexible like C and the Unix shell scripting
languages.

The name “Python” was not inspired by the snake 🐍 — it came from Guido’s love of the British comedy series
“Monty Python’s Flying Circus.”
He wanted the language to be fun and not too serious.

3. Major Versions of Python


🔹 Python 1.x (1991 – 2000)

 First official release: Python 1.0 (February 1991)


 Key features:
o Basic data types (lists, strings, dictionaries)
o Functions and exception handling
o The module system for code reuse

Other releases:

 Python 1.2 (1994)


 Python 1.6 (2000)

🔹 Python 2.x (2000 – 2010)

 Released: October 16, 2000


 Major improvement: Improved support for Unicode, garbage collection, and list comprehensions.

Python 2 introduced many new features but also had some compatibility issues with Python 1.
For many years, Python 2 and 3 coexisted.

 Last version: Python 2.7 (released in 2010)


 End of official support: January 1, 2020

⚠️After this date, Python 2 was officially retired.

🔹 Python 3.x (2008 – Present)

 Released: December 3, 2008


 Key feature: Cleaned up and modernized the language — not backward compatible with Python 2.

Major improvements:

 Better Unicode support (all strings are Unicode by default)


 New syntax for print() function
 Advanced libraries and modules
 Type hints and improved memory management
 Better support for asynchronous programming (async and await)

Latest versions (as of 2025):

 Python 3.11 (2022)


 Python 3.12 (2023)
 Python 3.13 (2024)

Python 3 is now the standard version used worldwide.


4. Python Timeline Summary
Year Event

1989 Guido van Rossum begins working on Python project

1991 Python 1.0 released

2000 Python 2.0 released with many new features

2008 Python 3.0 released (not backward compatible with Python 2)

2010 Python 2.7 released

2020 Python 2 officially retired

2023–2024 Python 3.12 and 3.13 released with modern updates

5. Python’s Growth and Popularity


Over the years, Python has grown to become one of the most popular programming languages in the world.
It is widely used in:

 Web development (Django, Flask)


 Data science and AI (NumPy, Pandas, TensorFlow)
 Automation and scripting
 Machine learning
 Education and research

According to global surveys (like Stack Overflow and TIOBE Index), Python consistently ranks among the top
3 programming languages worldwide.

6. Organizations Supporting Python


 Python Software Foundation (PSF):
o A non-profit organization founded in 2001
o Responsible for promoting, protecting, and advancing the Python programming language

7. Summary
Aspect Details

Creator Guido van Rossum

Year of Creation 1989


Aspect Details

First Release 1991 (Python 1.0)

Latest Major Version Python 3.x

Developed At CWI (Netherlands)

Inspired By ABC, C, and Unix Shell

Organization Python Software Foundation (PSF)

Named After Monty Python’s Flying Circus

Conclusion

Python’s history shows a continuous effort to make programming simple, powerful, and accessible.
From its humble beginnings as a small project by Guido van Rossum, Python has evolved into a global, open-
source language that powers modern technologies such as AI, web development, data science, and
automation.

1(b). Write about the Identifiers in Python programming language.


Ans. Identifiers in Python
In Python, identifiers are names used to identify various programming elements such as variables, functions,
classes, modules, and other objects. They are essential because they help programmers reference data and code
elements throughout a program.

1. Definition

An identifier is simply a name given to an entity in a Python program.


For example:

name = "Alice" # 'name' is an identifier for a variable


def greet(): # 'greet' is an identifier for a function
print("Hello!")

In the above code, name and greet are both identifiers.

2. Rules for Naming Identifiers

Python follows specific rules for forming identifiers:

1. Allowed characters:
Identifiers can include letters (A–Z, a–z), digits (0–9), and underscores (_).
✅ Valid examples:

student_name
rollNumber1
_count

2. Cannot start with a digit:


Identifiers must not begin with a number.

❌ Invalid example:

2name = "John" # SyntaxError

3. Case-sensitive:
Python identifiers are case-sensitive.
This means Name, name, and NAME are three different identifiers.
4. Cannot use keywords:
Python reserved keywords (like if, class, return, for, etc.) cannot be used as identifiers.

❌ Invalid example:

class = "Hello" # Error: 'class' is a reserved keyword

5. No special symbols:
Special characters such as @, #, $, %, !, and spaces are not allowed.

❌ Invalid example:

user-name = "Tom" # Error: '-' not allowed

3. Naming Conventions (Best Practices)

While Python does not enforce strict naming conventions, it follows the PEP 8 style guide, which suggests:

 Variable and function names → lowercase with underscores


 total_price = 100
 def calculate_total():
 pass

 Class names → use CamelCase


 class StudentDetails:
 pass

 Constants → all uppercase letters


 MAX_LIMIT = 500

 Private variables or functions → prefix with an underscore


 _hidden_value = 10
4. Examples of Valid and Invalid Identifiers
Valid Identifiers Invalid Identifiers
x 2value

_value my-name

student1 @score

total_amount for (keyword)

Data_2025 total amount (space)

2(a). Describe about the Keywords in Python programming language.


Ans. Keywords in Python

In Python, keywords are special reserved words that have predefined meanings and purposes in the language.
They are used to define the syntax and structure of Python programs. Since these words are reserved, you
cannot use them as identifiers (like variable names, function names, or class names).

1. Definition

A keyword in Python is a word that is part of the language’s vocabulary and has a specific meaning or
function.

For example:

if age > 18:


print("You are an adult.")

Here, if and print are keywords that have special roles:

 if — used for conditional statements.


 print — used to output data to the console.

2. Characteristics of Keywords

1. Reserved Words:
Keywords are reserved by Python and cannot be used as names for variables, functions, or classes.
2. Case-Sensitive:
Python keywords are case-sensitive. For example, True is a keyword, but true is not.
3. Fixed Meaning:
Each keyword has a fixed purpose and cannot be redefined or altered.
4. Used in Program Structure:
They define the logical structure of the code — such as loops, conditions, functions, and exception
handling.
3. List of Python Keywords (Python 3.12 / 3.13)

Python has around 35 keywords (the number may vary slightly between versions).
You can check them by using the built-in keyword module:

import keyword
print([Link])

Common Python Keywords:

Category Keywords

Control Flow if, elif, else, for, while, break, continue, pass

Boolean & None True, False, None

Function & Class Definition def, return, lambda, class

Exception Handling try, except, finally, raise, assert

Import & Modules import, from, as

Variable Scope global, nonlocal

Logical Operators and, or, not, in, is

Other Keywords with, yield, del, async, await

2(b). Write about the Statements and Expressions in Python programming


language.
Ans.
Statements and Expressions in Python Programming Language

In Python, statements and expressions are the fundamental building blocks of any program.
They define how Python code is written, executed, and how it produces results.

1. Expression
An expression is a combination of values, variables, operators, and function calls that can be evaluated to
produce a result (a value).

✅ In simple terms:
An expression returns a value when it is executed.

Examples of Expressions
5 + 3 # Arithmetic expression → result: 8
x = 10 # Assignment with expression → x gets value 10
x * 2 + 5 # Evaluates to 25
len("Python") # Function call expression → result: 6

Here, each line contains an expression that produces a value.

Characteristics of Expressions

 They always produce a value.


 They can be part of a statement.
 Can include:
o Constants → 10, "Hello"
o Variables → x, y
o Operators → +, -, *, /
o Function calls → sum([1,2,3])

✅ Example:

a = 5
b = 3
c = a + b # Expression: a + b → produces value 8

2. Statement
A statement is a complete line of code that performs an action.
It could be assigning a value, making a decision, or looping through data.

✅ In simple terms:
A statement does something.

Types of Statements in Python

1. Assignment Statement
2. x = 10
3. name = "Alice"

4. Conditional Statement
5. if x > 5:
6. print("x is greater than 5")

7. Looping Statement
8. for i in range(3):
9. print(i)

10. Function Definition Statement


11. def greet():
12. print("Hello, World!")

13. Import Statement


14. import math

15. Pass / Break / Continue Statement


16. for i in range(5):
17. if i == 3:
18. break

Examples of Statements and Expressions


Code Type Explanation

x = 5 Statement Assigns a value (also contains the expression 5)

x + 2 Expression Produces a value 7 if x = 5

print(x) Statement Executes the print function

if x > 0: Statement Starts a conditional block

2 + 3 * 4 Expression Evaluates to 14

3. Relationship Between Statements and Expressions


 Every expression produces a value.
 A statement performs an action, and may contain expressions inside it.

✅ Example:

x = 5 + 3

 5 + 3 → Expression (evaluates to 8)
 x = 5 + 3 → Statement (assigns the value 8 to x)

So, expressions form part of statements.

4. Expression Statement
In Python, a statement that contains only an expression is called an expression statement.
It is executed to evaluate the expression and possibly produce an effect (like printing output).

Example:

print("Hello, Python!")

Here, print("Hello, Python!") is both an expression (evaluates the function call)


and a statement (executes an action).
5. Summary
Feature Expression Statement

A combination of values, variables, and operators that A complete instruction that performs
Definition
produces a value an action

Produces a Value? ✅ Yes ❌ Not always

Example a + b, len("Hi") x = 10, if x > 5:

Can Contain
❌ No ✅ Yes
Expressions?

Control program flow or perform


Purpose Compute or return a value
actions

6. Example Program Using Both


x = 10 # Statement
y = 5 # Statement

z = x + y # Statement containing an expression


print(z) # Expression statement (prints the value)

Output:

15

✅ In Short:

 Expression → produces a value.


 Statement → performs an action.
 Expressions can exist inside statements, but statements can’t exist inside expressions.

3(a). Describe about the Variables in Python programming language.


Ans.
Variables in Python Programming Language

In Python, variables are used to store data values that can be referenced and manipulated in a program.
They act as containers or names that hold information in the computer’s memory.

1. Definition
A variable is a name given to a memory location where data is stored.
In Python, you don’t need to declare the type of a variable before using it — the interpreter automatically
assigns the data type based on the value you store.

✅ Example:

x = 10
name = "Alice"

Here:

 x is a variable that stores an integer value 10


 name is a variable that stores a string value "Alice"

2. Features of Python Variables


1. Dynamic Typing:
You don’t need to specify the type of variable explicitly.
2. a = 10 # Integer
3. a = "Hello" # Now a becomes a String

4. No Need for Declaration:


Variables are created automatically when you assign a value.
5. Case-Sensitive:
Variable names are case-sensitive.
For example: Name, name, and NAME are three different variables.
6. Can Store Different Data Types:
Variables can hold integers, floats, strings, lists, dictionaries, etc.
7. age = 20
8. price = 99.5
9. city = "New York"

3. Rules for Naming Variables


Python has specific rules for creating valid variable names:

Rule Example

Must start with a letter (A–Z, a–z) or an underscore (_) _count, name

Cannot start with a digit ❌ 1name

Can contain letters, digits, and underscores user_name, value1

Cannot contain spaces or special characters ❌ user-name, first name

Case-sensitive Age and age are different

Cannot use Python keywords ❌ for, class, if


4. Assigning Values to Variables
Python allows single, multiple, and chained assignments.

(a) Single Assignment


x = 10
name = "John"
(b) Multiple Assignment

You can assign values to multiple variables in one line:

x, y, z = 10, 20, 30
(c) Chained Assignment

You can assign one value to multiple variables at the same time:

a = b = c = 50

5. Changing Variable Values


You can change the value of a variable anytime — Python will update it dynamically.

x = 10
x = "Ten"
print(x)

Output:

Ten

6. Variable Types
Variables in Python can store any data type.
Here are some examples:

# Integer
age = 25

# Float
price = 99.9

# String
name = "Alice"

# Boolean
is_active = True

# List
colors = ["red", "green", "blue"]
# Dictionary
student = {"name": "John", "age": 21}

7. Global and Local Variables


Local Variable:

Declared inside a function and can be used only within that function.

def greet():
message = "Hello" # Local variable
print(message)

greet()
# print(message) → Error (not accessible outside)
Global Variable:

Declared outside a function and can be accessed anywhere in the program.

name = "Python" # Global variable

def show():
print("Language:", name)

show()
print("Outside:", name)

8. Constants
Python doesn’t have true constants, but by convention, uppercase variable names are used for values that
shouldn’t change.

PI = 3.14159
MAX_USERS = 100

Even though Python allows you to change them, programmers treat them as read-only.

9. Deleting Variables
You can delete a variable using the del keyword.

x = 10
del x
# print(x) → Error: name 'x' is not defined

10. Summary Table


Concept Description Example

Definition A name used to store a value in memory x = 10

Dynamic Typing No need to declare type a = "Hi"

Case-Sensitive Name ≠ name —

Multiple Assignment Assign several values at once x, y = 5, 10

Chained Assignment Same value to multiple variables a = b = 100

Constant Convention Uppercase names PI = 3.14

Example Program
# Variable examples
name = "Alice"
age = 25
height = 5.6

print("Name:", name)
print("Age:", age)
print("Height:", height)

Output:

Name: Alice
Age: 25
Height: 5.6

✅ In Short

 A variable is a named memory location to store data.


 Python variables are dynamically typed.
 Variable names must follow naming rules.
 Variables can be local or global.
 Constants are written in uppercase by convention.

3(b). Write about the Operators in Python programming language.


Ans.
Operators in Python Programming Language

In Python, operators are special symbols or keywords used to perform operations on values and variables.
They allow you to perform mathematical calculations, compare values, and manipulate data efficiently.

For example:

x = 10
y = 5
print(x + y) # Output: 15

Here, + is an operator that adds two numbers.

1. Types of Operators in Python


Python provides several types of operators:

1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1️⃣ Arithmetic Operators


Used to perform basic mathematical operations.

Operator Description Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division (returns float) 10 / 5 2.0

// Floor Division 10 // 3 3

% Modulus (remainder) 10 % 3 1

** Exponentiation 2 ** 3 8

✅ Example:

a = 7
b = 3
print(a + b, a - b, a * b, a / b)

2️⃣ Relational (Comparison) Operators


Used to compare two values.
They return True or False (Boolean values).
Operator Description Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 5 > 3 True

< Less than 5 < 3 False

>= Greater than or equal to 5 >= 3 True

<= Less than or equal to 5 <= 5 True

✅ Example:

x = 10
y = 20
print(x > y) # False

3️⃣ Assignment Operators


Used to assign values to variables.

Operator Description Example Equivalent To

= Assign x = 5 —

+= Add and assign x += 3 x = x + 3

-= Subtract and assign x -= 2 x = x - 2

*= Multiply and assign x *= 2 x = x * 2

/= Divide and assign x /= 2 x = x / 2

//= Floor divide and assign x //= 2 x = x // 2

%= Modulus and assign x %= 2 x = x % 2

**= Power and assign x **= 2 x = x ** 2

✅ Example:

x = 10
x += 5
print(x) # Output: 15

4️⃣ Logical Operators


Used to combine conditional statements.
Operator Description Example Result

and Returns True if both conditions are True (x > 5 and y < 10) True

or Returns True if at least one condition is True (x > 5 or y < 5) True

not Reverses the result not(x > 5) False

✅ Example:

x = 7
print(x > 5 and x < 10) # True

5️⃣ Bitwise Operators


Used to perform operations on binary numbers (bits).

Operator Description Example Result

& AND 5 & 3 1

` ` OR `5

^ XOR 5 ^ 3 6

~ NOT ~5 -6

<< Left Shift 5 << 1 10

>> Right Shift 5 >> 1 2

✅ Explanation:

5 = 101 (binary)
3 = 011 (binary)
5 & 3 = 001 → 1

6️⃣ Membership Operators


Used to test membership in sequences like strings, lists, or tuples.

Operator Description Example Result

in Returns True if value is present "a" in "apple" True

not in Returns True if value is not present "b" not in "apple" True

✅ Example:

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


print("apple" in fruits) # True
print("mango" not in fruits) # True

7️⃣ Identity Operators


Used to compare memory locations of two objects.

Operator Description Example Result

is Returns True if both refer to the same object x is y True / False

is not Returns True if they are not the same object x is not y True / False

✅ Example:

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

print(x is y) # True (same object)


print(x is z) # False (different objects with same data)

8. Operator Precedence (Priority Order)


Python follows a specific order of evaluation when multiple operators appear in an expression.

Precedence Level Operators Description

1 () Parentheses

2 ** Exponentiation

3 *, /, //, % Multiplication, Division, Floor Division, Modulus

4 +, - Addition, Subtraction

5 >, <, >=, <=, ==, != Comparisons

6 and, or, not Logical operations

✅ Example:

result = 10 + 5 * 2
print(result) # Output: 20 (because * has higher precedence than +)

9. Summary Table
Type of Operator Used For Example

Arithmetic Mathematical calculations a + b

Relational Compare values a > b

Assignment Assign values x += 5

Logical Combine conditions a and b

Bitwise Bit-level operations a & b

Membership Check for membership "a" in s

Identity Compare memory locations x is y

Example Program
x = 10
y = 5

print("Addition:", x + y)
print("Greater:", x > y)
print("AND:", x > 0 and y > 0)
print("Membership:", 10 in [5, 10, 15])
print("Identity:", x is y)

Output:

Addition: 15
Greater: True
AND: True
Membership: True
Identity: False

✅ In Short

 Operators are symbols that perform operations on data.


 Python supports 7 main types of operators.
 Operators are essential for mathematical, logical, and comparison operations in programming.
 The order of precedence determines how expressions are evaluated.

4(a). Write about the Precedence and Associativity in Python programming


language.
Ans.
Precedence and Associativity in Python Programming Language

In Python, precedence and associativity determine the order in which operators are evaluated in an
expression — especially when multiple operators appear together.
They ensure that expressions are computed accurately and predictably.
1. Operator Precedence
Operator precedence defines which operator is evaluated first when an expression has more than one
operator.

✅ Example:

result = 10 + 5 * 2
print(result)

Output: 20

👉 Here, multiplication (*) has higher precedence than addition (+),


so Python evaluates 5 * 2 = 10 first, then 10 + 10 = 20.

Table: Operator Precedence in Python (Highest to Lowest)


Precedence Level Operator(s) Description / Example

1 () Parentheses (highest precedence)

2 ** Exponentiation (2 ** 3 = 8)

3 +x, -x, ~x Unary plus, minus, bitwise NOT

4 *, /, //, % Multiplication, Division, Floor Division, Modulus

5 +, - Addition, Subtraction

6 <<, >> Bitwise shift operators

7 & Bitwise AND

8 ^, ` `

9 ==, !=, >, <, >=, <= Comparison operators

10 not Logical NOT

11 and Logical AND

12 or Logical OR

13 =, +=, -=, *=, /=, //=, %= Assignment operators (lowest precedence)

✅ Example 1:

x = 5 + 3 * 2
# Multiplication has higher precedence
print(x)
Output: 11

✅ Example 2:

x = (5 + 3) * 2
# Parentheses override precedence
print(x)

Output: 16

2. Operator Associativity
When two operators of the same precedence appear in an expression,
associativity decides the direction (left or right) of evaluation.

 Left-to-right associativity → most operators


 Right-to-left associativity → some like ** and assignment (=)

Table: Operator Associativity


Operators Associativity Example Result

+, -, *, /, %, // Left to Right 10 - 4 + 2 8

<, >, <=, >=, ==, != Left to Right 3 < 4 < 5 True

and, or, not Left to Right True and False or True True

=, +=, -=, **= Right to Left x = y = 5 x = 5, y = 5

** Right to Left 2 ** 3 ** 2 512

✅ Example of Right-to-Left Associativity:

x = 2 ** 3 ** 2
# Evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512
print(x)

Output: 512

✅ Example of Left-to-Right Associativity:

x = 10 - 5 + 2
# Evaluated as (10 - 5) + 2 = 7
print(x)

Output: 7
3. Combining Precedence and Associativity
Both precedence and associativity work together to determine execution order.

Example:

result = 10 + 5 * 2 ** 3
print(result)

Step-by-step:

1. ** → Highest precedence → 2 ** 3 = 8
2. * → Next → 5 * 8 = 40
3. + → Last → 10 + 40 = 50
✅ Final Output: 50

4. Importance of Precedence and Associativity


 Ensures accurate evaluation of complex expressions.
 Reduces ambiguity in execution.
 Use parentheses () to make expressions clear and readable.

5. Summary
Concept Description Example

Precedence Determines which operator executes first 2 + 3 * 4 → 14

Associativity Determines order when operators have same precedence 2 ** 3 ** 2 → 512

Parentheses Used to change normal precedence (2 + 3) * 4 → 20

✅ In Short

 Precedence decides which operation happens first.


 Associativity decides in which direction (left or right) operations of the same precedence are performed.
 Parentheses () can be used to override normal precedence rules.

Example Program:

a = 10
b = 5
c = 2
result = a + b * c ** 2
print(result)

Output:
a + (b * (c ** 2)) = 10 + (5 * 4) = 30

4(b). Write about the Data types in Python programming language.


Ans.
Data Types in Python Programming Language

In Python, data types define the type of value a variable holds and the operations that can be performed on it.
Since Python is a dynamically typed language, you don’t need to declare the data type of a variable — it is
automatically determined when you assign a value.

✅ Example:

x = 10 # Integer
name = "Alice" # String
price = 99.5 # Float

1. Classification of Data Types


Python’s standard data types are divided into the following main categories:

Category Data Types

Numeric Types int, float, complex

Sequence Types str, list, tuple, range

Mapping Type dict

Set Types set, frozenset

Boolean Type bool

Binary Types bytes, bytearray, memoryview

None Type NoneType

2. Numeric Data Types


Used for storing numbers.

(a) int (Integer)

Stores whole numbers (positive, negative, or zero).


a = 10
b = -25
print(type(a)) # <class 'int'>
(b) float (Floating-point)

Stores numbers with decimal points.

price = 99.99
pi = 3.14159
print(type(price)) # <class 'float'>
(c) complex

Used for complex numbers (a + bj form).

z = 3 + 5j
print(type(z)) # <class 'complex'>
print([Link], [Link]) # 3.0 5.0

3. Sequence Data Types


These are ordered collections of elements.

(a) str (String)

A sequence of Unicode characters enclosed in quotes.

name = "Python"
print(type(name)) # <class 'str'>

Strings are immutable (cannot be changed after creation).

(b) list

An ordered, mutable collection of items enclosed in square brackets [].

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


print(fruits[0]) # apple
fruits[1] = "mango" # Lists are mutable
print(fruits)
(c) tuple

An ordered, immutable collection of elements enclosed in parentheses ().

colors = ("red", "green", "blue")


print(colors[1]) # green
# colors[0] = "black" → Error (immutable)
(d) range

Represents a sequence of numbers, often used in loops.

r = range(1, 6)
print(list(r)) # [1, 2, 3, 4, 5]
4. Mapping Data Type
dict (Dictionary)

Stores key–value pairs in an unordered manner.

student = {"name": "Alice", "age": 20, "grade": "A"}


print(student["name"]) # Alice
print(type(student)) # <class 'dict'>

Dictionaries are mutable and allow unique keys.

5. Set Data Types


Used to store unordered collections of unique items.

(a) set
s = {1, 2, 3, 3, 4}
print(s) # {1, 2, 3, 4}
(b) frozenset

An immutable version of a set.

fs = frozenset([1, 2, 3])
# [Link](4) → Error (cannot modify)

6. Boolean Data Type


bool

Stores either True or False.


Usually the result of a comparison or logical operation.

x = 10
y = 5
print(x > y) # True
print(type(True)) # <class 'bool'>

7. Binary Data Types


Used to store binary data like images or files.

Type Description
bytes Immutable sequence of bytes
Type Description

bytearray Mutable sequence of bytes

memoryview Provides a view of binary data without copying it

✅ Example:

b = bytes([65, 66, 67])


print(b) # b'ABC'

8. None Data Type


NoneType

Represents the absence of a value or a null variable.

x = None
print(type(x)) # <class 'NoneType'>

Used to indicate that a variable or function has no value assigned.

9. Type Conversion
Python allows type casting between compatible data types.

(a) Implicit Conversion (Automatic)

Python automatically converts smaller data types to larger ones.

x = 10 # int
y = 2.5 # float
z = x + y # int + float → float
print(z) # 12.5
(b) Explicit Conversion (Manual)

You can manually convert data types using built-in functions like:
int(), float(), str(), list(), tuple(), set(), etc.

x = "100"
y = int(x)
print(y + 50) # 150

10. Summary Table


Data Type Description Example

int Integer numbers 10

float Decimal numbers 12.5

complex Complex numbers 3 + 2j

str String (text) "Python"

list Ordered, mutable collection [1, 2, 3]

tuple Ordered, immutable collection (1, 2, 3)

dict Key-value pairs {"name":"Tom"}

set Unordered, unique elements {1, 2, 3}

bool Boolean values True, False

NoneType Represents null value None

11. Example Program


a = 10
b = 3.14
c = "Python"
d = [1, 2, 3]
e = {"name": "Alice", "age": 20}

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>

✅ In Short

 Data types specify the kind of data stored in variables.


 Python supports numeric, sequence, mapping, set, and boolean types.
 Data types can be converted using type casting.
 Being dynamically typed, Python automatically assigns types at runtime.
5(a). Describe about the Loop Statements in Python programming language.
Ans.
In Python, loop statements are used to repeatedly execute a block of code as long as a specified condition is
true or for a fixed number of iterations. Loops help reduce code repetition and make programs more efficient
and readable.

Python provides two main types of loop statements:

1. for Loop

 The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range).
 It executes a block of code for each item in the sequence.

Syntax:
for variable in sequence:
# loop body
Example:
for i in range(5):
print("Hello, Python!")

Output:

Hello, Python!
Hello, Python!
Hello, Python!
Hello, Python!
Hello, Python!

✅ Explanation:

 range(5) generates numbers from 0 to 4.


 The loop executes 5 times, printing the message each time.

2. while Loop

 The while loop executes a block of code as long as a condition is true.


 It is useful when the number of iterations is not known in advance.

Syntax:
while condition:
# loop body
Example:
count = 1
while count <= 5:
print("Count is:", count)
count += 1

Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

✅ Explanation:

 The loop continues as long as count <= 5 is True.


 The value of count is increased each time to avoid an infinite loop.

Loop Control Statements

Python provides special statements to control loop execution:

Statement Description

break Terminates the loop completely.

continue Skips the current iteration and moves to the next one.

pass Does nothing; used as a placeholder.

Example using break and continue:


for i in range(1, 6):
if i == 3:
continue # skips when i = 3
if i == 5:
break # stops loop when i = 5
print(i)

Output:

1
2
4

Summary
Type Used for Example

for loop Iterating over a sequence for i in range(5):

while loop Repeating while a condition is true while x < 10:

5(b). Write about the Conditional Statements in Python programming


language.
Ans.
In Python, conditional statements are used to make decisions in a program — that is, to execute certain
blocks of code only if specific conditions are true. They help control the flow of a program based on different
situations or inputs.
🧠 Types of Conditional Statements in Python
Python provides the following types of conditional statements:

1. if statement
2. if…else statement
3. if…elif…else statement
4. Nested if statements

1. if Statement

The simplest form of a decision-making statement.


It executes a block of code only if the condition is true.

Syntax:
if condition:
# code to execute if condition is true
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")

Output:

You are eligible to vote.

✅ Explanation:

 The condition age >= 18 evaluates to True, so the message is printed.

2. if…else Statement

Used when you want to perform one action if the condition is true, and another action if it is false.

Syntax:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
Example:
num = 5
if num % 2 == 0:
print("Even number")
else:
print("Odd number")

Output:
Odd number

✅ Explanation:

 Since 5 % 2 != 0, the condition is false, and the else block executes.

3. if…elif…else Statement

Used when you have multiple conditions to check.


Python evaluates conditions from top to bottom and executes the block of the first true condition.

Syntax:
if condition1:
# code for condition1
elif condition2:
# code for condition2
else:
# code if all conditions are false
Example:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")

Output:

Grade: B

✅ Explanation:

 The program checks each condition in order and executes the first one that is true.

4. Nested if Statement

You can place one if statement inside another to check multiple levels of conditions.

Syntax:
if condition1:
if condition2:
# code to execute if both conditions are true
Example:
num = 10
if num > 0:
if num % 2 == 0:
print("Positive even number")

Output:
Positive even number

🔹 Notes on Conditional Statements

 Conditions usually involve comparison operators (==, !=, <, >, <=, >=) or logical operators (and, or,
not).
 Indentation is very important in Python — it defines the blocks of code to be executed.
 You can use the pass statement when no action is needed inside a conditional block.

Example using pass:


x = 10
if x > 0:
pass # placeholder for future code
else:
print("Negative number")

✅ Summary Table
Statement Type Description Example

if Executes code if condition is true if x > 0:

if…else Executes one block if true, another if false if x > 0: ... else: ...

if…elif…else Checks multiple conditions if x > 0: ... elif x == 0: ... else: ...

Nested if One if inside another if x > 0: if y > 0:

6(a). Describe about the Functions in Python programming language.


Ans.
Functions in Python

A function in Python is a block of organized, reusable code that performs a specific task. Functions help make
code more modular, easier to read, and maintainable.

1. Why Use Functions?

Functions are used to:

 Avoid repetition of code


 Break a large program into smaller, manageable parts
 Improve code readability and reusability
 Simplify debugging and testing

2. Defining a Function

In Python, a function is defined using the def keyword.


Syntax:

def function_name(parameters):
"""optional docstring"""
# function body
statement(s)
return value

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

# Calling the function


sum_value = add_numbers(5, 3)
print("Sum:", sum_value)

Output:

Sum: 8

4. Function Components

 Function Name: A unique name that identifies the function (e.g., add_numbers).
 Parameters (Arguments): Values passed into the function (e.g., a and b).
 Docstring: Optional documentation string describing what the function does.
 Body: Contains statements that perform operations.
 Return Statement: Sends a value back to the caller.

5. Types of Functions

1. Built-in Functions – Provided by Python (e.g., len(), print(), max())


2. User-defined Functions – Created by programmers using def
3. Lambda Functions – Small anonymous functions created with the lambda keyword

6. Example of a Lambda Function


square = lambda x: x * x
print(square(4))

Output:

16

7. Function Arguments

Python supports several types of arguments:

 Positional Arguments
 Keyword Arguments
 Default Arguments
 Variable-length Arguments (*args and **kwargs)

Example:

def greet(name, message="Hello"):


print(message, name)

greet("Alice") # Uses default message


greet("Bob", "Good Morning")

Output:

Hello Alice
Good Morning Bob

8. Returning Multiple Values

A function can return more than one value using tuples:

def calc(a, b):


return a + b, a - b

add, sub = calc(10, 5)


print("Addition:", add)
print("Subtraction:", sub)

Output:

Addition: 15
Subtraction: 5

✅ In summary:
Functions in Python make your code modular, reusable, and easier to understand. They are one of the most
essential building blocks of Python programming.

6(b). Write about the Strings in Python programming language.


Ans.

Strings in Python
A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """).
Strings are one of the most commonly used data types in Python.

1. Creating Strings

You can create strings in several ways:


# Using single quotes
str1 = 'Hello'

# Using double quotes


str2 = "Python"

# Using triple quotes for multi-line strings


str3 = '''This is
a multi-line
string.'''

print(str1)
print(str2)
print(str3)

2. Accessing String Characters

Strings are indexed — the first character has index 0.

text = "Python"
print(text[0]) # P
print(text[3]) # h

You can also use negative indexing (from the end):

print(text[-1]) # n
print(text[-3]) # h

3. String Slicing

You can extract parts of a string using slicing syntax:

text = "Programming"
print(text[0:6]) # Progra (characters from index 0 to 5)
print(text[3:]) # gramming (from index 3 to end)
print(text[:5]) # Progr (from start to index 4)
print(text[-6:-1]) # ammin

4. String Concatenation and Repetition


str1 = "Hello"
str2 = "World"

# Concatenation
result = str1 + " " + str2
print(result) # Hello World

# Repetition
print(str1 * 3) # HelloHelloHello

5. String Methods

Python provides many built-in string methods.


Method Description Example

upper() Converts to uppercase "hello".upper() → 'HELLO'

lower() Converts to lowercase "HELLO".lower() → 'hello'

title() Capitalizes first letter of each word "python language".title()

strip() Removes whitespace " hi ".strip() → 'hi'

replace(old, new) Replaces substring "apple".replace("a","A")

split() Splits string into list "a,b,c".split(",")

join() Joins list elements ",".join(['a','b','c'])

find() Returns index of substring "hello".find("e") → 1

count() Counts occurrences "banana".count("a") → 3

6. String Formatting

You can format strings in different ways:

(a) Using f-strings (Python 3.6+)


name = "Alice"
age = 20
print(f"My name is {name} and I am {age} years old.")
(b) Using format() method
print("My name is {} and I am {} years old.".format("Alice", 20))
(c) Using % operator
print("My name is %s and I am %d years old." % ("Alice", 20))

7. Escape Characters

Escape characters are used to include special characters inside strings.

Escape Sequence Description

\' Single quote

\" Double quote

\\ Backslash

\n New line

\t Tab

Example:

print("Hello\nWorld")
print("She said, \"Python is fun!\"")
Output:

Hello
World
She said, "Python is fun!"

8. Strings Are Immutable

In Python, strings cannot be changed after creation.

text = "Hello"
# text[0] = "J" # ❌ Error: Strings are immutable
new_text = "J" + text[1:] # ✅ Correct way
print(new_text) # Jello

✅ In summary:

 A string is a sequence of characters.


 Strings are immutable.
 Python provides many built-in methods for string manipulation.
 Strings can be formatted, sliced, and combined easily.

7(a). Write about the Lists in Python programming language.


Ans.

Lists in Python
A list in Python is a collection of ordered, mutable (changeable) items. Lists are one of the most powerful
and commonly used data types in Python because they can store different types of data (integers, strings,
floats, etc.) in a single container.

1. Creating a List

Lists are created using square brackets [ ], and elements are separated by commas.

Example:

# Creating lists
list1 = [1, 2, 3, 4, 5]
list2 = ["apple", "banana", "cherry"]
list3 = [1, "hello", 3.5, True]
print(list1)
print(list2)
print(list3)
2. Accessing List Elements

Lists are indexed, starting from 0.

Example:

fruits = ["apple", "banana", "cherry", "date"]


print(fruits[0]) # apple
print(fruits[2]) # cherry

You can also use negative indexing (from the end):

print(fruits[-1]) # date
print(fruits[-2]) # cherry

3. List Slicing

You can extract parts of a list using slicing.

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


print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[3:]) # [40, 50, 60]
print(numbers[-3:]) # [40, 50, 60]

4. Modifying Lists

Lists are mutable, meaning their elements can be changed after creation.

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


colors[1] = "yellow"
print(colors) # ['red', 'yellow', 'blue']

You can also add or remove elements using various methods.

5. Common List Methods


Method Description Example

append(x) Adds an item at the end [Link](5)

insert(i, x) Inserts item at index i [Link](2, "hi")

remove(x) Removes first occurrence of value [Link]("apple")

pop(i) Removes item at index i (default last) [Link]()

clear() Removes all elements [Link]()

sort() Sorts the list [Link]()

reverse() Reverses the list [Link]()

count(x) Counts occurrences of x [Link](2)


Method Description Example

index(x) Returns index of x [Link]("apple")

copy() Returns a shallow copy [Link]()

6. Adding and Removing Elements


fruits = ["apple", "banana"]
[Link]("cherry")
print(fruits) # ['apple', 'banana', 'cherry']

[Link](1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']

[Link]("banana")
print(fruits) # ['apple', 'orange', 'cherry']

[Link]()
print(fruits) # ['apple', 'orange']

7. Iterating Through a List

You can use a for loop to go through all items in a list.

numbers = [1, 2, 3, 4, 5]
for n in numbers:
print(n)

8. Nested Lists (Lists within Lists)

Lists can contain other lists.

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


print(matrix[1]) # [4, 5, 6]
print(matrix[0][2]) # 3

9. List Comprehension

A concise way to create lists using a single line of code.

squares = [x**2 for x in range(1, 6)]


print(squares) # [1, 4, 9, 16, 25]

10. Combining and Repeating Lists


list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Concatenation
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]
# Repetition
print(list1 * 2) # [1, 2, 3, 1, 2, 3]

✅ In summary:

 A List is an ordered, mutable, and versatile data structure in Python.


 It can store multiple and mixed data types.
 Lists support a wide range of built-in methods for manipulation.
 They are widely used for storing collections of data.

7(b). How to Create dictionary and Access the dictionary in Python


programming language.
Ans.

Dictionaries in Python
A dictionary in Python is a collection of key–value pairs.
Each key is unique, and it is used to access its corresponding value.
Dictionaries are mutable (can be changed) and unordered (in Python 3.7+, they preserve insertion order by
default).

1. Creating a Dictionary

Dictionaries are created using curly braces {} with key–value pairs, separated by a colon :.

Example 1 – Basic Dictionary:

student = {
"name": "Alice",
"age": 20,
"course": "Computer Science"
}
print(student)

Output:

{'name': 'Alice', 'age': 20, 'course': 'Computer Science'}

Example 2 – Using the dict() Constructor:

person = dict(name="Bob", age=25, city="New York")


print(person)

Output:

{'name': 'Bob', 'age': 25, 'city': 'New York'}


2. Accessing Dictionary Values

You can access dictionary values using keys.

student = {"name": "Alice", "age": 20, "course": "Computer Science"}

print(student["name"]) # Access using key → Alice


print([Link]("age")) # Access using get() → 20

If you try to access a non-existent key using student["key"], it raises an error.


Using .get() returns None instead of an error.

3. Adding and Modifying Elements

You can add a new key–value pair or update an existing one.

student["grade"] = "A" # Add new item


student["age"] = 21 # Update existing value
print(student)

Output:

{'name': 'Alice', 'age': 21, 'course': 'Computer Science', 'grade': 'A'}

4. Removing Elements
Method Description Example

pop(key) Removes item with specified key [Link]("age")

popitem() Removes the last inserted item [Link]()

del Deletes item by key del student["course"]

clear() Removes all items [Link]()

Example:

student = {"name": "Alice", "age": 21, "course": "CS"}


[Link]("age")
print(student)

Output:

{'name': 'Alice', 'course': 'CS'}

5. Accessing Keys, Values, and Items

You can access all keys, values, or key–value pairs using built-in methods.
student = {"name": "Alice", "age": 20, "course": "CS"}

print([Link]()) # dict_keys(['name', 'age', 'course'])


print([Link]()) # dict_values(['Alice', 20, 'CS'])
print([Link]()) # dict_items([('name', 'Alice'), ('age', 20), ('course', 'CS')])

6. Looping Through a Dictionary

You can iterate through keys, values, or both.

student = {"name": "Alice", "age": 20, "course": "CS"}

for key in student:


print(key, ":", student[key])

Output:

name : Alice
age : 20
course : CS

7. Nested Dictionaries

A dictionary can contain another dictionary (useful for structured data).

students = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}

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

✅ In summary:

 A dictionary stores data as key–value pairs.


 Keys must be unique and immutable (like strings or numbers).
 Dictionaries are mutable (can be modified).
 You can create, access, update, and loop through dictionary data easily.

8(a). Write about the Tuples and Sets in Python programming language.
Ans.

Tuples and Sets in Python


In Python, tuples and sets are two important data types used to store collections of items.
They differ mainly in mutability and ordering.
🟢 1. Tuples in Python
Definition:

A tuple is an ordered, immutable (unchangeable) collection of elements.


Tuples are similar to lists, but once created, their elements cannot be changed.

1.1 Creating a Tuple

Tuples are created using parentheses ( ).

# Creating tuples
tuple1 = (1, 2, 3, 4)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (1, "hello", 3.5, True)
print(tuple1)
print(tuple2)
print(tuple3)

If there is only one element, include a comma after it:

single = (10,)
print(type(single)) # <class 'tuple'>

1.2 Accessing Tuple Elements

You can access elements using indexing or slicing, just like lists.

numbers = (10, 20, 30, 40, 50)


print(numbers[0]) # 10
print(numbers[-1]) # 50
print(numbers[1:4]) # (20, 30, 40)

1.3 Immutability of Tuples

Tuples cannot be modified after creation.

fruits = ("apple", "banana", "cherry")


# fruits[0] = "orange" ❌ Error: Tuples are immutable

However, you can convert a tuple into a list, modify it, and then convert it back.

fruits = ("apple", "banana", "cherry")


temp = list(fruits)
[Link]("orange")
fruits = tuple(temp)
print(fruits)

1.4 Tuple Operations


t1 = (1, 2, 3)
t2 = (4, 5)
# Concatenation
print(t1 + t2) # (1, 2, 3, 4, 5)

# Repetition
print(t1 * 2) # (1, 2, 3, 1, 2, 3)

# Membership
print(2 in t1) # True

1.5 Tuple Methods


Method Description Example

count(x) Returns number of occurrences of x (1,2,2,3).count(2) → 2

index(x) Returns index of first occurrence of x (10,20,30).index(20) → 1

1.6 Tuple Advantages

✅ Faster than lists


✅ Data integrity (cannot be modified)
✅ Can be used as dictionary keys (lists cannot)

🟣 2. Sets in Python
Definition:

A set is an unordered, mutable, and unindexed collection of unique elements.


Sets automatically remove duplicate values.

2.1 Creating a Set

Sets are created using curly braces { } or the set() constructor.

set1 = {1, 2, 3, 4, 5}
set2 = {"apple", "banana", "cherry"}
set3 = set([10, 20, 30])
print(set1)
print(set2)
print(set3)

Note:
To create an empty set, use set() (not {} which creates an empty dictionary).
2.2 Properties of Sets

 Unordered → No indexing or slicing


 Mutable → Can add or remove elements
 Unique → No duplicates allowed

s = {1, 2, 2, 3, 4}
print(s) # {1, 2, 3, 4} (Duplicate removed)

2.3 Adding and Removing Elements


Operation Description Example

add(x) Adds an element [Link](5)

update(iterable) Adds multiple elements [Link]([6, 7, 8])

remove(x) Removes element (error if not found) [Link](3)

discard(x) Removes element (no error if not found) [Link](10)

pop() Removes a random element [Link]()

clear() Removes all elements [Link]()

Example:

fruits = {"apple", "banana"}


[Link]("cherry")
[Link]("banana")
print(fruits)

2.4 Set Operations

Sets are useful for mathematical operations like union, intersection, etc.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A | B) # Union → {1,2,3,4,5,6}


print(A & B) # Intersection → {3,4}
print(A - B) # Difference → {1,2}
print(A ^ B) # Symmetric Difference → {1,2,5,6}

2.5 Set Methods


Method Description Example

union() Combines sets [Link](B)

intersection() Common elements [Link](B)

difference() Elements in A not in B [Link](B)

symmetric_difference() Elements in A or B but not both A.symmetric_difference(B)


Method Description Example

issubset() Checks if A is subset of B [Link](B)

issuperset() Checks if A is superset of B [Link](B)

🔶 Difference Between Tuple and Set


Feature Tuple Set

Syntax ( ) { }

Order Ordered Unordered

Mutability Immutable Mutable

Duplicates Allowed Not allowed

Indexing Supported Not supported

Use Case Fixed data Unique or mathematical data

✅ In summary:

 Tuple → Ordered, Immutable, Allows duplicates.


 Set → Unordered, Mutable, No duplicates, Supports set operations.

8(b). How to create and read the text data.


Ans.

Creating and Reading Text Data in Python


In Python, text data (like notes, records, or logs) is usually stored in text files with the extension .txt.
Python provides built-in functions to create, write, and read these files easily.

🟢 1. Creating (Writing) Text Data


To create or write data into a text file, you use the open() function with the write ('w') or append ('a') mode.

Syntax:
file = open("[Link]", "mode")
[Link]("Your text here")
[Link]()
File Modes:
Mode Description

'w' Write mode – creates a new file or overwrites an existing file

'a' Append mode – adds data to the end of an existing file

'r' Read mode – reads data from a file

'r+' Read and write mode

Example 1 – Create and Write to a File


# Create and write data to a file
file = open("[Link]", "w")
[Link]("Hello, this is a sample text file.\n")
[Link]("Python makes file handling easy!")
[Link]()

print("File created and data written successfully.")

This will create a file named [Link] with the given text.

Example 2 – Append Data to Existing File


# Add more text without deleting old content
file = open("[Link]", "a")
[Link]("\nThis line was added later.")
[Link]()

print("Data appended successfully.")

🟣 2. Reading Text Data


You can read data from a text file using the open() function in read mode ('r').

Example 1 – Read Entire File


file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

Output:

Hello, this is a sample text file.


Python makes file handling easy!
This line was added later.

Example 2 – Read Line by Line

You can read one line at a time using readline() or readlines().

file = open("[Link]", "r")


print([Link]()) # Reads first line
print([Link]()) # Reads next line

[Link]()

or

file = open("[Link]", "r")


lines = [Link]()

for line in lines:


print([Link]()) # Removes extra newlines
[Link]()

🟡 3. Using with Statement (Recommended)


Using the with statement automatically closes the file — safer and cleaner.

Example:
with open("[Link]", "r") as file:
content = [Link]()
print(content)

You can also write data using with:

with open("[Link]", "w") as file:


[Link]("Python file handling is easy and safe!")

🟠 4. Summary of File Handling Functions


Function Description

open(filename, mode) Opens a file in specified mode

read() Reads entire file content

readline() Reads one line

readlines() Reads all lines as a list

write(data) Writes data to file

writelines(list) Writes multiple lines

close() Closes the file

with open() Automatically closes file after use

✅ In summary:
 Use open() to create, read, or write text files.
 Always close files after use (or use with open() for safety).
 'w' for writing, 'a' for appending, and 'r' for reading.
 Text data is handled using simple string operations in Python.

9(a). How to create the class in Python programming language.


Ans.

🟢 Creating a Class in Python


In Python, a class is a blueprint for creating objects.
A class defines attributes (data) and methods (functions) that describe the behavior of an object.

Classes are an essential part of Object-Oriented Programming (OOP) in Python.

1. Basic Syntax of a Class


class ClassName:
# class body
def __init__(self, parameters):
# constructor to initialize object attributes
[Link] = value

def method_name(self):
# method to perform some action
print("This is a method")

2. Example: Creating and Using a Class


# Define a class
class Student:
# Constructor (initializer)
def __init__(self, name, age):
[Link] = name # Instance variable
[Link] = age

# Method to display student details


def display(self):
print("Name:", [Link])
print("Age:", [Link])

# Create objects (instances) of the class


s1 = Student("Alice", 20)
s2 = Student("Bob", 22)

# Access methods
[Link]()
[Link]()

Output:

Name: Alice
Age: 20
Name: Bob
Age: 22

3. Key Components of a Class


Component Description

class Keyword used to define a class

__init__() Constructor method (automatically called when an object is created)

self Refers to the current instance of the class

Attributes Variables that store data for each object

Methods Functions defined inside a class to perform operations

4. Example: Class with Methods and Attributes


class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model

def start(self):
print(f"{[Link]} {[Link]} is starting...")

def stop(self):
print(f"{[Link]} {[Link]} has stopped.")

# Create object
car1 = Car("Toyota", "Camry")

# Access attributes
print([Link])
print([Link])

# Call methods
[Link]()
[Link]()

Output:

Toyota
Camry
Toyota Camry is starting...
Toyota Camry has stopped.

5. Modifying Object Attributes

You can change or add attributes after creating an object.

student = Student("John", 19)


[Link] = 20 # Modify existing attribute
[Link] = "Python" # Add new attribute

print([Link], [Link], [Link])


6. Example: Using Multiple Objects
class Rectangle:
def __init__(self, length, width):
[Link] = length
[Link] = width

def area(self):
return [Link] * [Link]

# Create two rectangle objects


r1 = Rectangle(10, 5)
r2 = Rectangle(7, 3)

print("Area of r1:", [Link]())


print("Area of r2:", [Link]())

Output:

Area of r1: 50
Area of r2: 21

7. Class vs Object
Term Description Example

Class Blueprint or template class Student:

Object Instance of a class s1 = Student("Alice", 20)

8. Advantages of Using Classes

✅ Organizes code (modular programming)


✅ Promotes reusability
✅ Supports encapsulation and inheritance
✅ Makes complex programs easier to manage

✅ In summary:

 A class is defined using the class keyword.


 The __init__() method initializes object data.
 self refers to the instance of the class.
 Objects are created from classes to use their attributes and methods.

9(b). How to create the object in Python programming language.


Ans.

Creating Objects in Python


In Python, an object is an instance of a class.
Objects allow you to access the attributes (data) and methods (functions) defined in the class.

1. Steps to Create an Object

1. Define a class with attributes and methods.


2. Create an object (instance) of the class by calling the class name like a function.
3. Access attributes and methods using the object.

2. Basic Example
# Define a class
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display(self):
print("Name:", [Link])
print("Age:", [Link])

# Create objects (instances) of the class


s1 = Student("Alice", 20)
s2 = Student("Bob", 22)

# Access methods
[Link]()
[Link]()

Output:

Name: Alice
Age: 20
Name: Bob
Age: 22

Explanation:

 Student is the class.


 s1 and s2 are objects (instances) of the Student class.
 .display() is a method called using the objects.

3. Accessing Object Attributes

You can access or modify attributes using the object.

s1 = Student("Alice", 20)

# Access attribute
print([Link]) # Alice

# Modify attribute
[Link] = 21
print([Link]) # 21
4. Example: Multiple Objects
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model

def start(self):
print(f"{[Link]} {[Link]} is starting...")

# Create multiple objects


car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")

# Call methods using objects


[Link]()
[Link]()

Output:

Toyota Camry is starting...


Honda Civic is starting...

5. Key Points
Point Description

Object Instance of a class

Creation Call the class as a function: object_name = ClassName(arguments)

Access Use dot . operator: [Link] or [Link]()

Multiple Objects You can create multiple objects with different attribute values

6. Summary

 A class is a blueprint.
 An object is an instance of a class.
 Objects store data (attributes) and perform actions (methods).
 Objects are created by calling the class with required parameters.

10(a).Describe about the User Defined Functions in Python programming


language.
Ans.

User-Defined Functions in Python


In Python, a function is a block of code designed to perform a specific task.
A user-defined function is a function created by the programmer to perform a custom operation.
1. Why Use Functions?

 Code Reusability – Write once, use multiple times.


 Modularity – Break programs into smaller, manageable parts.
 Readability – Makes code cleaner and easier to understand.
 Avoid Redundancy – Reduces repeated code.

2. Syntax of User-Defined Function


def function_name(parameters):
"""
Optional docstring: description of the function
"""
# Code block (statements)
return value # optional

 def → Keyword to define a function


 function_name → Name of the function (must follow variable naming rules)
 parameters → Inputs to the function (optional)
 return → Sends a value back to the caller (optional)

3. Example 1: Simple Function Without Parameters


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

# Call the function


greet()

Output:

Hello, welcome to Python!

4. Example 2: Function With Parameters


def greet_user(name):
print(f"Hello, {name}!")

# Call the function with an argument


greet_user("Alice")
greet_user("Bob")

Output:

Hello, Alice!
Hello, Bob!

5. Example 3: Function With Return Value


def add(a, b):
sum = a + b
return sum
# Call the function and store result
result = add(5, 3)
print("Sum:", result)

Output:

Sum: 8

6. Types of User-Defined Functions

1. No Input, No Output

def greet():
print("Hello!")

2. Input, No Output

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

3. No Input, Output

def get_greeting():
return "Hello!"

4. Input and Output

def square(x):
return x * x

7. Example 4: Function Calling Another Function


def multiply(a, b):
return a * b

def square_and_multiply(x, y):


sq = multiply(x, x)
result = multiply(sq, y)
return result

print(square_and_multiply(2, 3)) # Output: 12

8. Advantages of User-Defined Functions

 Reduces code duplication


 Makes programs easier to read and maintain
 Helps in modular programming
 Makes debugging easier

9. Summary

 Functions are blocks of code for specific tasks.


 User-defined functions are created using the def keyword.
 Functions may have parameters (input) and return values (output).
 Using functions improves reusability, modularity, and readability.

10(b). Write about the Indentation,Comments in Python programming


language.
Ans.

1. Indentation in Python
Definition:

Indentation in Python refers to the spaces or tabs at the beginning of a line to define blocks of code.
Unlike many other programming languages that use {} to define blocks, Python relies on indentation.

Why Indentation is Important

 Indicates which statements belong to a block (e.g., inside a function, loop, or conditional).
 Mandatory in Python; missing or incorrect indentation causes IndentationError.
 Improves code readability.

Example 1: Indentation in If Statement


x = 10

if x > 5:
print("x is greater than 5") # Indented block
print("This is inside the if statement")
print("This is outside the if statement")

Output:

x is greater than 5
This is inside the if statement
This is outside the if statement

Example 2: Indentation in Function


def greet(name):
print("Hello,", name) # Indented inside function
print("Welcome to Python")

greet("Alice")

Note: All lines inside the function are indented the same way.
Rules for Indentation

 Use 4 spaces per level (recommended by PEP 8).


 Mixing tabs and spaces can cause errors.
 All statements in a block must be indented equally.

2. Comments in Python
Definition:

Comments are non-executable statements in code that explain or document the code.
Python ignores comments during execution.

Types of Comments
1. Single-line Comment

 Begins with #
 Used to add short explanations.

# This is a single-line comment


x = 10 # Variable x stores the value 10

2. Multi-line Comment

 Python does not have a special multi-line comment symbol.


 Use triple quotes """ """ or ''' ''' to create multi-line comments or docstrings.

"""
This is a multi-line comment.
It can span multiple lines.
Used to explain complex code.
"""
x = 10
y = 20

Advantages of Comments

 Makes code readable and understandable.


 Helps others (or yourself) understand your logic later.
 Useful for debugging by temporarily disabling code.

Example: Using Indentation and Comments Together


def check_number(num):
# Check if the number is positive
if num > 0:
print("Positive number") # Print if number is positive
else:
print("Zero or Negative") # Print otherwise

check_number(5)

Output:

Positive number

Summary
Feature Description

Indentation Spaces or tabs at the start of a line to define a code block. Mandatory in Python.

Comments Non-executable text to explain code. Single-line (#) or multi-line (""" """).

Python strongly emphasizes readability, so proper indentation and meaningful comments are essential.

THE END

You might also like