0% found this document useful (0 votes)
3 views19 pages

Python 3rd

Python is a high-level, interpreted programming language developed by Guido Van Rossum in 1989, known for its simplicity and versatility. It supports various programming paradigms, including object-oriented programming, and is widely used in applications such as web development, data science, and artificial intelligence. Key concepts include variables, data types, control statements, and file handling, with built-in functions for operations like reading and writing files.

Uploaded by

samkampro
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)
3 views19 pages

Python 3rd

Python is a high-level, interpreted programming language developed by Guido Van Rossum in 1989, known for its simplicity and versatility. It supports various programming paradigms, including object-oriented programming, and is widely used in applications such as web development, data science, and artificial intelligence. Key concepts include variables, data types, control statements, and file handling, with built-in functions for operations like reading and writing files.

Uploaded by

samkampro
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

1. What is Python?

Python is a general-purpose, dynamic, high-level, and interpreted programming language. It


supports Object Oriented programming approach to develop applications. It is simple and easy
to learn and provides lots of high-level data structures.
2. Who developed Python and when?
Python was developed by Guido Van Rossum at CWI, Netherlands in December 1989 and its first
version 0.9.0 was released in February 1991.
3. Why the name Python?
Guido Van Rossum named it after the popular BBC comedy series “Monty Python’s Flying
Circus”.
4. List some features of Python.
Easy to Learn and Use, Expressive Language, Interpreted, Object Oriented, Open Source,
Extensible, Large Standard Library, Cross-Platform, GUI Support, Integrated and Dynamic Memory
Allocation.
5. What are the applications of Python?
Python is used in Web Applications, Desktop Applications, Data Science, Artificial Intelligence,
Machine Learning, Scientific Computing, Robotics, IoT, and Gaming.
6. Define Variable.
A Variable is a named location in memory used to store data while the program is being
executed.
7. Define Constant.
A Constant is a variable whose value cannot be changed throughout the program.
8. Define Literal.
Literals are raw data given in a variable or constant. Example: Numeric, String, Boolean, Special
and Collection Literals.
9. Give examples of Numeric Literals.
Numeric Literals are Integer, Float and Complex numbers. Example: a=30, b=40.67, c=10+4j.
10. What are Boolean Literals?
Boolean Literals have only two values True or False, where True is 1 and False is 0.
11. What are String Literals?
A String Literal is a sequence of characters surrounded by single, double or triple quotes.
12. Define Identifiers.
An Identifier is a name given to variables, functions, classes or modules in Python. Identifiers are
case-sensitive.
13. Mention rules for naming Identifiers.
Identifiers can contain letters, digits and underscores, must not start with a digit, must not
contain special symbols and should not use keywords.
14. What are Keywords?
Keywords are predefined and reserved words that have special meanings in Python and cannot
be used as identifiers.
15. Give examples of Keywords.
Examples: and, or, not, if, else, for, while, break, class, def, return, import, True, False, None.
16. What is Indentation in Python?
Indentation refers to spaces used at the beginning of a line to define a block of code.
17. What is a Comment in Python?
A Comment is a non-executable statement written using ‘#’ symbol to describe the code.
18. What are Python Operators?
Operators are special symbols used to perform operations on variables and values.
19. What are the types of Python Operators?
Arithmetic, Assignment, Comparison, Logical, Bitwise and Special Operators.
20. What is Type Conversion in Python?
Type Conversion means changing the data type of a variable into another type using built-in
functions like int(), float(), str(), etc.
21. What are the advantages of Python?
Python is easy to learn, portable, extensible, has a large standard library, and supports object-
oriented and dynamic memory management.
22. What is meant by Interpreted Language?
In Python, code is executed line by line using an interpreter, so no separate compilation is
needed.
23. What is meant by Object Oriented Language?
Python supports object-oriented features like classes, objects, inheritance, polymorphism, and
encapsulation.
24. What is Dynamic Memory Allocation?
Python automatically manages and allocates memory space at runtime depending on the
variable type.
25. What are Built-in Data Types in Python?
Numbers, String, List, Tuple, Dictionary, Set, and Boolean.
26. Define List with example.
List is an ordered, mutable collection of elements enclosed in square brackets. Example: list1 =
[1, “hi”, 2].
27. Define Tuple with example.
Tuple is an ordered, immutable collection of elements enclosed in parentheses. Example: tup =
(1, 2, 3).
28. Define Dictionary with example.
Dictionary stores data as key–value pairs enclosed in curly braces. Example: d = {1:'John',
2:'Alex'}.
29. Define Set with example.
Set is an unordered collection of unique elements enclosed in curly braces. Example: set1 =
{'a','b','c'}.
30. What is meant by Data Type?
Data Type defines the type of data a variable holds such as int, float, string, list, tuple, etc.
31. What is an Expression in Python?
An expression is a combination of operators, constants, and variables that produces a result.
32. What is meant by Output Statement?
Output statement is used to display values using the print() function.
33. What is meant by Input Statement?
Input statement is used to accept data from the user using the input() function.
34. Write the syntax of print() function.
Syntax: print(value(s), sep=' ', end='\n')
35. Write the syntax of input() function.
Syntax: input(prompt)
1. What are control statements in Python?
In any programming language, a program may execute sequentially, selectively, or iteratively.
Every programming language provides constructs to support sequence, selection, and iteration.
In Python, all these constructs are called control statements that control the flow of execution of
a program.
2. What are the main types of control statements in Python?
Python has three types of control statements: selection (branching) statements, iteration
(looping) statements, and jumping (break / continue) statements.
3. What is a conditional control construct?
A conditional control construct supports selection and iteration. It allows a program to execute a
block of code when a particular condition is true.
4. What is an unconditional control construct?
An unconditional control construct does not depend on a condition. It includes pass, break,
continue, exit(), and quit() statements that control the flow directly.
5. What are the different types of selection statements in Python?
Python has four types of selection statements: if statement, if-else statement, ladder if-else (if-
elif-else) statement, and nested if statement.
6. What is the syntax of an if statement?
if (condition):
statements * When the condition becomes true, the block of statements is executed.
7. What is an example of an if statement?
age = int(input("Enter Age: "))
if (age >= 18):
print("You are eligible for vote")
8. What is the purpose of an if-else statement?
The if-else statement consists of one condition and two blocks. When the condition is true, the
first block executes; otherwise, the else block executes.
9. Write the syntax of an if-else statement.
if (condition):
statements
else:
statements
10. What is a ladder if-else statement?
A ladder if-else (if-elif-else) statement is a multi-decision construct that tests multiple conditions
one after another using elif clauses.
11. Write the syntax of ladder if-else statement.
if (condition1):
statements
elif (condition2):
statements
else:
statements
12. What is a nested if statement?
It is a construct where one if condition is placed inside another if condition. The inner block
executes only when both conditions are true.
13. Write an example of a nested if statement.
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")
14. What are iteration statements in Python?
Iteration statements or looping constructs are used to execute a block of statements repeatedly
until a condition becomes false.
15. What are the types of iteration statements in Python?
Python supports two types of iteration statements: while loop and for loop.
16. Write the syntax of a while loop.
initialization
while (condition):
statements
update
17. What is the use of the range() function?
The range() function returns a sequence of numbers starting from a given start value up to, but
not including, a stop value with an optional step value.
18. What is the purpose of else in a loop?
The else block in a loop is executed when the loop finishes normally without being terminated by
a break statement.
19. What is the pass statement?
The pass statement does nothing; it is used to complete the syntax where a statement is
required but no action needs to be performed.
20. What is the difference between break and continue statements?
The break statement terminates the loop completely, while the continue statement skips the
current iteration and proceeds to the next iteration of the loop.
19. What is the purpose of the__name__ variable in Python?
__name__ is a special variable. If a file is run directly, __name__= __main__. If imported, its value
is the module name.
20. What are Variable Length Arguments (*args)?
Allows a function to accept any number of arguments beyond the defined ones. These are
received as a Tuple.
1. What is a sequence data type in Python? A sequence is a datatype that represents a group of
elements, and its purpose is to store and process these elements. In Python, strings, lists, tuples,
and dictionaries are very important sequence datatypes.
2. Define a List in Python. A list is similar to an array and consists of a group of elements or
items. Unlike an array, a list is more versatile because it can store different types of elements
(heterogeneous data types).
3. What is the major difference between an array and a list in Python? An array can store only one
type of element (homogeneous), whereas a list can store different types of
elements (heterogeneous).
4. How is a List created? Give an example. A list is created by putting different comma-separated
values between square brackets []. Example: student = [556, "Mothi", 84, 96, 84, 75, 84]
5. How do you create an empty list? An empty list can be created without any elements by simply
writing empty square brackets, as in student = [].
6. Are Lists mutable or immutable? Lists are mutable. This means that their contents can be
modified by appending, updating, or deleting the elements after the list is created.
7. What is appending an element to a list, and which method is used? Appending an element
means adding an element at the end of the list. To append an element, the append() method is
used.
8. How can you update an element in a List? This is done by accessing the specific element
using indexing or slicing and assigning a new value to it. Example: lst[2] = 5 updates the element
at index 2.
9. Which statement is used to delete an element from a list? The del statement is used to delete
an element from the list, and it requires the position number of the element to be deleted.
10. Explain List Concatenation with an example. List concatenation is performed using the +
operator on two lists to join them. If x and y are two lists, x + y joins list y at the end of list x.
Example: [10, 20] + [40, 50] results in [10, 20, 40, 50].
11. How is List Repetition achieved? The elements of a list can be repeated a number of times
using the multiplication * operator. Example: x * 2 repeats the elements in list x
twice.
12. What is List Aliasing? Aliasing is giving a new name to an existing list using the assignment
operator (=). Since both names point to the same object, any modification done to one name (the
alias) will also modify the other name (the original list).
13. What is List Cloning? Cloning is obtaining an exact copy of an existing list. This is done using
the slicing operation [:] (e.g., y = x[:]), which ensures the lists x and y are independent, and
modifications to one will not affect the other.
14. Give the function and purpose of len() and [Link](x) methods.?* len(lst): Returns the
number of elements in the list.
*[Link](x): Returns the number of occurrences of element x in the list.
1. Define a Tuple in Python. A tuple is a Python sequence that stores a group of elements. Tuples
are similar to lists, but the main difference is that tuples are immutable.
2. How do you create a tuple with only a single element? To create a tuple with only one element,
you must mention that element in parentheses and a comma is needed after the element (e.g.,
tup = (10,)). In the absence of the comma, Python treats it as an
ordinary data type (like an integer).
3. Define a Dictionary in Python. A dictionary represents a group of elements arranged in the
form of key-value pairs. The key and its value are separated by a colon (:), and all pairs are
inserted in curly braces {}.
4. What are the two main rules for Dictionary keys? The keys in a dictionary must obey the
following rules:
○ Keys should be unique: Duplicate keys are not allowed; entering the same key again will
overwrite the old key's value.
○ Keys should be an immutable type: Keys must be immutable types like numbers, strings, or
tuples; lists or dictionaries cannot be used as keys.
1. What is the fundamental concept of File Handling in Python? File handling is an integral part
of programming that allows performing various operations on files, such as creating, opening,
closing, reading, writing, and appending information. Python simplifies this with built-in methods.
2. What is the default mode for opening files in Python, and where is the file handle located in
this mode? The default mode for opening files is Read Only ('r'). In this mode, the file handle is
located at the start of the file.
3. How does the 'w' (Write Only) mode handle a file that already exists? If the file already exists,
the 'w' (Write Only) mode modifies and overwrites the existing data. If the file does not already
exist, a new one gets created.
4. What happens when you try to open a non-existent file using the 'r' (Read Only) or 'r+' (Read
and Write) modes? If the file does not exist, both the 'r' (Read Only) mode and the 'r+' (Read and
Write) mode will raise an I/O error.
6. Where is the file handle positioned when a file is opened using the 'a' (Append Only) mode?
When a file is opened using the 'a' (Append Only) mode, the handle is set at the end of the file.
Any newly written data will be added at the end, following the previously written data.
7. Differentiate between the write() and writelines() methods. The write() method inserts a single
string into the text file on a single line. The writelines() method inserts multiple strings at the
same time by taking a list of string elements and adding each string to the text file.
8. What is the purpose of the newline character (\backslash n) when writing data to a file? The
\backslash n (newline character) is placed in the string to indicate the end of the line. This helps
ensure that subsequent text starts on a new line in the file.
9. What is the primary function of the read() method without any arguments? When no argument
is specified, the read() function reads the entire file and returns the content as a string.
10. How does the readline() method limit the amount of data it reads? The readline() method
reads a single line from a file and returns it as a string. While it can read at most n bytes if n is
specified, it does not read more than one line even if n is greater than the line's length.
11. What data structure does the readlines() method return? The readlines() method reads all of
the lines in the file and returns them as a list of string elements, with one string for each line.
12. Why is it considered good practice to use the close() function? It is considered good practice
to always call the close() function when you are done with the file. This function tells Python that
you are finished with that section (creating or reading).
13. What is the significance of the 'a+' (Append and Read) mode regarding file position? The 'a+'
mode allows both reading and writing. The file handle is set at the end of the file, meaning any
new text written will be appended to the end.
14. What is a "file handle," and what controls the activities you can perform on an opened file? A
file handle is similar to a pointer that indicates where data should be read or put into the file. The
activities you can perform on the opened file are controlled by Access Modes.
15. What does the seek(n) function do? The seek(n) function takes the file handle to the n^{th}

