0% found this document useful (0 votes)
1 views30 pages

Section

Uploaded by

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

Section

Uploaded by

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

SECTION–A – MOST EXPECTED QUESTIONS

1. What is problem solving? Explain the steps involved.


2. Define algorithm. Write characteristics of a good algorithm.
3. Explain flowchart. Draw and explain flowchart symbols.
4. Write an algorithm and flowchart to add two numbers.
5. Explain the various stages of program development.
6. What is Python? Explain its features.
7. Explain the history and evolution of Python.
8. What are Python versions? Difference between Python 2 and Python 3.
9. Explain Python execution environment and interpreter.
10. What are IDEs? Explain PyCharm and VS Code.
11. Explain Python program structure in detail.
12. Write and explain your first Python program.
13. What are comments? Why are they used?
14. Explain indentation in Python with examples.
15. Explain the steps of installing and setting up Python.

Q1. What is Problem Solving? Explain the steps involved in detail.

Answer:
Problem solving is a logical, systematic, and disciplined process of identifying a problem, understanding it, and
developing an efficient solution using computers. In computer science, problem solving is extremely important
because a computer cannot perform any task unless it is instructed using clear steps.
Problem solving is a combination of analytical thinking, logical reasoning, and creativity. It helps programmers
convert a real-life problem into a computational problem that can be solved using a programming language such as
Python.

Steps Involved in Problem Solving

1. Understanding the Problem


In this stage, the programmer reads the problem carefully to understand what is being asked.
Questions asked in this stage:
• What is the input?
• What output is required?
• What conditions or constraints exist?
2. Analyzing the Problem
Here, the problem is divided into smaller tasks. The programmer identifies:
• Inputs
• Outputs
• Processing requirements
• Exception cases
3. Designing the Solution
This is the most critical step. The programmer designs an algorithm (step-by-step solution) and a flowchart
(graphical solution). Proper planning reduces errors.
4. Coding (Implementation)
In this stage, the designed algorithm is converted into a Python program using correct syntax, rules, and programming
logic.
5. Testing
The program is executed using various test cases to check whether the output is correct or not. Testing ensures:
• Correctness
• Reliability
• Accuracy
6. Debugging
If any errors occur during testing, the programmer fixes them by correcting syntax errors, logical errors, or runtime
errors.
7. Documentation
Documentation includes writing explanations for the code, algorithm, or program so that others can easily understand
and modify it in the future.
8. Maintenance
Programs need updates with time. Maintenance includes improving performance, adding new features, and fixing
bugs.

Q2. Define Algorithm. Explain characteristics of a good algorithm.

Answer:
An algorithm is a step-by-step, finite, and well-defined sequence of instructions designed to solve a specific problem.
It represents the solution approach before writing the actual code.

Characteristics of a Good Algorithm

1. Clear and Unambiguous


Every step must be precise and have only one meaning. No confusion should occur.
2. Finite
An algorithm must terminate after a limited number of steps.
3. Well-defined Input
Inputs should be clearly specified.
4. Well-defined Output
Output must be clear and expected.
5. Effective
Each step should be basic enough that it can be executed by a computer.
6. Language Independent
Algorithm is not written in any specific programming language.
7. Logical Flow
Steps must follow a clear and logical order.

Q3. Explain Flowchart. Draw flowchart symbols.

Answer:
A flowchart is a graphical or pictorial representation of an algorithm. It uses different shapes to show different
operations, making the logic easy to understand.
Flowcharts are used for:
• Planning program logic
• Debugging
• Presenting ideas visually
• Simplifying complex processes

Flowchart Symbols

Symbol Meaning

Oval Start/Stop

Rectangle Process (calculation)

Parallelogram Input/Output

Diamond Decision (Yes/No)

Arrow Direction of flow

Example Flowchart (Add Two Numbers)

(Start)
|
[ Input a, b ]
|
[ c=a+b ]
|
[ Print c ]
|
(Stop)

Q4. Write an algorithm and flowchart to add two numbers.


Algorithm:
1. Start
2. Declare variables a, b, c
3. Read values of a and b
4. c = a + b
5. Print c
6. Stop

Flowchart:
(Same as above)

Q5. Explain Stages of Program Development.

Answer:
Program development follows these stages:
1. Problem Definition
2. Problem Analysis
3. Algorithm Design
4. Flowchart Creation
5. Coding
6. Testing
7. Debugging
8. Documentation
9. Maintenance
(Already explained in Q1 but more detailed in exam format)

