Python 3rd
Python 3rd
🖌️
byte from the start. For example, [Link](0) moves the handle to the very beginning.
3. Explain the jump and unconditional control statements in Python with syntax and
examples.?
*Unconditional control statements allow the flow of control to jump or skip certain parts of a
program without depending on a condition.
1. pass Statement: The pass statement does nothing but is used to complete the syntax where a
statement is required. When the Python compiler encounters a pass statement, it simply ignores
it and moves to the next statement.
Ex: a = int(input("Enter first Number: "))
b = int(input("Enter Second Number: "))
if (b == 0):
pass
else:
print("a/b =", a/b)
2. break Statement: The break statement enables skipping over part of a loop even if the
condition remains true.
Ex: for i in range(5):
if i == 3:
break
print(i) Output: 0 1 2
3. continue Statement: The continue statement skips the current iteration and starts the next
iteration of the loop.
Example 1: for i in range(6):
if i % 2 != 0:
continue
print(i) Output: 0 2 4
🖌️ Features of Python:
1)Easy to Learn and Use: Python is very easy to learn compared to other [Link] syntax is
simple like English and indentation defines the code [Link] is highly suitable for beginners.
2)Expressive Language: Python performs complex tasks with very few lines of [Link]
example,the statement print("Hello World") executes in one line while Java or C needs multiple
lines.
3)Interpreted Language: Python is an interpreted language which means it executes the code line
by [Link] makes debugging easier and the code portable.
4)Cross-Platform: Python programs can run on Windows,Linux,UNIX,and Mac [Link] is a portable
language because the same program can run on multiple platforms.
5)Free and Open Source: Python is freely available on its official website [Link]
can use or modify its source code [Link] has a large active community that develops new
modules.
6)Object-Oriented: Python supports object-oriented programming concepts like
classes,objects,inheritance,polymorphism,and [Link] allows code reusability and
modular programming.
7)Extensible: Python can use code written in C or C++ and it can be compiled to bytecode which
runs on any platform.
8)Large Standard Library: Python includes rich libraries for various fields like machine
learning,web development,and data [Link] are
NumPy,Pandas,TensorFlow,Keras,Django,and Flask.
9)GUI Programming Support. 10)Integrated and Embeddable. 11)Dynamic Memory Allocation.
🖌️ [Link] Variables: A variable is a named location used to store data during program
execution. Variables hold values of any data type. In Python, when a variable is created, it
occupies memory space according to the value and its type. The Python interpreter automatically
allocates RAM based on the data type. The value of a variable can be changed anytime. An
identifier is the unique name given to a variable.
*Syntax: variable_name = value
*Note: In Python, we do not need to specify the data type. Python automatically understands the
data type and allocates memory space accordingly.
*Rules for declaring Variables:
1. A variable name cannot start with a number. It must begin with an alphabet or underscore.
2. Variable names are case-sensitive and can include alphabets, numbers, and underscores.
3. Variable names cannot use reserved keywords.
4. The equal sign (=) is used to assign values to variables.
*Assigning values to Variables: There are different methods to assign values to variables.
1) Simple declaration and assignment:
Example:
num = 10
print(num) output: 10
2) Changing the value of a Variable:
val = 50
print("Initial value:", val) output: 50
3) Assigning multiple values to multiple Variables:
name, age, city = 'David', 27, 'New York'
print(name)
print(age)
print(city) output: David, 27, new york
🖌️ 2.)Python Constants: A Python constant is a variable whose value cannot be changed during
program execution. Constants represent fixed values that remain the same throughout the
program. They are like a bag of fruits where items cannot be replaced or changed.
Note: Unlike other programming languages, Python does not have built-in constants. Instead,
constants are represented by writing variable names in UPPERCASE letters. Example: PI = 3.14
*Rules for declaring Constants:
1. Constants should contain a combination of lowercase (a-z), uppercase (A-Z), digits (0-9), or an
underscore (_).
2. Constant names must always be written in UPPERCASE. Example: CONSTANT = 50
3. Constant names should not begin with digits.
4. Except underscore (_), no special symbols like (!, #, ^, @, $) can be used.
5. Use meaningful names for constants. Example: VALUE is better than V.
*Assigning Values to Constants:
Constants are usually declared and assigned inside a separate module file in Python. The
module is imported into the main program where constants can be used. Constants are written
in all capital letters with underscores separating words.
Example:
PI = 3.14
GRAVITY = 9.8
[Link] file:
import constant as const
print('Value of PI:', [Link])
print('Value of Gravitational force:', [Link])
Output: Value of PI: 3.14
Value of Gravitational force: 9.8
🖌️ 3.)Python Keywords: Python keywords are predefined reserved words that have special
meanings and define the syntax of Python. They cannot be used as identifiers, variable names, or
function names.
All keywords are written in lowercase except True and False. There are 35 keywords in Python.
*To check whether a word is a keyword, use the keyword module:
import keyword
print([Link]("if"))
print([Link])
*Rules for Keywords in Python:
• Keywords cannot be used as identifiers.
• All keywords must be written in lowercase except True and False.
•and → Logical operator; returns True if both operands are true.
•or → Logical operator; returns True if any one operand is true.
•not → Logical operator; returns True if the operand is false.
•if → Used to make a conditional statement.
•elif → Used with if; executes if previous conditions are not true.
🖌️3.) Python Literals: The data which is being assigned to the variables are called as Literal. In
Python, Literals are defined as raw data which is being assigned to the variables or constants.
Numeric Literals: Numeric Literals are values assigned to the Variables or Constants which
cannot be changed i.e., they are immutable. There are a total of 3 categories in Numeric Literals.
They are – Integer, Float, and Complex.
🖌️ 4.)Identifiers in Python: An identifier is a user-defined name given to a variable, function, class,
or module. It is used to uniquely identify an element in a Python program. Identifiers are case-
sensitive, meaning num, Num, and NUM are treated as three different names. It is a good
practice to give meaningful names to identifiers for better readability.
We can use the isidentifier() method in Python to check if a string is a valid identifier or not.
*Rules for Naming Python Identifiers:
• Identifiers cannot be a reserved Python keyword.
• Identifiers should not contain any white spaces.
• They can include alphabets (A–Z, a–z), digits (0–9), and underscores ().
• An identifier must begin with an alphabet or an underscore.
• No special characters except underscore () are allowed.
*Examples of Valid Identifiers:
var1 , _var1, _1_var, var_1
*Python Keywords and Identifiers Example:
*print("Example of True, False, and, or, not keywords")
# compare two operands using and operator
print(True and True)
*Output: Example of True, False, and, or, not keywords
True
🖌️ 5.) Python Input Statement: In Python, we use the input() function to take input from the user.
Whatever you enter as input, the input() function converts it into a string. Even if you enter an
integer value, the input() function still treats it as a string.
Example: name = input("What is your name? ")
print("Hello,", name)
Output: What is your name? GFG
Hello, GFG!
Python input() Syntax
*Syntax: input(prompt)
*Parameter: prompt (optional): The string that is displayed to the user on the screen (without
newline).
Example: "Enter your name:"
*Return: Returns a string object as user input.
🖌️ 6.)Python Output Statement: The print() function in Python prints the message to the screen
or any standard output device.
Example: name = "John"
print("Name:", name)
Output: Name: John
*Syntax: print(value(s), sep=' ', end='\n', file=file, flush=flush)
*Parameters:
value(s): One or more values to print. (Automatically converted to string)
sep (optional): Separator between values. Default is ' '.
*Return Type: Returns the output to the screen (no explicit return value).
* How print() Works in Python: You can pass variables, strings, numbers, or other data types as
one or more parameters to the print() function. Each parameter is converted into a string using
the str() function. These strings are then concatenated together with spaces between them to
form the final output.
🖌️ 1. Explain in detail the different types of selection statements in Python with syntax and
examples.?
*In Python, selection statements are used to make decisions and execute a particular set of
statements based on conditions.
1. if statement: This construct of a Python program consists of one if condition with one block of
statements. When the condition becomes true, it executes the block given below it.
Ex: age = int(input("Enter Age: "))
(age >= 18):
print("You are eligible for vote")
if (age < 0):
print("You entered Negative Number")
2. if-else statement: This construct of a Python program consists of one if condition with two
blocks. When the condition becomes true, it executes the block given below it. If the condition
evaluates to false, it executes the block given below else.
age = int(input("Enter Age: "))
if (age >= 18):
print("You are eligible for vote")
else:
print("You are not eligible for vote")
3. Ladder if-else (if-elif-else): This construct consists of more than one if condition. When the
first condition evaluates to true, it executes the block given below it. If it is false, it transfers the
control to another condition. It is a multi-decision-making construct.
num = int(input("Enter Number: "))
if (num >= 0):
print("You entered positive number")
elif (num < 0):
print("You entered Negative number")
else:
print("You entered Zero")
4. Nested if statement: It is the construct where one if condition is placed inside another if
condition. The inner block executes when both conditions are true. It is also a multi-decision-
making construct.
num = int(input("Enter Number: "))
if (num <= 0):
if (num < 0):
print("You entered Negative number")
else:
print("You entered Zero")
else:
print("You entered Positive number")
🖌️ 2. Explain in detail the iteration (looping) statements in Python with examples.?
*The iteration or looping construct executes a block of statements again and again depending on
the result of a condition. This repetition continues until the condition becomes false. Python
supports the following types of iteration statements: while loop and for loop.
1. while loop: The while loop is a conditional construct that executes a block of statements
repeatedly while a given condition remains true. When the condition becomes false, the loop
terminates.
Syntax:initialization
while (condition):
statements
update
Ex: num = 1
while (num <= 10):
print(num, end=" ")
num += 1
2. for loop: A for loop is used for iterating over a sequence (that is either a list, tuple, or string). It
can execute a set of statements once for each element in a sequence.
fruits = ["mango", "apple", "grapes", "cherry"]
for x in fruits:
print(x) Output: mango, apple, grapes, cherry
3. else in loop: The else keyword in a loop specifies a block of code to be executed when the loop
finishes normally.
for x in range(4):
print(x)
else:
print("Finally finished!")
4. Nested loops: A nested loop is a loop inside another loop.
city = ["Jaipur", "Delhi", "Mumbai"]
fruits = ["apple", "mango", "cherry"]
for x in city:
for y in fruits:
print(x, ":", y)
🖌️ 1. What is the role of the os module in Python file handling? Write Python code to rename a
file named "[Link]" to "[Link]" and then delete the "[Link]" file.
*Role of the os Module: The os module provides an interface to the Operating System (OS),
allowing Python programs to perform file system operations directly. Its key roles in file handling
include:
* Renaming Files: Using [Link](old_name, new_name). * Deleting Files: Using
[Link](file_path). * Path Management: Checking file existence and manipulating file paths
(via [Link]).
*Python Program to Rename and Delete a File: This code uses the os module to rename a file
and then delete it, including necessary setup and error handling.
🖌️ 2. Explain the purpose of the with keyword in file handling. Write a Python function to count
the total number of lines and spaces in a given text file.?
*Purpose of the with Keyword: The with statement ensures automatic resource management
(using context managers).
● It guarantees that the file is properly closed (by calling [Link]()) as soon as the block is
exited.
● This closing happens even if runtime errors (exceptions) occur.
● This mechanism is crucial for preventing resource leaks and data corruption.
*Program to Count Lines and Spaces
def count_stats(f):
try:
with open(f, "r") as file:
# 1. Lines count
lines = [Link]()
line_count = len(lines)
# 2. Spaces count (Need to seek back to the start)
[Link](0)
content = [Link]()
space_count = [Link](' ')
print(f"Lines: {line_count}, Spaces: {space_count}")
except FileNotFoundError:
print("File not found.")
🖌️ 1. Defining and Processing Arrays? The array module is typically used when you need a
sequence that only stores items of the same data type for better performance and memory
efficiency.
*Defining an Array: To create an array using the array module, you must first import the module
and then use the [Link]() function, specifying a type code to define the data type of the
elements.
**Processing Arrays: Arrays, like lists, are sequence types and support standard sequence
operations:
* Indexing: Accessing individual elements by their zero-based index (e.g., my_array[2] returns 30).
* Slicing: Extracting a subset of elements (e.g., my_array[1:4] returns [20, 30, 40]).
* Modification: Changing the value of an element at a specific index (e.g., my_array[2] = 35).
* Length: Finding the number of elements using the len() function (e.g., len(my_array) returns 5).
🖌️
* Concatenation: Combining two arrays of the same type using the + operator.
2. Array Methods: The array object provides several built-in methods for manipulation,
addition, and conversion.
*Append: add a single item with value x to the end of the array.
*Extend: add multiple items from an iterable (like a list or another array) to the end of the array.
*Insert: add a single item with value x at a specific index i.
*Pop: remove and return the element at a specific index i. If no index is given, it removes the last
element.
*Remove: remove the first occurrence of the element with the value x.
*Index: return the smallest index where the value x is found.
*Count: return the number of times the value x appears in the array.
*Reverse: reverse the order of the elements in the array in place.
*Tolist: convert the array into a standard Python list.
*Fromlist: append items from a standard Python list to the end of the array.
Important 10-Mark Questions with Answers: Python
File Handling (Unit 5)
Q.1: Explain the concept of File Handling in Python. Describe the six
main File Access Modes used with the open() function and explain the
significance of the File Handle in these operations.
Answer
1. File Handling Concept
File handling is an integral part of programming, simplified in Python with built-in methods for
creating, opening, and closing files. It allows performing various file operations like reading,
writing, and appending information. All these operations are controlled by Access Modes,
which determine how the file will be used after it is opened.
2. Six Main File Access Modes
These modes specify the operations allowed and the initial location of the File Handle (pointer)
in the file.
Mode Description Action on Existing Action on File Handle
File Non-Existent File Position
'r' Read Only Opens for reading Raises an I/O Start of the file
only. error. (Default).
'r+' Read and Write Opens for both Raises an I/O Start of the file.
reading and error.
writing.
'w' Write Only Existing data is Creates a new file. Start of the file.
overwritten
(modified).
'w+' Write and Read Existing text is Creates a new file. Start of the file.
overwritten and
deleted.
'a' Append Only Opens for writing, Creates a new file. End of the file.
new data added at
the end.
'a+' Append and Allows reading and Creates a new file. End of the file.
Read writing, new data
added at the end.
3. Significance of the File Handle
A File Handle is similar to a pointer that indicates the exact location within the file where the
next read or write operation will take place. The access mode determines its initial position. The
seek(n) method can be used to explicitly move the file handle to the n^{th} byte from the start.
Answer
1. File Writing Methods
Method Purpose Data Type Accepted Key Behavior
write() To insert data as a String Inserts the string into
single string. the text file on a single
line.
writelines() To insert multiple List of Strings Takes a list of string
strings at once. elements, and each
string is added to the
text file.
2. File Reading Methods
Method Purpose Return Type Key Behavior
read() To read the entire file String Returns the entire file
content. as a single string. If a
number is specified,
reads that many
bytes/characters.
readline() To read a single line String Reads one line at a
from the file. time, up to the newline
character. Will not read
more than one line.
readlines() To read all lines from List of Strings Returns a list where
the file at once. each element is a
single line, including
the newline character
(\n).
Example of readlines() Output:
If a file contains: Hello There\n ThisisLagos\n
The output of print([Link]()) would be: ['Hello There\n', 'ThisisLagos\n', 'ThisisFcc \n']
UNIT-III: Functions, Python Strings, and Modules 🐍
1. Function Prototypes (Signatures) Explained
Q: What is a function prototype and what are its four types?
A: A function prototype (or signature) describes how a function is called, defining the presence
or absence of arguments and a return value.
● 1. No Arguments, No Return Value: Does not accept inputs or return an output.
Operation completes internally.
○ Example: def display_time(): print("9:30 AM")
● 2. Arguments, No Return Value: Accepts inputs but doesn't use a return statement.
○ Example: def calculate_area(I, w): area = I*w; print(area)
● 3. No Arguments, Return Value: Takes no input but returns a single value using return.
○ Example: def get_constant(): return 3.14
● 4. Arguments and a Return Value: Accepts inputs and processes them to return a result
(most common).
○ Example: def subtract(a, b): return a - b
2. Built-in Functions
Q: What are Built-in Functions and categorize them with examples.
A: Built-in functions are pre-defined functions provided by the Python interpreter, available
immediately for use without needing to be imported.
Category Description and Use Examples
Input/Output Used for user interaction print(), input()
(getting input) and displaying
results.
Data Type Conversion Used to convert values from int(), float(), str(), list(), tuple()
one data type to another.
Mathematical Used for basic arithmetic and abs(), sum(), min(), max()
numeric operations.
Utility Used for general tasks like len(), type(), range()
determining size or checking
type.
3. Commonly Used Modules
Q: Define a Module and list three commonly used ones with their key functions.
A: A Module is a file containing Python definitions and executable statements, imported using
the import statement for reusability and organization.
1. math Module: Provides access to advanced mathematical functions and constants.
○ Functions: sqrt(), pow(), \sin(), \cos(), \pi.
2. random Module: Used to generate pseudo-random numbers, useful for simulations
and games.
○ Functions: randint() (random integer), random() (float between 0 and 1).
3. os Module: Provides functions for interacting with the operating system, like file and
directory management.
○ Functions: getcwd() (current working directory), listdir(), remove().
a. Defining a Function
The definition starts with the def keyword, followed by the function name and parameters.
def function_name (parameter1, parameter2, ...):
"""(Docstring) Description of what the function does"""
# Block of statements/Code
return expression # Optional
b. Calling a Function
The function is executed by calling its name, followed by parentheses containing the required
arguments.
returned_value = function_name(argument1, argument2,...)
B. Operations
Method Description
[Link]() Returns a sequence of all the keys.
[Link]() Returns a sequence of all the values.
[Link](k) Removes key k and its value, returns the value.
[Link](d2) Adds all elements from dictionary d2 to dict.
2. Differentiate between Lists, Tuples, and Dictionaries
Characteristic List Tuple Dictionary
1. Primary Structure Ordered sequence of Ordered sequence of Unordered collection of
elements elements Key: Value Pairs
Characteristic List Tuple Dictionary
2. Syntax Square Brackets [] Parentheses () Curly Braces {}
3. Mutability Mutable Immutable Mutable (Values can
change; keys
immutable)
4. Access Method Index Index Key Name
5. Element Type Heterogeneous Heterogeneous Heterogeneous
elements elements Key-Value pairs
6. Method Support Supports modifying Does not support Supports structure
operations modifying operations operations (keys(),
values(), etc.)
3. Python List Concepts
(a) List Slicing and Negative Indexing
● List Slicing: Brackets and colons used to obtain a subset of the list.
○ Ex: If student = [100, "Navin", 95, 80], student[0:2] results in [100, "Navin"].
● Negative Indexing: Starts counting from the end (-1 is the last element).
○ Ex: student[-1] results in 80.
1. Differentiate between Text Files and Binary Files, and explain the
key file access modes used for writing data.
Text Files vs. Binary Files