🖌️
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.

Q.2: Differentiate between the three file Reading methods (read(),


readline(), readlines()) and the two file Writing methods (write(),
writelines()) in Python.

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().

4. Local vs. Global Variables


Q: Differentiate between Local and Global Variables based on definition, scope, and
modification.
Feature Global Variable Local Variable
Definition Defined outside all functions in Defined inside a specific
the main body of the program. function.
Scope Accessible from any part of the Accessible only within the
program. function where it is defined.
Modification Must use the global keyword Can be modified directly inside
inside a function to modify its the defining function.
value.
5. Defining and Calling a User-defined Function
Q: Explain the purpose of a function and provide the syntax for defining and calling it.
A: A Function is a named, reusable block of code designed to perform a specific task, essential
for modularizing code and improving readability.

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,...)​

6. Types of Function Arguments


Q: List and explain the four main types of function arguments.
A: Function arguments are inputs passed to a function.
●​ a. Required Arguments (Positional): Arguments that must be present in the function
call, mapped based on their position/order.
○​ Rule: Number and order of arguments passed must exactly match the parameters
defined.
○​ Example: create_user("sam", "sam@[Link]")
●​ b. Default Arguments: Arguments assigned a default value in the function definition. If
omitted in the call, the default is used.
○​ Rule: Must be defined after all Required Arguments.
○​ Example: def log_event (message, level="INFO"):
●​ c. Keyword Arguments: Identified by their parameter name during the function call
(e.g., param=value).
○​ Benefit: Allows arguments to be passed in an arbitrary order.
○​ Example: configure_db(password="p@ss", host="localhost", user="admin")
●​ d. Variable Length Arguments: Used when the number of arguments is not fixed.
○​ i. Non-Keyword Variable Length (*args): Accepts any number of positional
(unnamed) arguments. Collected as a tuple.
■​ Example: display_scores ("Riya", 85, 92, 77)
○​ ii. Keyword Variable Length (**kwargs): Accepts any number of keyword (named)
arguments. Collected as a dictionary.