NOW PYTHON INTRO PART OF LONG ANSWERS

Q6. What is Python? Explain features of Python.

Answer:
Python is a high-level, interpreted, and general-purpose programming language created by Guido van Rossum in
1991. It is known for its simplicity, readability, and powerful libraries.

Features (Explain in exam):

1. Simple and Easy to Learn


2. Interpreted
3. Object-Oriented
4. Portable
5. Extensive Libraries
6. Free and Open Source
7. Dynamic Typing
8. High Productivity

Q7. Explain Python Program Structure.

A Python program generally contains:


1. Statements
2. Variables
3. Expressions
4. Functions
5. Indentation
6. Comments

Q8. Write and explain your first Python program.

print("Hello World")
Explanation:
• print() is a built-in function.
• It displays text on screen.
• The text inside quotes is a string.

Q9. Explain Indentation in Python.

Indentation means adding spaces to indicate a block of code.


Example:
if a > b:
print("A is greater")
No braces used like C, C++ or Java. Python fully depends on indentation.

Q10. What are Comments in Python? Explain types, purpose, and advantages in detail.**

Answer:
Comments are an essential part of any programming language, including Python. A comment is a piece of text written
inside a program that is ignored by the Python interpreter during execution. Comments are not executed as part of the
code; rather, they exist solely for the benefit of the programmer or anyone reading the program.
In simple terms, comments act as notes or explanations inside a program. They help improve the readability, clarity,
and maintainability of code. While writing complex programs, comments become necessary because they explain
what different parts of the code are doing, why a specific logic is used, and how a program flows.
Python provides two major types of comments: single-line comments and multi-line comments.

Need / Importance of Comments

1. Improves readability
Comments make it easier for others (or even yourself after months) to understand what your code does.
2. Acts as documentation
Comments serve as in-program documentation that explains functions, logic, variables, and algorithms.
3. Helps during debugging
Programmers can disable lines of code temporarily by converting them into comments.
4. Explains complex logic
Whenever a code segment is difficult to understand at first glance, comments describe it in simple words.
5. Enhances teamwork
In collaborative projects, comments help team members understand each other's work.
6. Defines purpose and usage
Comments explain why a function exists, what parameters it accepts, and what output it returns.

Types of Comments in Python

Python supports two main types:

1. Single-Line Comments

A single-line comment begins with the '#' (hash symbol).


Everything written after # in the same line is ignored by Python.
Syntax:
# This is a single-line comment

Example:

# This program adds two numbers


a = 10
b = 20
c=a+b
print(c) # printing the result
Explanation:
• The comment at the top describes the purpose of the program.
• The comment beside print() explains what that line does.
• Python ignores all these comments during execution.

2. Multi-Line Comments

Python does not have a dedicated multi-line comment symbol like C (/* */).
Instead, multi-line comments are written using triple quotes:
• Triple single quotes:
• ''' Multi-line comment '''
• Triple double quotes:
• """ Multi-line comment """
These are usually written at the beginning of a program, function, or class to describe their purpose in detail.

Example:

"""
This program demonstrates multi-line comments in Python.
It calculates the square of a number.
Author: Harkirat
Date: 01-12-2025
"""

x=5
square = x * x
print("Square =", square)
Explanation:
• The comment block explains what the program does.
• Such comments are helpful in large programs and for documentation.

3. Inline Comments

Inline comments appear on the same line as a statement.


Example:
x = 10 # assigning value to x
y = 20 # assigning value to y
print(x + y) # printing sum
Inline comments should be short and precise.

Best Practices for Writing Comments

1. Write meaningful comments – Avoid obvious comments like:


2. a = a + 1 # adding 1
3. Keep comments short and clear
4. Update comments when code changes
5. Do not overuse comments – Code should be self-explanatory.
6. Use comments for complex logic, not simple statements
Advantages of Using Comments

1. Makes code easy to understand


2. Saves time during debugging
3. Helps new programmers analyze the code
4. Essential for teamwork and collaboration
5. Useful when revisiting old programs
6. Improves code documentation quality

Q11. Explain Python Interpreter and its Working. (Long Answer)

Answer:
Python is an interpreted language, which means its code is not converted into machine code in a single step like C or
C++.
Instead, Python uses an interpreter that executes the program line by line.
A Python interpreter is a software component that reads Python source code, translates it into an intermediate form,
and executes it.

Working of Python Interpreter (Step-by-Step)

