Python imp Q&A
Python imp Q&A
# Expressions (Arithmetic)
sum_ab = a + b # Adding a and b
product_ab = a * b # Multiplying a and b
# Outputting results
print("The sum of a and b is:", sum_ab) # Display the sum
print("The product of a and b is:", product_ab) # Display the
product
print(greeting) # Display the greeting
numbers).
• Example:
age = int(input("Enter your age: ")) # Converts input to integer
print("Next year, you will be", age + 1)
4. Define the key differences between a list, a tuple, and a
dictionary in Python.
In Python, lists, tuples, and dictionaries are all used to store
collections of data. However, they have different characteristics
and behaviors. Here's a breakdown of their key differences:
Key Differences:
Feature List Tuple Dictionary
Syntax [] () {}
Keys must be
Can contain Can contain unique, but
Duplicates
duplicates duplicates values can be
duplicates
Example:
# List (Mutable)
fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Mango") # Allowed
# Tuple (Immutable)
colors = ("Red", "Green", "Blue")
immutability).
o Dictionaries allow O(1) average-time complexity for
lookups (using hash tables).
4. When to Use?
o List: For collections that need frequent modifications
Output:
1
2
3
2. continue Statement
• Skips the current iteration and moves to the next.
• Example:
for i in range(1, 5):
if i == 3:
continue # Skip i=3
print(i)
Output:
1
2
4
3. pass Statement
• Acts as a placeholder (does nothing).
• Used where syntax requires a statement but no action is
needed.
• Example:
for i in range(5):
if i == 2:
pass
print(i)
Output:
0
1
2
3
4
• Example:
>>> x = 10
>>> y = 5
>>> print(x + y)
15
Script Mode:
• Execution: Code is written in a .py file and executed all at once
# example.py
x = 10
y=5
print(x + y)
Running the script:
$ python example.py
15
7. Explain different types of operators in python with examples?
• Arithmetic Operators:
These operators are used for mathematical operations.
Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
// Floor Division a // b
% Modulus (remainder) a % b
** Exponentiation a ** b
Example:
a = 10
b = 3
print(a + b) # Output: 13
• Logical Operators
These operators combine conditional statements.
• Assignment Operators
These operators assign values to variables.
Operator Description Example
= Assigns a value a = 10
+= Add and assign a += 5
-= Subtract and assign a -= 5
*= Multiply and assign a *= 5
Example:
a = 10
a += 5 # a = a + 5
print(a) # Output: 15
• Identity Operators
These operators compare memory locations of two objects.
Operator Description Example
True if both objects are
is a is b
the same
True if both objects are a is
is not
not the same not b
Example:
a = [1, 2, 3]
b = a
print(a is b) # Output: True
print("\nResults:")
print(f"Addition: {num1} + {num2} = {addition}")
print(f"Subtraction: {num1} - {num2} = {subtraction}")
print(f"Multiplication: {num1} * {num2} = {multiplication}")
print(f"Division: {num1} / {num2} = {division}")
print(f"Modulus: {num1} % {num2} = {modulus}")
print(f"Exponentiation: {num1} ** {num2} = {exponentiation}")
print(f"Floor Division: {num1} // {num2} = {floor_division}")
Output :
Enter the first number: 10
Enter the second number: 5
Results:
Addition: 10.0 + 5.0 = 15.0
Subtraction: 10.0 - 5.0 = 5.0
Multiplication: 10.0 * 5.0 = 50.0
Division: 10.0 / 5.0 = 2.0
Modulus: 10.0 % 5.0 = 0.0
Exponentiation: 10.0 ** 5.0 = 100000.0
Floor Division: 10.0 // 5.0 = 2.0
print(f"Grade: {grade}")
output:
87
Grade: A
11. Write a program to check if a given number is prime using a
while loop
num = int(input("Enter a number: "))
if num <= 1:
print(f"{num} is not a prime number")
else:
is_prime = True
i=2
while i*i <= num:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
output:
23
23 is a prime number
UNIT 2
uppercase.
• Functionality: Returns a new string with all lowercase
2. lower()
• Description: Converts all characters in a string to
lowercase.
• Functionality: Returns a new string with all uppercase
3. strip()
• Description: Removes leading and trailing whitespace
4. replace(old, new)
• Description: Replaces occurrences of a substring (old) with
5. split(separator)
• Description: Splits the string into a list of substrings based
on a specified separator.
• Functionality: Returns a list where each element is a part
• Opening a File
Use the open() function with a file path and mode.
Example:
file = open("example.txt", "r")
• Reading from a File:
file.read(): Reads the entire file content.
file.readline(): Reads a single line.
file.readlines(): Reads all lines as a list of strings.
Example:
file = open("example.txt", "r")
content = file.read() # Reads entire file
print(content)
file.close()
• Closing a File:
After performing operations, always close the file using close()
to free up system resources.
Example :
file.close() # Closes the file after operations
Consumes more
Memory More memory-efficient
memory
Example :
List -
my_list = [1, 2, 3]
my_list[0] = 99 # Allowed (Mutable)
Tuples –
my_tuple = (1, 2, 3)
output:
Enter a string: sriya
Number of vowels in the string: 2
5. Create a program to read a text file, count the no. of words in it,
and display the result.
def count_words(filename):
try:
with open(filename, 'r') as file:
content = file.read()
words = content.split()
return len(words)
except FileNotFoundError:
return "File not found. Please check the filename and try
again."
if isinstance(word_count, int):
print(f"The file '{filename}' contains {word_count} words.")
else:
print(word_count)
# Union:
union_result = set_A.union(set_B)
print("Union:", union_result) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection:
intersection_result = set_A.intersection(set_B)
print("Intersection:", intersection_result) # Output: {4, 5}
# Difference (A - B):
difference_A_B = set_A.difference(set_B)
print("Difference (A - B):", difference_A_B) # Output: {1, 2, 3}
# Difference (B - A):
difference_B_A = set_B.difference(set_A)
print("Difference (B - A):", difference_B_A) # Output: {6, 7, 8}
# Symmetric Difference:
symmetric_diff = set_A.symmetric_difference(set_B)
print("Symmetric Difference:", symmetric_diff) # Output: {1, 2, 3, 6,
7, 8}
Output :
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A - B): {1, 2, 3}
Difference (B - A): {6, 7, 8}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
7. Compare and contrast the use of lists and dictionaries for storing
and retriving data efficiently
• Lists
➢ Ordered collection (indexed by position).
➢ Syntax: [1, 2, 3]
➢ Access: Fast by index (O(1)), slow for searches (O(n)).
➢ Use Case: Storing sequences (e.g., students = ["Alice", "Bob"]).
• 2. Dictionaries
➢ Unordered key-value pairs.
➢ Syntax: {"name": "Alice", "age": 25}
➢ Access: Instant by key (O(1)).
➢ Use Case: Labeled data (e.g., student_grades = {"Alice": 90}).
Examples:
# List (slow search)
if "Bob" in students: # O(n) time
print("Found!")
Access
O(1) for index access O(1) for key-based access
Speed
output :
5.0
Division successful!
Operation complete!
• Keyword Arguments
➢ Passed using param=value syntax
➢ Can be in any order (not position-dependent)
➢ Make code more readable by explicitly naming arguments
• Default Arguments
➢ Defined in function declaration with default values
➢ Become optional parameters (can be omitted in call)
➢ Must come after non-default args in parameter list
Example –
def greet(name,age,country="INDIA"):
print(f"Hello, my name is {name} and I am {age} years old
from {country}")
#positional arguments
greet("Bhairava",3)
#keyword arguments
greet(name="Bhairava", age=3,country="Canada")
#default arguments
greet("Janu",12)
Output :
Hello, my name is Bhairava and I am 3 years old from INDIA
Hello, my name is Bhairava and I am 3 years old from Canada
Hello, my name is Janu and I am 12 years old from INDIA
Output:
The result of 10 divided by 2 is: 5.0
Execution completed.