💾 Python Dictionary and List Concepts


■​ Example: profile(name="Sam", age=30, city="Delhi")

1. Structure and Rules of a Python Dictionary


A. Structure and Rules

●​ A Dictionary is an unordered collection of key-value pairs, enclosed in {}.


●​ Key and value are separated by a colon (:). Key-value pairs are separated by a comma
(,).
●​ Keys must be immutable (number, string, tuple).
●​ Values can be any data type (heterogeneous).

B. Operations

1.​ Creating: Key-value pairs inside curly braces.


○​ Ex: Regd_No={'Reg1':101, 'Reg2':102, 'Reg3':103}
2.​ Accessing: Value retrieved using its corresponding key inside []. No indexing/slicing.
○​ Ex: print(Regd_No['Reg3']) displays 103.
3.​ Inserting/Updating: Inserted by new key/value assignment. Value is updated if the key
exists.

C. Built-in Dictionary Methods (Four Examples)

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.

(b) Aliasing vs. Cloning

Feature Aliasing (list_b = list_a) Cloning (list_b = list_a[:])


Concept One object, two references. Two independent objects.
Operation Assignment operator = Slice notation [:] or [Link]()
Modification Effect Change to list_a will modify Change to list_a will not
list_b. modify list_b.
(c) Two List Methods and their functions

