0% found this document useful (0 votes)
2 views26 pages

Python imp Q&A

The document provides a comprehensive overview of Python programming concepts, including comments, variables, loops, functions, data structures, and file handling. It includes example programs demonstrating arithmetic operations, conditional statements, and string methods, as well as explanations of mutable vs. immutable types. Additionally, it covers operators, user input, and the differences between interactive and script modes in Python.

Uploaded by

veenakoninti
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)
2 views26 pages

Python imp Q&A

The document provides a comprehensive overview of Python programming concepts, including comments, variables, loops, functions, data structures, and file handling. It includes example programs demonstrating arithmetic operations, conditional statements, and string methods, as well as explanations of mutable vs. immutable types. Additionally, it covers operators, user input, and the differences between interactive and script modes in Python.

Uploaded by

veenakoninti
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
You are on page 1/ 26

UNIT 1

1. Write a Python program to demonstrate the use of comments,


variables, and expressions.
# This is a simple Python program to demonstrate comments,
variables, and expressions
# Variables
a = 10 # Integer variable
b = 5 # Integer variable
name = "Alice" # String variable

# Expressions (Arithmetic)
sum_ab = a + b # Adding a and b
product_ab = a * b # Multiplying a and b

# Expression (String concatenation)


greeting = "Hello, " + name # Concatenate the greeting string
with the name

# 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

2. Create a Python program that uses a for loop to calculate the


sum of the first 10
natural numbers.
sum=0
for i in range (1,11):
sum=sum+i
i=i+1 #optional code line
print(sum)

3. Describe how print() and input() functions work in Python.


Provide examples.
1. print() Function
• Purpose: Displays output on the screen.

• Syntax: print(value1, value2, ..., sep=' ', end='\n')


o sep (optional): Separator between values (default: space).

o end (optional): What to print at the end (default:


newline).
• Example:
print("Hello", "World!", sep=" ", end="!!") # Output: Hello
World!!!
2. input() Function
• Purpose: Takes user input from the keyboard.

• Syntax: input("Prompt message")