When we write a Python program (e.g., [Link]) and run it, the interpreter performs the following steps:
1. Reading the Source Code
The interpreter opens the Python file and reads each line from top to bottom.
2. Lexical Analysis
The code is broken into small units called tokens:
Example tokens: print, "Hello", (, )
3. Parsing
The tokens are arranged into a structure called a Parse Tree.
It checks if the syntax is correct.
4. Bytecode Generation
If the syntax is correct, Python converts the code into an intermediate form known as bytecode (.pyc files).
Bytecode is NOT machine code — it is a lower-level, portable instruction set.
5. Python Virtual Machine (PVM) Execution
The bytecode is executed by the Python Virtual Machine, which interacts with the system and gives the output.

Why Python uses Interpreter?

1. Easy debugging
2. Cross-platform portability
3. Fast development
4. No need for manual compilation

Types of Python Interpreters

1. CPython – Default, standard interpreter (most widely used)


2. PyPy – Faster interpreter using JIT
3. Jython – Runs on Java Virtual Machine
4. IronPython – Integrates with .NET
5. MicroPython – For microcontrollers

Q12. What is IDE? Explain different Python IDEs.

Answer:
An IDE (Integrated Development Environment) is a software application that provides tools to write, edit, debug,
and run programs easily.
It combines:
• Code editor
• Compiler/interpreter
• Debugger
• Auto-completion
• Project tools
IDEs make coding faster and error-free.

Popular Python IDEs

1. Python IDLE
• Comes with Python installation
• Simple and lightweight
• Best for beginners
2. PyCharm
• Developed by JetBrains
• Professional IDE
• Best for large projects
• Features: auto-complete, debugger, console, plugins
3. Visual Studio Code (VS Code)
• Lightweight
• Highly customizable
• Large plugin support
• Supports multiple languages
4. Jupyter Notebook
• Best for Data Science
• Supports cell-based execution
• Good for visualization and experiments
5. Spyder
• Used for scientific computing
• MATLAB-like interface

Q13. Explain the Python Execution Environment.

Answer:
A Python execution environment refers to the complete setup in which Python programs can be written, executed, and
tested.
A full execution environment includes:

1. Python Interpreter

Converts source code to output.

2. Standard Library

Python comes with hundreds of built-in modules like math, random, os, datetime.

3. External Libraries

Packages installed using pip (e.g., numpy, pandas).

4. IDE/Code Editor

Tools for writing programs easily.

5. File System

Python interacts with files to read/write data.

6. Operating System

Windows, macOS, Linux — Python works on all.

Q14. Explain the Process of Installing and Setting Up Python. (Long Answer)

Answer:
Setting up Python involves the following steps:

Step 1: Download Python

• Open official website: [Link]


• Go to Downloads section
• Select version (Python 3 recommended)
Step 2: Install Python

• Run the installer


• Tick the option: “Add Python to PATH”
• Click “Install Now”
• Wait for installation to complete

Step 3: Verify Installation

Open terminal/command prompt:


python --version
If Python is installed, version will appear.

Step 4: Install Code Editor or IDE

You can install:


• PyCharm
• VS Code
• IDLE (already included)

Step 5: Write Your First Program

Open IDLE and type:


print("Hello World")
Run the program using Run → Run Module.

Step 6: Set Up pip

pip allows installing external Python packages:


pip install package_name

Q15. Explain Python Program Structure in Detail. (Long Answer)

A Python program is logically divided into multiple components.


Typical structure:

1. Comments

Used to describe code.

2. Import Statements

Used to include modules.


Example:
import math

3. Variables and Data Types

Used to store values.


Example:
name = "Harkirat"
age = 20

4. Expressions

Mathematical or logical operations.


Example:
total = a + b

5. Control Statements

Decision making using if, elif, else.

6. Loops

for, while loops used for repetition.

7. Functions

Blocks of reusable code.

8. Indentation

Defines program blocks.


Python uses spaces instead of braces.

9. Output Statements

Used to display results.


Example:
print("Result:", result)

10. End of Program

Execution stops when statements finish.


Bhai, ab main Section–B ke 10 MOST IMPORTANT EXPECTED QUESTIONS + FULL LONG ANSWERS (2–
3 page exam level) deta hoon.
Ye EXACT wahi questions hain jo exam me baar-baar repeat hote hain.
I am giving:
1. Top 10 Expected Questions
2. Long, High-Scoring Answers (detailed, neat)
3. Hinglish understanding + English exam-writing style
Chal start karein.

SECTION–B – TOP 10 MOST EXPECTED EXAM QUESTIONS

