Computer Programming, Python - Important QA)
Computer Programming, Python - Important QA)
Vadamavandal-604410.
Important questions and answers
CS25C02-Computer Programming: Python
Prepared by
[Link],
Prof. /Mech.
[Link] Question Answer
Syllabus
[Link]. Describtion
1 Introduction to Python: Problem Solving, Problem Analysis Chart, Developing an
Algorithm, Flowchart and Pseudocode, Interactive and Script Mode, Indentation,
Comments, Error messages, Variables, Reserved Words, Data Types, Arithmetic
operators and expressions, Built-in Functions, Importing from Packages.
Practical: Problem Analysis Chart, Flowchart and Pseudocode Practices. (Minimum
three)
2 Control Structures: if, if-else, nested if, multi-way if-elif statements, while loop, for
loop, nested loops, pass statements.
Practical: Usage of conditional logics in programs. (Minimum three)
3 Functions: Hiding redundancy, complexity; Parameters, arguments and return
values; formal vs actual arguments, named arguments, Recursive & Lambda
Functions.
Practical: Usage of functions in programs. (Minimum three)
4 Strings & Collections: String Comparison, Formatting, Slicing, Splitting, Stripping,
Lists, tuples, and dictionaries, basic list operators, searching and sorting lists;
dictionary literals, adding and removing keys, accessing and replacing values.
Practical: String manipulations and operations on lists, tuples, sets, and dictionaries.
(Minimum three)
5 File Operations: Create, Open, Read, Write, Append and Close files. Manipulating
directories, OS and Sys modules, reading/writing text and numbers, from/to a file;
creating and reading a formatted file (csv, tab-separated, etc.).
Practical: Opening, closing, reading and writing in formatted file format and sort data.
(Minimum three)
6 Packages: Built-in modules, User-Defined modules, Numpy, SciPy, Pandas, Scikit-
learn.
Practical: Usage of modules and packages to solve problems. (Minimum three),
Project (Minimum Two)
Unit-I
Introduction to Python
Introduction to Python
Python is a high-level, interpreted programming language that is widely used for various purposes
such as web development, scientific computing, data analysis, artificial intelligence, and more.
Basic Concepts
- Interactive Mode: Python can be used in interactive mode, where you can execute commands
one by one.
- Script Mode: Python can also be used in script mode, where you write a script and execute it.
- Indentation: Python uses indentation to define the structure of the code.
- Comments: Comments are used to explain the code and are ignored by the interpreter.
- Error Messages: Python displays error messages when there is an error in the code.
- Variables: Variables are used to store values in Python.
- Reserved Words: Python has reserved words that cannot be used as variable names.
- Data Types: Python has various data types such as integers, floats, strings, lists, tuples, and
dictionaries.
- Arithmetic Operators: +, -, , /, %, *, //
- Arithmetic Expressions: Expressions that involve arithmetic operators and operands.
Built-in Functions
- print(): Prints the output to the screen.
- input(): Takes input from the user.
- len(): Returns the length of a string or list.
- type(): Returns the data type of a variable.
# This is a comment
x = 5 # variable assignment
y = 3 # variable assignment
print(x + y) # prints 8
- Calculator Program:
- Simple Chatbot:
13 and 15 Marks QA
11. Write a Python program to solve the following problem:
A company has a list of employees with their names, ages, and salaries. Write a
program to find the average salary of employees in each age group (20-29, 30-39, 40-
49, etc.).
Solution:
import pandas as pd
# Create a DataFrame
df = [Link](data)
print(average_salaries)
Explanation:
Example Output:
Age Group
(20, 30] 52500.0
(30, 40] 62500.0
(40, 50] 75000.0
Name: Salary, dtype: float64
This program solves the problem by using pandas to manipulate and analyze the data. It
demonstrates the use of various pandas functions, including [Link](), groupby(), and
mean().
12. Create a problem analysis chart in Python to analyze the following problem:
Solution:
def display_chart(self):
print(f"Problem: {[Link]}")
print("Causes:")
for cause in [Link]:
print(f"- {cause}")
print("Effects:")
for effect in [Link]:
print(f"- {effect}")
print("Solutions:")
for solution in [Link]:
print(f"- {solution}")
# Add causes
chart.add_cause("Increased competition")
chart.add_cause("Poor marketing strategy")
chart.add_cause("Economic downturn")
# Add effects
chart.add_effect("Reduced revenue")
chart.add_effect("Job losses")
chart.add_effect("Damage to brand reputation")
# Add solutions
chart.add_solution("Improve marketing strategy")
chart.add_solution("Develop new products")
chart.add_solution("Expand into new markets")
Explanation:
Example Output:
This program creates a problem analysis chart to analyze the given problem. It
demonstrates the use of object-oriented programming concepts in Python.
13. Develop an algorithm in Python to find the maximum value in a list of numbers.
Solution:
def find_max(numbers):
# Initialize max_value to the first element of the list
max_value = numbers[0]
Explanation:
Algorithm Analysis:
Example Output:
Maximum value: 89
This algorithm finds the maximum value in a list of numbers. It demonstrates the use of
iteration and conditional statements in Python.
Algorithm Steps:
- Use the built-in max function in Python to find the maximum value in a list.
- Use a more efficient algorithm, such as the divide-and-conquer approach, for large lists.
- Modify the algorithm to find the minimum value instead of the maximum value.
14. Design a flowchart and write pseudocode for an algorithm that calculates the
average of a list of numbers.
Flowchart:
1. Start
2. Initialize sum = 0 and count = 0
3. Input a list of numbers
4. For each number in the list:
- Add the number to sum
- Increment count by 1
5. Calculate average = sum / count
6. Output average
7. End
Pseudocode:
Python Code:
def calculate_average(numbers):
sum = 0
count = 0
for num in numbers:
sum += num
count += 1
average = sum / count
return average
Explanation:
1. Easy to Understand: Flowcharts and pseudocode are easy to understand, even for non-
programmers.
2. Platform Independent: Flowcharts and pseudocode are platform independent, meaning
they can be used on any computer system.
3. Language Independent: Flowcharts and pseudocode are language independent,
meaning they can be used with any programming language.
Arithmetic Operators:
Arithmetic Expressions:
Python Code:
# Arithmetic operators
print("Addition:", 5 + 3) # Output: 8
print("Subtraction:", 10 - 4) # Output: 6
print("Multiplication:", 5 * 3) # Output: 15
print("Division:", 10 / 2) # Output: 5.0
print("Modulus:", 17 % 5) # Output: 2
print("Exponentiation:", 2 ** 3) # Output: 8
print("Floor Division:", 10 // 3) # Output: 3
# Arithmetic expression
print("(5 + 3) * 2 =", (5 + 3) * 2) # Output: 16
Explanation:
Control structures are used to control the flow of a program's execution. Python has several
control structures, including if statements, loops, and more.
if Statement
x=5
if x > 3:
print("x is greater than 3")
if-else Statement
- The if-else statement is used to execute one block of code if a condition is true, and another
block if it's false.
- Syntax: if condition: statement1 else: statement2
- Example:
x=5
if x > 3:
print("x is greater than 3")
else:
print("x is less than or equal to 3")
Nested if Statement
x=5
if x > 3:
if x > 4:
print("x is greater than 4")
else:
print("x is less than or equal to 4")
- The if-elif statement is used to check multiple conditions and execute different blocks of code.
- Syntax: if condition1: statement1 elif condition2: statement2 ... else: statementN
- Example:
x=5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
while Loop
- The while loop is used to execute a block of code repeatedly while a condition is true.
- Syntax: while condition: statement
- Example:
i=0
while i < 5:
print(i)
i += 1
for Loop
- The for loop is used to execute a block of code for each item in a sequence (such as a list or
string).
- Syntax: for variable in sequence: statement
- Example:
Nested Loops
for i in range(3):
for j in range(3):
print(i, j)
pass Statement
- The pass statement is a placeholder when a statement is required syntactically but no execution
of code is required.
- Example:
if x > 5:
pass
else:
print("x is less than or equal to 5")
- Guessing Game:
import random
number = [Link](1, 10)
guess = int(input("Guess a number: "))
while guess != number:
if guess < number:
print("Too low!")
else:
print("Too high!")
guess = int(input("Guess again: "))
print("Congratulations! You guessed it!")
- Printing a Pattern:
for i in range(5):
for j in range(i+1):
print("*", end=" ")
print()
Two mark Question and Answers
16. What is the syntax of an if statement in Python?
The syntax of an if statement in Python is if condition: statement.
17. What is the difference between if and if-else statements in Python?
The if statement is used to execute a block of code if a condition is true, while the if-else
statement is used to execute one block of code if a condition is true and another block if it
is false.
18. What is a nested if statement in Python?
A nested if statement is an if statement inside another if statement.
19. What is the syntax of a multi-way if-elif statement in Python?
The syntax of a multi-way if-elif statement in Python is if condition1: statement1 elif
condition2: statement2 ... else: statementN.
20. What is a while loop in Python?
A while loop is used to execute a block of code repeatedly while a condition is true.
21. What is a for loop in Python?
A for loop is used to execute a block of code for each item in a sequence (such as a list,
tuple, or string).
22. What is the difference between break and continue statements in Python?
The break statement is used to exit a loop, while the continue statement is used to skip
the rest of the current iteration and move to the next iteration.
23. How do you exit a loop in Python?
You can exit a loop in Python using the break statement.
24. What is the purpose of the else clause in a loop in Python?
The else clause in a loop in Python is used to execute a block of code when the loop is
finished.
25. Can you use a for loop to iterate over a dictionary in Python?
Yes, you can use a for loop to iterate over a dictionary in Python.
13 and 15 Marks QA
26. What are the control structures available in Python? Explain each control structure
with an example.
Control Structures:
x=5
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
# while loop
i=0
while i < 5:
print(i)
i += 1
# break statement
for i in range(5):
if i == 3:
break
print(i)
# continue statement
for i in range(5):
if i == 3:
continue
print(i)
# pass statement
for i in range(5):
if i == 3:
pass
print(i)
Explanation:
1. Sequence Control Structure: Executes a series of statements one after the other.
2. Selection Control Structure: Executes a block of code based on a condition.
3. Repetition Control Structure: Repeats a block of code for a specified number of times.
27. Explain the multi-way if-elif statements and while loop in Python with examples.
Syntax:
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition2 is true
elif condition3:
# code to be executed if condition3 is true
else:
# code to be executed if none of the conditions are true
Example:
x=5
if x > 10:
print("x is greater than 10")
elif x == 5:
print("x is equal to 5")
elif x < 0:
print("x is less than 0")
else:
print("x is not equal to 5 and is greater than 0")
While Loop:
The while loop is used to repeat a block of code as long as a condition is true.
Syntax:
while condition:
# code to be executed
Example:
i=0
while i < 5:
print(i)
i += 1
x=0
while x < 10:
if x == 5:
print("x is equal to 5")
elif x > 5:
print("x is greater than 5")
else:
print("x is less than 5")
x += 1
Explanation:
1. We use the multi-way if-elif statements to check multiple conditions and execute a
block of code accordingly.
2. We use the while loop to repeat a block of code as long as a condition is true.
3. We can use the multi-way if-elif statements inside a while loop to check multiple
conditions and execute a block of code accordingly.
Best Practices:
Real-World Example:
Suppose we want to create a program that asks the user to enter a number and checks if
it's a prime number. We can use the multi-way if-elif statements and while loop to
achieve this.
def is_prime(n):
if n <= 1:
return False
elif n == 2:
return True
else:
i=2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
For Loop:
The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other
iterable objects.
Syntax:
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Nested Loops:
Nested loops are used to iterate over multiple sequences or iterable objects.
Syntax:
Example:
Pass Statement:
The pass statement is used to skip a block of code or to create a placeholder when a
statement is required syntactically but no execution of code is necessary.
Syntax:
if condition:
pass
Example:
for i in range(5):
if i == 3:
pass
print(i)
Explanation:
Best Practices:
Real-World Example:
Suppose we want to create a program that asks the user to enter a number and prints the
multiplication table for that number. We can use the for loop and nested loops to achieve
this.
Functions in Python
Functions are a way to group a set of statements together to perform a specific task. They help to:
Defining a Function
def greet(name):
print("Hello, " + name + "!")
greet(name="John", age=30)
Return Values
result = add(2, 3)
print(result) # prints 5
Recursive Functions
**Lambda Functions**
- *Calculator Program*:
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
if choice == "1":
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Result:", add(x, y))
elif choice == "2":
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Result:", subtract(x, y))
elif choice == "3":
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Result:", multiply(x, y))
elif choice == "4":
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Result:", divide(x, y))
else:
print("Invalid choice!")
```
Two mark Question and Answers
29. What is the purpose of using functions in Python?
Functions are used to hide redundancy and complexity in Python programs, making them
more readable, maintainable, and efficient.
30. What is the difference between formal and actual arguments in Python?
Formal arguments are the names given to the parameters in the function definition, while
actual arguments are the values passed to the function when it is called.
31. What is the purpose of the return statement in Python?
The return statement is used to return a value from a function to the caller.
32. What is a lambda function in Python?
A lambda function is a small anonymous function that can take any number of arguments,
but can only have one expression.
33. What is the difference between named and positional arguments in Python?
Named arguments are passed to a function using the parameter name, while positional
arguments are passed in the order they are defined.
34. What is the purpose of using default arguments in Python?
Default arguments are used to provide a default value for a parameter if it is not passed
when calling the function.
35. What is the syntax for defining a function in Python?
The syntax for defining a function in Python is deffunction_name(parameters).
36. What is the purpose of using type hints in Python?
A14: Type hints are used to indicate the expected types of the function's parameters and
return value.
37. What is a recursive function in Python?
A4: A recursive function is a function that calls itself, either directly or indirectly, to
solve a problem.
38. What is the purpose of using docstrings in Python?
A13: Docstrings are used to document what a function does, what inputs it takes, and
what outputs it returns.
13 and 15 Marks QA
39. What are functions in Python? Explain the types of functions, function arguments,
and function return values with examples.
Functions:
A function is a block of code that can be executed multiple times from different parts of
your program. Functions are used to organize your code, reduce repetition, and make
your code more modular and reusable.
Types of Functions:
1. Built-in Functions: These are functions that are built into Python, such as print(), len(),
range(), etc.
2. User-defined Functions: These are functions that you define yourself using the def
keyword.
Function Arguments:
Function arguments are values that are passed to a function when it is called. There are
two types of function arguments:
1. Required Arguments: These are arguments that must be passed to a function when it is
called.
2. Default Arguments: These are arguments that have a default value and are optional.
Example:
# Define a function
def greet(name):
print(f"Hello, {name}!")
Function Types:
1. Void Function: A function that does not return a value.
2. Value-returning Function: A function that returns a value.
Example:
# Void function
def print_message():
print("Hello, World!")
# Value-returning function
def get_message():
return "Hello, World!"
Lambda Functions:
Lambda functions are small anonymous functions that can take any number of arguments,
but can only have one expression.
Example:
Example:
# Without function
print("Hello, John!")
print("Hello, Jane!")
print("Hello, Bob!")
# With function
def greet(name):
print(f"Hello, {name}!")
greet("John")
greet("Jane")
greet("Bob")
Hiding Complexity:
Functions can be used to hide complexity by encapsulating complex logic into a single
function. This makes the code more readable and maintainable.
Example:
# Without function
def calculate_area(length, width):
if length < 0 or width < 0:
raise ValueError("Length and width must be non-negative")
return length * width
# With function
def validate_dimensions(length, width):
if length < 0 or width < 0:
raise ValueError("Length and width must be non-negative")
Best Practices:
1. Keep functions short and focused: Functions should perform a single task and be short
and concise.
2. Use meaningful function names: Function names should be descriptive and indicate the
purpose of the function.
3. Use docstrings: Docstrings should be used to document functions and provide
information about their purpose and behavior.
Return Values:
A return value is the value that a function returns to the caller after executing the
function. Return values can be of any data type, including integers, strings, lists,
dictionaries, and even custom objects.
Examples:
# Single value
def add(a, b):
return a + b
x, y, z = get_coordinates()
print(x, y, z) # Output: 1 2 3
numbers = get_list()
print(numbers) # Output: [1, 2, 3]
# No value (None)
def print_message():
print("Hello, World!")
result = print_message()
print(result) # Output: None
# Custom object
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def get_person():
return Person("John", 30)
person = get_person()
print([Link], [Link]) # Output: John 30
Best Practices:
1. Use meaningful return values: Return values should be meaningful and indicate the
purpose of the function.
2. Use type hints: Use type hints to specify the return type of a function.
3. Document return values: Use docstrings to document the return values of a function.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area of the rectangle.
"""
return length * width
area = calculate_area(5, 3)
print(f"Area: {area}") # Output: Area: 15
42. What are formal and actual arguments in Python functions? How do named
arguments work? Provide examples to illustrate your answer.
Example:
Named Arguments:
Named arguments allow you to pass arguments to a function using the argument name.
This makes the code more readable and flexible.
Example:
greet(name="John", age=30)
greet(age=30, name="John") # order doesn't matter
Default Values:
You can assign default values to formal arguments. These values are used if the actual
argument is not provided.
Example:
def greet(*names):
for name in names:
print(f"Hello, {name}!")
def greet(**kwargs):
for name, age in [Link]():
print(f"Hello, {name}! You are {age} years old.")
Best Practices:
1. Use meaningful argument names: Argument names should be descriptive and indicate
the purpose of the argument.
2. Use default values: Default values can make the function more flexible and easier to
use.
3. Use named arguments: Named arguments can make the code more readable and reduce
errors.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area of the rectangle.
"""
return length * width
Recursive Functions:
A recursive function is a function that calls itself during execution. The process of
recursion has two main components:
1. Base Case: A trivial case that can be solved directly, stopping the recursion.
2. Recursive Case: A case that requires the function to call itself to solve the problem.
Example:
def factorial(n):
if n == 0: # base case
return 1
else:
return n * factorial(n-1) # recursive case
Lambda Functions:
A lambda function is a small anonymous function that can take any number of arguments,
but can only have one expression.
Syntax:
Example:
Best Practices:
1. Use lambda functions for simple operations: Lambda functions are best suited for
simple, one-time use cases.
2. Avoid complex lambda functions: Complex lambda functions can be difficult to read
and debug.
3. Use meaningful variable names: Use descriptive variable names to make the code more
readable.
Strings
String Comparison
String Formatting
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
- Using f-strings:
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
String Slicing
s = "hello"
print(s[1:3]) # prints "el"
String Splitting
s = "hello world"
print([Link]()) # prints ["hello", "world"]
String Stripping
Lists
- +: concatenation
- *: repetition
- len(): length
- Example:
Dictionaries
Dictionary Literals
Strings:
A string is a sequence of characters, such as letters, numbers, and symbols, enclosed in
quotes (single, double, or triple quotes).
Example:
Collections:
A collection is a data structure that can store multiple values. Python has several types of
collections:
Operations on Collections:
1. Indexing: Accessing a specific element in a collection using its index.
- Example: my_list[0] or my_tuple[1]
2. Slicing: Extracting a subset of elements from a collection.
- Example: my_list[1:3] or my_tuple[1:]
3. Concatenation: Combining two or more collections.
- Example: my_list + [6, 7, 8] or my_tuple + (6, 7, 8)
4. Membership Testing: Checking if an element is in a collection.
- Example: 5 in my_list or 5 in my_set
Best Practices:
1. Use meaningful variable names: Collection variable names should be descriptive and
indicate the type of collection.
2. Use type hints: Use type hints to specify the type of collection.
3. Use collection methods: Collection methods, such as append(), extend(), and sort(), can
simplify code and improve readability.
String Comparison:
Python provides several ways to compare strings:
String Formatting:
Python provides several ways to format strings:
Example:
name = "John"
age = 30
# Using concatenation
print("Hello, " + name + "! You are " + str(age) + " years old.")
# Using [Link]()
print("Hello, {}! You are {} years old.".format(name, age))
Best Practices:
1. Use f-strings: f-strings are the most readable and efficient way to format strings in
Python.
2. Use meaningful variable names: Variable names should be descriptive and indicate the
purpose of the variable.
3. Avoid concatenating strings: Concatenating strings can be inefficient and hard to read.
Tuples:
A tuple is an immutable, ordered collection of values. Tuples are defined using
parentheses ().
Characteristics:
Creation:
my_tuple = (1, 2, 3, 4, 5)
my_tuple = 1, 2, 3, 4, 5 # parentheses are optional
Common Operations:
Dictionaries:
A dictionary is a mutable, unordered collection of key-value pairs. Dictionaries are
defined using curly braces {}.
Characteristics:
Creation:
Common Operations:
- Key Access: my_dict["name"] returns the value associated with the key.
- Key Assignment: my_dict["name"] = "Jane" updates the value associated with the key.
- Key Deletion: del my_dict["name"] removes the key-value pair.
- Iteration: for key, value in my_dict.items(): iterates over key-value pairs.
Best Practices:
1. Use meaningful variable names: Variable names should be descriptive and indicate the
purpose of the variable.
2. Use type hints: Use type hints to specify the type of collection.
3. Avoid modifying tuples: Tuples are immutable, so avoid modifying them.
4. Use dictionary methods: Dictionary methods, such as get() and update(), can simplify
code and improve readability.
Searching Lists:
Python provides several ways to search lists:
Sorting Lists:
Python provides several ways to sort lists:
Example:
my_list = [3, 1, 2, 4, 5]
# Indexing
print(my_list[0]) # Output: 3
# Slicing
print(my_list[1:3]) # Output: [1, 2]
# Concatenation
print(my_list + [6, 7, 8]) # Output: [3, 1, 2, 4, 5, 6, 7, 8]
# Repetition
print(my_list * 2) # Output: [3, 1, 2, 4, 5, 3, 1, 2, 4, 5]
# Membership
print(3 in my_list) # Output: True
# Index
print(my_list.index(3)) # Output: 0
# Count
print(my_list.count(3)) # Output: 1
# Sort
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4, 5]
# Sorted
print(sorted(my_list)) # Output: [1, 2, 3, 4, 5]
# Reverse
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
Best Practices:
1. Use meaningful variable names: Variable names should be descriptive and indicate the
purpose of the variable.
2. Use type hints: Use type hints to specify the type of list.
3. Avoid modifying lists: Lists are mutable, so avoid modifying them unnecessarily.
4. Use list methods: List methods, such as append() and extend(), can simplify code and
improve readability.
def find_max(numbers):
return max(numbers)
numbers = [3, 1, 2, 4, 5]
print(find_max(numbers)) # Output: 5
58. How do you add and remove keys from a dictionary in Python? Provide examples to
illustrate your answer.
Adding Keys:
You can add a new key to a dictionary using the following methods:
1. Assignment: Assign a value to a new key.
- Example: my_dict["new_key"] = "new_value"
2. update() method: Update the dictionary with new key-value pairs.
- Example: my_dict.update({"new_key": "new_value"})
3. setdefault() method: Set a default value for a key if it doesn't exist.
- Example: my_dict.setdefault("new_key", "default_value")
Removing Keys:
You can remove a key from a dictionary using the following methods:
Example:
# Remove a key
del my_dict["age"]
print(my_dict) # Output: {'name': 'John', 'country': 'USA', 'city': 'New York', 'state': 'NY'}
Best Practices:
1. Use meaningful variable names: Variable names should be descriptive and indicate the
purpose of the variable.
2. Use type hints: Use type hints to specify the type of dictionary.
3. Avoid modifying dictionaries: Dictionaries are mutable, so avoid modifying them
unnecessarily.
4. Use dictionary methods: Dictionary methods, such as get() and update(), can simplify
code and improve readability.
users = {}
add_user(users, "john", "john@[Link]")
print(users) # Output: {'john': 'john@[Link]'}
Unit-V
File Operations
File Operations
- Create: Create a new file using the open() function with the 'w' mode.
- Open: Open an existing file using the open() function with the 'r' mode.
- Read: Read from a file using the read() method.
- Write: Write to a file using the write() method.
- Append: Append to a file using the write() method with the 'a' mode.
- Close: Close a file using the close() method.
Example
Manipulating Directories
- OS Module: The os module provides functions for working with directories and files.
- Sys Module: The sys module provides functions for interacting with the Python interpreter.
Example
import os
- Reading Text: Use the read() method to read text from a file.
- Writing Text: Use the write() method to write text to a file.
- Reading Numbers: Use the read() method to read numbers from a file and convert them to
integers or floats.
- Writing Numbers: Use the write() method to write numbers to a file after converting them to
strings.
Example
- CSV Files: Use the csv module to read and write CSV files.
- Tab-Separated Files: Use the csv module with the delimiter='\t' argument to read and write tab-
separated files.
Example
import csv
File Operations:
Python provides several functions for performing file operations:
Example:
Best Practices:
1. Use the with statement: The with statement automatically closes the file when you're
done with it.
- Example: with open("[Link]", "r") as file:
2. Check if the file exists: Use the [Link]() function to check if the file exists
before trying to open it.
- Example: if [Link]("[Link]"):
3. Handle exceptions: Use try-except blocks to handle exceptions that may occur during
file operations.
- Example: try: file = open("[Link]", "r") except FileNotFoundError: print("File
not found")
def read_file(file_name):
try:
with open(file_name, "r") as file:
contents = [Link]()
return contents
except FileNotFoundError:
print("File not found")
return None
print(read_file("[Link]"))
File Modes:
70. How do you create, open, and read files in Python? Explain the different modes of
file opening and provide examples.
Creating Files:
You can create a new file in Python using the open() function with the w or x mode.
- w mode: Creates a new file if it doesn't exist, or overwrites the existing file.
- x mode: Creates a new file if it doesn't exist, but raises a FileExistsError if the file
already exists.
Example:
Opening Files:
You can open an existing file in Python using the open() function with the r mode.
Example:
Reading Files:
You can read the contents of a file using the read() method.
Example:
def read_file(file_name):
try:
with open(file_name, "r") as file:
contents = [Link]()
return contents
except FileNotFoundError:
print("File not found")
return None
print(read_file("[Link]"))
71. How do you write, append, and close files in Python? Explain the different modes of
file opening and provide examples.
Writing Files:
You can write to a file in Python using the write() method.
- w mode: Opens the file for writing, truncating the existing content.
- x mode: Creates a new file for writing, raising a FileExistsError if the file already exists.
Example:
# Write to a file
with open("[Link]", "w") as file:
[Link]("Hello, World!")
Appending Files:
You can append to a file in Python using the a mode.
- a mode: Opens the file for appending, adding new content to the end of the file.
Example:
# Append to a file
with open("[Link]", "a") as file:
[Link]("This is appended text.\n")
Closing Files:
You can close a file in Python using the close() method.
Example:
# Open a file
file = open("[Link]", "r")
Best Practices:
1. Use the with statement: The with statement automatically closes the file when you're
done with it.
2. Check if the file exists: Use the [Link]() function to check if the file exists
before trying to open it.
3. Handle exceptions: Use try-except blocks to handle exceptions that may occur during
file operations.
File Modes:
72. How do you manipulate directories and use the OS and Sys modules in Python?
Explain the different functions and provide examples.
Manipulating Directories:
You can manipulate directories in Python using the os module.
Example:
import os
OS Module:
The os module provides a way to use operating system dependent functionality.
Example:
import os
**Sys Module:**
--------------
**Example:**
python
import sys
## Best Practices:
1. *Use the `os` module:* The `os` module provides a way to use operating system
dependent functionality.
2. *Use the `sys` module:* The `sys` module provides access to system-specific
parameters and functions.
3. *Handle exceptions:* Use try-except blocks to handle exceptions that may occur
during file operations.
import os
import sys
def create_dir(dir_name):
try:
[Link](dir_name)
except FileExistsError:
print(f"Directory {dir_name} already exists")
[Link](1)
create_dir("example_dir")
```
73. How do you read and write text and numbers to files in Python? Explain the
different methods and provide examples.
Example:
Example:
# Write to a text file
with open("[Link]", "w") as file:
[Link]("Hello, World!")
Example:
Example:
Best Practices:
1. Use the with statement: The with statement automatically closes the file when you're
done with it.
2. Handle exceptions: Use try-except blocks to handle exceptions that may occur during
file operations.
3. Use type conversions: Use type conversions to convert strings to numbers and vice
versa.
def read_numbers(file_name):
try:
with open(file_name, "r") as file:
numbers = [int(line) for line in [Link]()]
return numbers
except FileNotFoundError:
print("File not found")
return []
numbers = read_numbers("[Link]")
print(numbers)
Unit-VI
File Operations
Packages in Python
- Built-in Modules: Python has a vast collection of built-in modules that provide various
functionalities, such as math, statistics, random, etc.
- User-Defined Modules: You can create your own modules by saving a Python file with a .py
extension and importing it in another Python file.
Importing Modules
Example
import math
print([Link])
import math as m
print([Link])
Popular Packages
Numpy
- Arrays: Numpy arrays are similar to Python lists but are more efficient for numerical
computations.
- Vectorized Operations: Numpy provides vectorized operations that allow you to perform
operations on entire arrays at once.
Example
import numpy as np
Pandas
Example
import pandas as pd
# Access a column
print(df['Name'])
# Access a row
print([Link][0])
Scikit-learn
- Machine Learning: Scikit-learn provides a wide range of machine learning algorithms, including
classification, regression, clustering, etc.
- Datasets: Scikit-learn provides several built-in datasets for testing and training machine learning
models.
Example
Creating Packages:
To create a package, you need to create a directory with an __init__.py file inside it. The
__init__.py file can be empty, but it's required to make the directory a package.
mypackage/
__init__.py
[Link]
[Link]
subpackage/
__init__.py
[Link]
Importing Packages:
You can import packages using the import statement.
Example:
import mypackage
import mypackage.module1
from mypackage import module1
Types of Packages:
- Standard Packages: These are packages that come with Python, such as math and os.
- Third-Party Packages: These are packages created by other developers and can be
installed using pip, such as numpy and pandas.
- Local Packages: These are packages created by you and are not installed globally, such
as a package in your project directory.
Managing Packages:
You can manage packages using pip, the Python package manager.
Best Practices:
1. Use meaningful package names: Package names should be descriptive and follow PEP
8 conventions.
2. Use version control: Use version control systems like Git to manage your packages.
3. Document your packages: Use docstrings and comments to document your packages
and modules.
4. Test your packages: Write tests for your packages and modules to ensure they work
correctly.
# mypackage/__init__.py
from .module1 import function1
from .module2 import function2
# mypackage/[Link]
def function1():
print("Hello from function1")
# mypackage/[Link]
def function2():
print("Hello from function2")
# [Link]
from mypackage import function1, function2
Answer: Python has a vast collection of built-in modules that provide a wide range of
functionalities, from basic mathematical operations to advanced data structures and
networking capabilities. Some of the most commonly used built-in modules in Python
include:
import math
import os
import random
import time
1. Import the module using the import statement (e.g., import mymodule).
2. Use the functions, classes, and variables defined in the module.
Example Use Case:
Let's create a user-defined module called math_operations.py that contains some basic
mathematical functions:
# math_operations.py
# [Link]
import math_operations
result = math_operations.add(2, 3)
print(result) # Output: 5
result = math_operations.subtract(5, 2)
print(result) # Output: 3
Best Practices:
1. Use meaningful module names: Use descriptive and concise names for your modules.
2. Use docstrings: Use docstrings to document your modules, functions, and classes.
3. Organize related code: Group related functions and classes together in a single module.
87. What are the key features and use cases of the Numpy, SciPy, and Pandas packages
in Python, and how can they be used to perform numerical computations, scientific
computing, and data analysis tasks?
Answer: Numpy, SciPy, and Pandas are three popular packages in Python that are widely
used for numerical computations, scientific computing, and data analysis tasks.
- Numpy: Numpy (Numerical Python) is a package for working with arrays and
mathematical operations. It provides support for large, multi-dimensional arrays and
matrices, and provides a wide range of high-performance mathematical functions for
manipulating them.
- SciPy: SciPy (Scientific Python) is a package for scientific computing that provides
functions for tasks such as signal processing, linear algebra, optimization, and statistics. It
is built on top of Numpy and extends its capabilities to provide more advanced scientific
computing functionality.
- Pandas: Pandas is a package for data manipulation and analysis. It provides data
structures such as Series (1-dimensional labeled array) and DataFrame (2-dimensional
labeled data structure with columns of potentially different types), and provides various
functions for data manipulation, analysis, and visualization.
1. Numpy:
- Array Operations: Numpy provides support for large, multi-dimensional arrays and
matrices, and provides a wide range of high-performance mathematical functions for
manipulating them.
- Linear Algebra: Numpy provides functions for performing linear algebra operations
such as matrix multiplication, eigenvalue decomposition, and singular value
decomposition.
- Random Number Generation: Numpy provides functions for generating random
numbers and arrays.
2. SciPy:
- Signal Processing: SciPy provides functions for signal processing tasks such as
filtering, convolution, and Fourier transforms.
- Optimization: SciPy provides functions for optimization tasks such as minimization,
maximization, and curve fitting.
- Statistics: SciPy provides functions for statistical analysis tasks such as hypothesis
testing, confidence intervals, and regression analysis.
3. Pandas:
- Data Manipulation: Pandas provides functions for data manipulation tasks such as
filtering, sorting, grouping, and merging.
- Data Analysis: Pandas provides functions for data analysis tasks such as data
cleaning, data transformation, and data visualization.
- Data Visualization: Pandas provides functions for data visualization tasks such as
plotting and charting.
1. Numpy:
import numpy as np
2. SciPy:
# Generate a signal
t = [Link](0, 1, 1000)
x = [Link](2 * [Link] * 10 * t) + 0.5 * [Link](2 * [Link] * 20 * t)
# Apply a filter
b, a = [Link](4, 0.1)
y = [Link](b, a, x)
# Plot the signal and the filtered signal
import [Link] as plt
[Link](t, x)
[Link](t, y)
[Link]()
3. Pandas:
import pandas as pd
Key Features:
Common Algorithms:
# Make predictions
y_pred = [Link](X_test)
Best Practices:
1. Data Preprocessing: Always preprocess your data before feeding it into a machine
learning model.
2. Model Selection: Use cross-validation to select the best model for your dataset.
3. Hyperparameter Tuning: Use grid search or random search to tune the hyperparameters
of your model.
4. Evaluation Metrics: Use evaluation metrics such as accuracy, precision, recall, and F1-
score to evaluate the performance of your model.