o Always returns input as a string (needs conversion for

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 [] () {}

Mutability Mutable Immutable Mutable

Ordered (from Ordered (from Ordered (from


Order Python 3.7 Python 3.7 Python 3.7
onward) onward) onward)

Keys must be
Can contain Can contain unique, but
Duplicates
duplicates duplicates values can be
duplicates

Indexed by Indexed by Indexed by


Indexing integer values (0, integer values unique keys
1, 2…) (0, 1, 2…) (e.g., strings)

When you need


When you
a collection that When you need
need a fixed
Use Case can be modified to associate
collection of
or iterated in keys with values
values
order

Example:
# List (Mutable)
fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Mango") # Allowed

# Tuple (Immutable)
colors = ("Red", "Green", "Blue")

# colors[0] = "Yellow" → Error (Tuples can't be modified)


# Dictionary (Key-Value Pairs)
person = {"name": "Alice", "age": 30}
person["age"] = 31 # Allowed (modifying value)
#table explanation
Key Differences Explained
1. Mutability
o List: Can add, remove, or modify elements.

o Tuple: Cannot be changed after creation (immutable).


o Dictionary: Values can be modified, but keys must be
immutable (e.g., strings, numbers, tuples).
2. Syntax
o Lists use [ ], tuples use ( ), and dictionaries use {

} with key:value pairs.


3. Performance
o Tuples are faster than lists for iteration (due to

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

(e.g., [10, 20, 30]).


o Tuple: For fixed data (e.g., coordinates (x, y)).
o Dictionary: For storing labeled data (e.g., {"id": 101,
"name": "Bob"}).

5. Explain the use of break, continue, and pass statements with


examples. Write a
program to demonstrate each.
1. break Statement
• Exits the loop entirely when a condition is met.
• Example:
for i in range(1, 6):
if i == 4:
break # Loop stops when i=4
print(i)

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

6. What is python interactive mode? explain how it differs from


script mode with example?
Interactive Mode:
• Execution: Code is entered and executed line-by-line directly in

the Python interpreter.


• Use Case: Ideal for quick testing, experimentation, and

debugging small pieces of code.


• Feedback: Immediate output after each command.

• Example:

>>> x = 10
>>> y = 5
>>> print(x + y)
15
Script Mode:
• Execution: Code is written in a .py file and executed all at once

using the python filename.py command.


• Use Case: Best for writing larger programs or projects.
• Feedback: Output is shown after the entire script finishes
running.
• Example:

# 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

• Comparison (Relational) Operators


These operators compare values and return True or False.
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
a = 10
b = 5
print(a > b) # Output: True

• Logical Operators
These operators combine conditional statements.

Operator Description Example


Returns True if both conditions a > 5 and
and
are true b < 10
Returns True if at least one a > 5 or b
or
condition is true > 10
not Reverses the boolean value not a > 5
Example:
a = 10
b = 5
print(a > 5 and b < 10) # Output: True

• 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

8. Write a program to take two inputs from the user, perform


arthemetic operations, and print the results.
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

addition = num1 + num2


subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2 if num2 != 0 else "Cannot divide by zero"
modulus = num1 % num2
exponentiation = num1 ** num2
floor_division = num1 // num2

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

9. Write a python program to determine whether a given number is


positive,negative, or zero using if-else statements
n=int(input())
if n>0:
print(n,"is a positive number")
elif n<0:
print(n,"is a negative number")
else:
print("It is zero")
output :
56
56 is a positive number
10. Write a program using if-elif-else to assign grades to students
based on their marks
marks = float(input())
if marks >= 80 and marks <= 100:
grade = "A"
elif marks >= 60 and marks < 80:
grade = "B"
elif marks >= 45 and marks < 60:
grade = "C"
elif marks >= 34 and marks < 45:
grade = "D"
elif marks >= 0 and marks < 34:
grade = "F"
else:
grade = "Invalid Marks"

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

1. List five common methods for strings in python and describe


their functionality
1. upper()
• Description: Converts all characters in a string to

uppercase.
• Functionality: Returns a new string with all lowercase

letters converted to uppercase.


Example:
text = "hello"
result = text.upper()
print(result)
# Output: "HELLO"

2. lower()
• Description: Converts all characters in a string to

lowercase.
• Functionality: Returns a new string with all uppercase

letters converted to lowercase.


Example:
text = "HELLO"
result = text.lower()
print(result)
# Output: "hello"

3. strip()
• Description: Removes leading and trailing whitespace

(spaces, tabs, newlines) from a string.


• Functionality: Returns a new string with the whitespace
removed from both ends.
Example:
text = " hello "
result = text.strip()
print(result)
# Output: "hello"

4. replace(old, new)
• Description: Replaces occurrences of a substring (old) with

another substring (new).


• Functionality: Returns a new string where all occurrences

of old are replaced by new.


Example:
text = "I like cats"
result = text.replace("cats", "dogs")
print(result)
# Output: "I like dogs"

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

of the original string, split by the separator. If no separator


is provided, it splits by whitespace by default.
Example:
text = "apple,banana,orange"
result = text.split(",")
print(result)
# Output: ['apple', 'banana', 'orange']
2. Explain how file handling in python works. Provide examples of
opening,reading, and closing a file.

• Opening a File
Use the open() function with a file path and mode.

Common File Modes


Mode Description

'r' Read (default)

'w' Write (overwrites existing file)

'a' Append (adds to existing file)

'r+' Read + Write

'b' Binary mode (e.g., 'rb')

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

3. Illustrate the difference between mutable and immutable


sequences in python using lists and tuples.

Feature Lists (Mutable) Tuples (Immutable)

Can be modified after Cannot be modified


Mutability
creation after creation

Syntax [ ] (square brackets) ( ) (parentheses)

Slightly slower (due to Faster (optimized for


Performance
mutability) fixed data)

Dynamic data that Fixed data that


Use Case
changes frequently shouldn't change

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)

# my_tuple[0] = 99 → Error (Immutable)

4. Write a Python program to count the number of vowels in a


given string using iteration over sequences
def countvowels(input_string):
vowels = "aeiouAEIOU"
count = 0
for char in input_string:
if char in vowels:
count += 1
return count
input_string = input("Enter a string: ")
vowelcount = countvowels(input_string)
print(f"Number of vowels in the string: {vowelcount}")

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."

filename = input("Enter the name of the text file (e.g., sample.txt):


")
word_count = count_words(filename)

if isinstance(word_count, int):
print(f"The file '{filename}' contains {word_count} words.")
else:
print(word_count)

6. Analyze the behavior of set operations(unions, intersection, and


difference) by writing a Python program for two given sets.
# Define two sets
set_A = {1, 2, 3, 4, 5}
set_B = {4, 5, 6, 7, 8}

# 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!")

# Dictionary (instant search)


if "Bob" in student_grades: # O(1) time
print("Found!")
Feature Lists Dictionaries

Ordered (0-based integer


Indexing Unordered (key-value pairs)
indices)

Access
O(1) for index access O(1) for key-based access
Speed

Labeled data (key-value


Use Case Sequential data
mappings)

Syntax [1, 2, 3] {"key": "value"}

Mutable (keys must be


Mutability Mutable
immutable)

Duplicates Allowed Keys must be unique


8. Evaluate the pros and cons of using a tuple versus a list in a
program designed to store user data.
Tuples:
• Pros:
o Immutability: Data cannot be changed, ensuring data
integrity.
o Performance: More memory efficient and faster for access
due to immutability.
o Hashable: Can be used as dictionary keys.
• Cons:
o Limited flexibility: Cannot modify data (no
adding/removing elements).
o Less suitable for dynamic data: Not ideal for user data that
changes.
Lists:
• Pros:
o Mutability: Data can be changed, making it flexible for
dynamic user data.
o Rich functionality: Can append, remove, or modify data
easily.
• Cons:
o Performance: Slightly slower and uses more memory
compared to tuples.
o Potential for accidental modification: May not be suitable
for data that should remain constant.
UNIT 3

1. Define the purpose of the try and expect blocks in python


The try and except blocks are used for exception handling in
Python. They allow you to:
1. try Block
o Contains code that might raise an exception (error).
o Python executes this code first.
2. except Block
o Runs only if an exception occurs in the try block.
o Handles the error gracefully instead of crashing the
program.
Example -
try:
print(10 / 2) # No error
except ZeroDivisionError:
print("Error!")
else:
print("Division successful!") # Executes if no error
finally:
print("Operation complete!") # Always runs

output :
5.0
Division successful!
Operation complete!

2. List the difference between positional arguments, keyword


arguments and default arguments in python functions
• Positional Arguments
➢ Must be passed in the exact order defined in the function
➢ Required (must provide values for all non-default positional
args)

• 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

3. Explain how the finally clause works in exception handling. Give


an example
In Python, the finally clause is part of the exception handling
mechanism and is used to ensure that a block of code is executed
no matter what, whether an exception occurs or not.
How it Works:
1. The try block contains the code that might raise an exception.
2. The except block handles specific exceptions if they occur.
3. The finally block contains code that must be executed
regardless of whether an exception was raised or not. Even if an
exception is raised and caught, the finally block will still run.
Example:
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
print("Cleaning up...")
file.close()

4. Illustrate the concept of recursion with an example in Python


Recursion is a programming technique where a function calls
itself to solve a problem by breaking it into smaller subproblems.
Key Features:
1. Base Case → Condition to stop recursion (prevents infinite
loops).
2. Recursive Case → Function calls itself with a modified input.
Example:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Output:
120

5.Write a python program to handle division by zero using


exception handling.
def divide_numbers(num1, num2):
try:
result = num1 / num2 # Attempt to divide
print(f"The result of {num1} divided by {num2} is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("Execution completed.")
# Example usage
divide_numbers(10, 2) # Valid division
divide_numbers(10, 0)

Output:
The result of 10 divided by 2 is: 5.0
Execution completed.

Error: Division by zero is not allowed.


Execution completed.

You might also like