1. What is a variable? Explain rules for naming variables in Python.


2. Explain different data types and literals in Python with examples.
3. What are operators? Explain different types of operators in Python.
4. What are escape sequences? Explain with examples.
5. Explain control flow statements (if, elif, else) with examples.
6. Explain loops in Python. Differentiate between for and while loops.
7. What are break and continue statements? Explain with examples.
8. Explain lists in Python along with operations.
9. What is a tuple? Differentiate between list and tuple.
10. What is a dictionary? Explain its features and operations.
Yeh top 10 questions guaranteed exam repeat hain.

SECTION B

Q1. What is a Variable? Explain the rules for naming variables in Python. (Long Answer)

Answer:
A variable is a name given to a memory location where data is stored. In Python, variables are used to store values that
can be used and manipulated throughout the program. A variable acts like a container that holds data temporarily while
the program is running.
Python is a dynamically typed language, meaning that the type of the variable is determined at runtime. You do not
need to declare the type of variable beforehand.

Example of variables

name = "Kirat"
age = 20
marks = 92.5

Rules for Naming Variables (Identifiers)


1. A variable must start with a letter or an underscore (_).
Example: name, _value
2. A variable cannot start with a digit.
Wrong: 1name
Correct: name1
3. No special characters are allowed, such as @, #, $, %, etc.
4. Spaces are not allowed.
Wrong: my name = "Ram"
Correct: my_name = "Ram"
5. Python is case-sensitive.
Age and age are different variables.
6. Keywords cannot be used as identifiers.
Example: if, else, for, while, class
7. Names should be meaningful.
Good practice: total_marks, student_name

Importance of Variables

• Help in data storage


• Required for computation
• Used to access and modify values
• Promote code readability

Q2. Explain Data Types and Literals in Python. (Long Answer)

Answer:
Data types represent the type of value a variable can store. In Python, data types are automatically assigned based on
the value stored.

1. Numeric Data Types

• int → whole numbers


Example: 10, -3
• float → decimal numbers
Example: 3.14, 12.5
• complex → number with real + imaginary part
Example: 2+3j

2. String Data Type

String represents a sequence of characters enclosed in quotes.


Example:
name = "Python"
3. Boolean Data Type

Stores True or False.


Example:
flag = True

4. None Type

Represents no value.
x = None

Literals

Literals are fixed constant values written directly in the program.


Types of literals:
• Numeric literal: 10, 12.5
• String literal: "Hello"
• Boolean literal: True
• None literal: None

Q3. What are Operators? Explain their types. (Long Answer)

Answer:
Operators are symbols that perform operations on variables and values. Python provides several categories of
operators.

1. Arithmetic Operators

Used for mathematical operations.

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

// Floor Division

** Exponent

Example:
5 ** 2 # 25
2. Relational Operators

Used for comparison.

Operator Function

== Equal

!= Not equal

> Greater

< Less

>= Greater or equal

<= Less or equal

3. Logical Operators

Used for combining conditions.


and, or, not

4. Assignment Operators

=, +=, -=, *=, /=

5. Membership Operators

in, not in

6. Identity Operators

is, is not

Q4. What are Escape Sequences? Explain with examples. (Long Answer)

Escape sequences are special character combinations used inside strings to represent non-printable or special
characters.
Examples:
• \n → new line
• \t → tab
• \" → double quote
• \\ → backslash

Example Program

print("Hello\nWorld")
print("Name:\tKirat")
print("He said \"Hi\"")

Q5. Explain Control Flow Statements. (Long Answer)

Control flow statements decide the flow of execution based on conditions.

1. if Statement

if condition:
statements

2. if–else

if cond:
print("true")
else:
print("false")

3. if–elif–else Ladder

Used when multiple conditions exist.


if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
else:
print("Grade C")

Q6. Explain Loops. Difference between for and while. (Long Answer)

Loops repeat a block of code multiple times.

1. for Loop

Used when number of repetitions is known.


for i in range(1, 6):
print(i)

2. while Loop

Used when repetition continues until condition becomes false.


i=1
while i <= 5:
print(i)
i += 1

Difference between for & while

for Loop while Loop

Used when repetitions are known Used when repetitions depend on condition

range() used Condition used

More compact May become infinite

Q7. break & continue (Long Answer)

break

Immediately stops the loop.


for i in range(10):
if i == 5:
break

continue

Skips current iteration and moves to next.


for i in range(5):
if i == 3:
continue
print(i)

Q8. Explain Lists in Python. (Long Answer)