1.​ [Link](x): Appends element x at the end.


○​ Ex: If list = [1, 2], [Link](3) makes list become [1, 2, 3].
2.​ [Link](iterable): Extends list by appending all items from the iterable.

📝 Python File Handling: Core Concepts


○​ Ex: If list = [1, 2], [Link]([3, 4]) makes list become [1, 2, 3, 4].

1. Differentiate between Text Files and Binary Files, and explain the
key file access modes used for writing data.
Text Files vs. Binary Files

Feature Text File Binary File


Storage Human-readable characters; Raw byte stream; no EOL
uses EOL (\n) marker. marker.
Translation Automatic encoding/decoding No translation; stored as-is in
(e.g., UTF-8). bytes.
[Link]. Question Answer
1. Define a Function in Python. A Function is a block of organized, reusable code that is
designed to perform a specific task. It promotes code reusability
and program modularity.
2. Write the general Syntax for a User-defined functions are created using the def keyword.
user-defined function. Syntax: def function_name(list_of_parameters): statement(s)
3. What is a Built-in Function? Built-in functions are functions that are pre-defined in the Python
Give an example. interpreter and are always available for use. Examples: print(),
len(), input(), max(), min().
4. Differentiate between Global Global Variable: Defined outside any function. It can be accessed
and Local Variable. anywhere in the program. Local Variable: Defined inside a
function. It is only accessible within that specific function.
5. What is the purpose of the The return statement is used to send a value back from the
return statement? function to the calling environment. It also signifies the
termination of the function's execution.
6. What is a Void Function? A Void Function is a function that does not explicitly use a return
statement. By default, these functions return the special value
None.
7. Explain Keyword Arguments. Keyword Arguments are arguments passed to a function call
where the value is preceded by the parameter name (e.g.,
name='Ajith'). This allows arguments to be passed out of order.
8. Explain Default Arguments. Default Arguments are parameters assigned a default value in
the function definition. If no value is provided during the function
call, the default value is used.
9. What is Recursion? Recursion is the process where a function calls itself, either
directly or indirectly. It is often used to solve complex problems
by breaking them down into simpler, repeatable sub-problems
(e.g., Factorial calculation).
10. Explain String Immutability in String is an Immutable data type. Once created, its content
Python. cannot be changed. Any modification results in a new string.
11. What is String Concatenation? Joining two or more strings together using the + operator.
Example: 'Py' + 'thon' = 'Python'.
12. What is String Repetition? Repetition prints a given string multiple times using the *
operator. Example: 'A' * 4 = 'AAAA'.
13. What is String Indexing? Indexing accesses individual characters using their position.
Forward index starts at 0, backward at -1.
14. Write the Syntax for String Syntax: string[start : end : step]
Slicing.
15. What is a Module in Python? A Module is a .py file containing Python definitions and
statements like functions, classes, and variables.
16. What is the Syntax to Import a import modulename OR from modulename import specific_name
Module?
17. What is the use of the dir() The dir() function returns a list of names (attributes, functions,
function? variables) in a module or namespace.
18. What is a Namespace? A Namespace is a naming system ensuring names are unique
and do not conflict.

You might also like