A list is a mutable, ordered collection of items.


Example:
a = [1, 2, 3, 4]

Features:

• Allows duplicates
• Heterogeneous
• Mutable
• Indexed

Common list operations:

[Link](10)
[Link](1, 5)
[Link](3)
[Link]()
[Link]()

Q9. What is a Tuple? Difference between list and tuple. (Long Answer)

Tuple is an ordered, immutable collection.


Example:
t = (10, 20, 30)

Features:

• Immutable
• Faster
• Ordered

List vs Tuple

List Tuple

Mutable Immutable

Slower Faster

Uses [] Uses ()

More memory Less memory

Q10. What is a Dictionary? Explain its features. (Long Answer)

Dictionary stores data in key-value form.


Example:
d = {"name": "Kirat", "age": 20}

Features:

• Key-value pairs
• Mutable
• No duplicate keys
• Fast access

Operations:

[Link]()
[Link]()
[Link]()
d["name"]

SECTION C

1. What is a function? Explain types of functions.


2. Explain user-defined functions with examples.
3. What is the return statement? Explain its importance.
4. Explain types of arguments (positional, keyword, default, variable-length).
5. What is a module? Explain advantages.
6. Explain different ways to import a module.
7. Write a note on math and random modules.
8. What is exception handling? Why is it required?
9. Explain try–except–else–finally.
10. Explain types of errors and exceptions.
Let’s begin.

**LONG ANSWER 1

What is a Function? Explain the types of functions in Python.**


Answer:
A function is a block of organized, reusable code that performs a specific task. Functions help divide a large program
into small, manageable parts, improving readability and reducing repetition. In Python, functions make the program
modular and easier to maintain.
Python follows the principle of "DRY" (Don’t Repeat Yourself), and functions play a key role in achieving this.
Functions increase productivity because the same block of code can be reused multiple times.

Types of Functions in Python

Python provides three main categories of functions:

1. Built-in Functions

These functions are already available in Python and do not require any definition. They are ready to use.
Examples:
• print()
• input()
• len()
• max()
• type()
These functions perform basic tasks like displaying output, taking input, finding length of data, etc.

2. User-Defined Functions

These are functions created by the programmer. They help avoid repetition and make the program modular.
Syntax:
def function_name(parameters):
statements
return value

3. Recursive Functions

A recursive function is one that calls itself. It is useful for tasks such as factorial, Fibonacci series, and tree traversal.
Example:
def fact(n):
if n == 1:
return 1
return n * fact(n-1)

Conclusion

Functions are an essential part of Python programming. They improve modularity, reduce code redundancy, and
simplify debugging and maintenance.

**LONG ANSWER 2

Explain user-defined functions with examples.**


Answer:
User-defined functions are functions created by programmers to perform specific tasks. These functions help break
down complex programs into smaller parts and allow reuse of code.

Steps to create a user-defined function

1. Use the def keyword


2. Write function name
3. Provide parameters (optional)
4. Write statement block
5. Use return (optional)
Example 1: Function without parameters

def greet():
print("Hello User")
Call:
greet()

Example 2: Function with parameters

def add(a, b):


return a + b
Call:
print(add(5, 3))

Example 3: Function with return

def square(x):
return x * x

User-defined functions provide flexibility and make complex programs easy to write and maintain.

**LONG ANSWER 3

What is the return statement? Why is it important?**


Answer:
The return statement is used in a function to send a value back to the calling function. Without a return statement, a
function cannot provide any result.

Importance of return statement

1. Sends output from function to caller


2. Allows function results to be reused
3. Helps in modular programming
4. Improves flexibility

Example:

def multiply(a, b):


result = a * b
return result
If return is omitted, function returns None.
**LONG ANSWER 4

Explain types of arguments in Python.**


Python supports 4 major argument types:

1. Positional Arguments

Order matters.
def info(name, age):
print(name, age)

info("Ram", 20)

2. Keyword Arguments

Order does not matter.


info(age=20, name="Ram")

3. Default Arguments

Values assigned by default.


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

4. Variable-length Arguments

*args → multiple values (tuple form)


def sum(*numbers):
print(sum(numbers))
kwargs → keyword arguments (dictionary form)
def info(**data):
print(data)

**LONG ANSWER 5

What is a Module? Explain its advantages.**


Answer:
A module is a Python file that contains functions, variables, and classes.
It allows code to be organized into separate files.
Example: [Link], [Link]
Advantages of Modules

1. Code Reusability
2. Easy Maintenance
3. Reduces complexity
4. Provides built-in utilities
5. Improves readability

**LONG ANSWER 6

Explain different ways to import a module.**


Python allows three main import styles:

1. Simple Import

import math
print([Link](25))

2. Selective Import

from math import sqrt


print(sqrt(36))

3. Import with Alias

import math as m
print([Link])

**LONG ANSWER 7

Write a note on math and random modules.**

math module functions

• sqrt(x)
• pow(x,y)
• floor(x)
• ceil(x)
• factorial(x)
• pi
random module functions

• random() → 0 to 1
• randint(a,b)
• choice(list)
• shuffle(list)

**LONG ANSWER 8

What is Exception Handling? Why is it required?**


Answer:
Exception handling is a mechanism to handle runtime errors in a Python program.
Without exception handling, the program stops abruptly.

Need of Exception Handling

1. Prevents program crash


2. Provides meaningful error messages
3. Improves program reliability
4. Ensures smooth flow

Example:

try:
a = 10/0
except ZeroDivisionError:
print("Cannot divide by zero")

**LONG ANSWER 9

Explain try–except–else–finally with example.**

try block → code that may cause error


except block → handles error
else block → runs when no error occurs
finally block → always runs

Example:

try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("Valid number")
finally:
print("Execution complete")

**LONG ANSWER 10

Explain types of errors and exceptions.**


Python has two main error categories:

1. Syntax Errors

Detected before execution.


Example:
print("Hello)

2. Runtime Errors (Exceptions)

Examples:
• ZeroDivisionError
• ValueError
• TypeError
• IndexError
• FileNotFoundError

SECTION - D

1. What is file handling? Explain different file modes.

File Handling means reading and writing data to files stored on a computer permanently. Python uses the open()
function to access a file.

File Modes:

Mode Meaning

"r" Read mode (file must exist)

"w" Write mode (overwrites entire file)

"a" Append mode (adds new data at end)


Mode Meaning

"rb" Read binary file (images/videos)

"wb" Write binary file

Example:
f = open("[Link]", "r")

2. Write a note on opening, reading, writing, and closing files.

Opening a file
f = open("[Link]", "r")
Reading a file
• read() → reads entire file
• readline() → reads one line
• readlines() → reads all lines in a list
Writing a file
f = open("[Link]", "w")
[Link]("Hello Python")
Closing a file
[Link]()
Closing file frees memory & protects data.

3. Explain read(), write(), readline(), readlines().

read()
Reads complete file.
[Link]()
readline()
Reads one single line.
[Link]()
readlines()
Returns all lines in list form.
[Link]()
write()
Writes text into file.
[Link]("Hello")
4. What is the with statement? Why is it recommended?

The with statement automatically opens AND closes a file.


Example:
with open("[Link]", "r") as f:
data = [Link]()

Why recommended?

1. File automatically closes


2. No risk of data loss
3. Cleaner code
4. Handles errors better

5. Differentiate between text files and binary files.

Text File Binary File

Human readable Machine readable

Stores characters Stores bytes

.txt, .py .jpg, .mp4, .exe

Slower access Faster processing

Opens in "r"/"w" Opens in "rb"/"wb"

6. What are strings? Explain string slicing.

A string is a sequence of characters enclosed in quotes.


Example: "Hello"

String Slicing

Extract portion of a string.


Syntax:
str[start:end]
Example:
s = "Python"
s[1:4] # "yth"
s[:3] # "Pyt"
s[3:] # "hon"

7. Explain common string methods.


Method Purpose

upper() Converts to uppercase

lower() Converts to lowercase

strip() Removes spaces

title() Converts to Title Case

replace(a,b) Replace text

find() Returns index of substring

split() Breaks string into list

join() Joins list into string

Example:
"hello".upper() → "HELLO"

8. Explain indexing and slicing in Python strings.

Indexing

Position numbers of characters.


P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Slicing

Extract part of string:


s = "Python"
s[0:3] # Pyt
s[-3:] # hon

9. What is string concatenation? Explain with examples.

Concatenation = joining strings using +.


Example:
"Hello" + "World"
Output:
HelloWorld
With space:
"Hello " + "World"
10. Explain immutability of strings.

Strings in Python are immutable, meaning once created, they cannot be changed.
Example:
s = "Hello"
s[0] = "J" # ERROR
When we modify a string, Python creates a new string.
Example:
a = "Hello"
a = a + "World"
Here original "Hello" stays in memory; a new string is created.

You might also like