Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

21cs15it Problem Solving and Python Revision Questions and Answers (2)

Uploaded by

starun080905
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

21cs15it Problem Solving and Python Revision Questions and Answers (2)

Uploaded by

starun080905
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

PART A

1. List out the features of Python.

2. Evaluate the order of precedence of operators in Python.

3. Define function and mention its types.

4. What is the scope of variables

5. What is module and package in Python?

6. Difference between algorithm and pseudocode.

7. Define flowchart and list out the symbols.

8. Differentiate between local and global variables.

9. What do you mean by fruitful function?

10. Illustrate negative indexing in list with an example.

11. Discuss different modes of operation in python.

12. Define Variable.

13. Illustrate the flowchart of if-elif-else statements.

14. Write the syntax for function definition

15. Define Modules.

PART B
1. Explain in detail about the Operators in Python.

2. Explain in detail about various building blocks of algorithm?

3. Write the following Python programs.


To find the sum of ‘n’ natural numbers.
To convert Celsius to Fahrenheit.

4. Write algorithm, pseudo code and flowchart to find the eligibility for
voting?
Start
Input the age of the person.
Check if the age is 18 or above.
If true, the person is eligible to vote.
If false, the person is not eligible to vote.
Display the result.
End

5. Write algorithm, pseudo code and flowchart to check whether the number is
palindrome or not.
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")

6. Explain in detail about Iterative Statement with example.

7. Describe user defined function with example.

8. Explain about Built in function with example.

9. Define methods in a string with an example program using at least 5


methods.

10. How to access characters of a string?

11. Write a function that takes a string as a parameter and replaces the first
letter of every word with the corresponding uppercase letter.

12. Explain in detail about Conditional Statement with example.

13. Explain About Argument Types with example programs.

14. Analyze string slicing. Illustrate how it is done in python with an


example

15. Write a python code to search a string in the given list.

16. Describe python modules.

17. Describe python packages.

18. Explain in detail about various building blocks of algorithm?

19. Evaluate the different values (data types) and types of values that can be
used in Python.
20. Explain pseudocode and its rules also give examples for sequence,
selection and repetition type problems

21. Develop a flowchart to check whether the given number is a prime number or
not.

22. Write an algorithm find the square root of a number?

PART C
1. Write algorithm, pseudo code and flowchart to find Prime number or not.
Algorithm to Check if a Number is Prime:
Step-1:Start.
Step-2:Input the number n to be checked.
Step-3:If n <= 1, output that n is not prime and exit.
Step-4:for i from 2 to sqrt(n):
Step-5:If n % i == 0, then output that n is not prime and exit.
Step-6:If no divisors were found, output that n is prime.
Step-7:End.

2. Write algorithm, pseudo code and flowchart to check whether the number is
Armstrong or not.
Algorithm to Check if a Number is Armstrong:
Step-1:Start.
Step-2:Input the number n to check.
Step-3:Find the number of digits in n and store it in num_digits.
Step-4:Initialize sum to 0 and temp to n.
Step-5:while temp > 0:
Step-6:Extract the last digit of temp (digit = temp % 10).
Step-7:Raise the digit to the power num_digits and add the result to sum.
Step-8:Remove the last digit from temp (temp = temp // 10).
Step-9:If sum is equal to n, output that n is an Armstrong number.
Step-10:Otherwise, output that n is not an Armstrong number.
Step-11:End.

3. Write a python program to calculate electricity bill based on the number


of units consumed
1 to 100 units (Rs.2.5/Unit)
101 to 200 units (Rs.3.5/Unit)
201 to 300 units (Rs.4.5/Unit)
Above 301 units (Rs.6/Unit)
Tax = 2% of Total Bill. Using conditional statements.
# Function to calculate electricity bill
def calculate_bill(units):
# Initialize the bill amount
bill = 0
# Calculate based on units consumed
if units <= 100:
bill = units * 2.5
elif units <= 200:
bill = (100 * 2.5) + ((units - 100) * 3.5)
elif units <= 300:
bill = (100 * 2.5) + (100 * 3.5) + ((units - 200) * 4.5)
else:
bill = (100 * 2.5) + (100 * 3.5) + (100 * 4.5) + ((units - 300) * 6)
# Calculate tax (2% of total bill)
tax = 0.02 * bill
total_bill = bill + tax
return total_bill
# Input: Number of units consumed
units = int(input("Enter the number of units consumed: "))
# Calculate the total bill
total_bill = calculate_bill(units)
# Output: Display the total electricity bill
print("The total electricity bill is: Rs.",total_bill)
4. Write a program to explain the various operators involved in Python and
how an expression evaluated using precedence of operators.
# Python program to explain various operators and demonstrate operator
precedence
# Define a function to demonstrate each type of operator
def operators_demo():
# Arithmetic Operators
print("Arithmetic Operators:")
a = 10
b = 3
print(f"{a} + {b} = {a + b}") # Addition
print(f"{a} - {b} = {a - b}") # Subtraction
print(f"{a} * {b} = {a * b}") # Multiplication
print(f"{a} / {b} = {a / b}") # Division
print(f"{a} % {b} = {a % b}") # Modulus
print(f"{a} ** {b} = {a ** b}") # Exponentiation
print(f"{a} // {b} = {a // b}") # Floor Division
print()
# Comparison Operators
print("Comparison Operators:")
print(f"{a} > {b} = {a > b}") # Greater than
print(f"{a} < {b} = {a < b}") # Less than
print(f"{a} == {b} = {a == b}") # Equal to
print(f"{a} != {b} = {a != b}") # Not equal to
print(f"{a} >= {b} = {a >= b}") # Greater than or equal to
print(f"{a} <= {b} = {a <= b}") # Less than or equal to
print()
# Logical Operators
print("Logical Operators:")
x = True
y = False
print(f"{x} and {y} = {x and y}") # Logical AND
print(f"{x} or {y} = {x or y}") # Logical OR
print(f"not {x} = {not x}") # Logical NOT
print()
# Bitwise Operators
print("Bitwise Operators:")
print(f"{a} & {b} = {a & b}") # Bitwise AND
print(f"{a} | {b} = {a | b}") # Bitwise OR
print(f"{a} ^ {b} = {a ^ b}") # Bitwise XOR
print(f"~{a} = {~a}") # Bitwise NOT
print(f"{a} << 1 = {a << 1}") # Bitwise Left Shift
print(f"{a} >> 1 = {a >> 1}") # Bitwise Right Shift
print()
# Assignment Operators
print("Assignment Operators:")
a = 5
a += 3
print(f"a += 3 -> a = {a}")
a -= 2
print(f"a -= 2 -> a = {a}")
a *= 2
print(f"a *= 2 -> a = {a}")
a /= 2
print(f"a /= 2 -> a = {a}")
a %= 3
print(f"a %= 3 -> a = {a}")
a **= 2
print(f"a **= 2 -> a = {a}")
a //= 2
print(f"a //= 2 -> a = {a}")
print()
# Identity Operators
print("Identity Operators:")
print(f"{a} is {b} = {a is b}") # Identity operator: is
print(f"{a} is not {b} = {a is not b}") # Identity operator: is not
print()
# Membership Operators
print("Membership Operators:")
list_example = [1, 2, 3, 4, 5]
print(f"3 in {list_example} = {3 in list_example}")
print(f"6 not in {list_example} = {6 not in list_example}")
print()
# Call the function to show operator examples
operators_demo()
# Demonstrate Operator Precedence in an Expression
def precedence_demo():
print("Operator Precedence in an Expression:")
expression = 10 + 2 * 3 ** 2 - 5 / 5
print(f"Expression: 10 + 2 * 3 ** 2 - 5 / 5")
print("Steps:")
print("1. Exponentiation (3 ** 2) = 9")
print("2. Multiplication (2 * 9) = 18")
print("3. Division (5 / 5) = 1")
print("4. Addition (10 + 18) = 28")
print("5. Subtraction (28 - 1) = 27")
print(f"Result of expression = {expression}")
# Call the function to demonstrate precedence
precedence_demo()

5. Explain break statement and continue statement in Python with an example.

6. Write an algorithm and Pseudo code for the following:


(i) Calculating Area and Circumference of a Circle:
Input: Radius of the circle (R).
Process:
Calculate the area using the formula:
Area=π×R2
Calculate the circumference using the formula:
Circumference=2×𝜋×𝑅
(ii) Check if a Given Year is a Leap Year:
Input: Year (Y).
Process:
A year is a leap year if:
It is divisible by 4.
Otherwise, it is not a leap year.
1. Write a program to determine the factorial of a given number with and
without the use of recursion.
'1. Factorial Using Recursion:'
# Function to calculate factorial using recursion
def factorial_recursive(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial_recursive(n - 1)
# Input from user
num = int(input("Enter a number: "))
# Check if the number is non-negative
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"Factorial of {num} (using recursion) is:
{factorial_recursive(num)}")
'2. Factorial Without Recursion (Using Iteration):'
# Function to calculate factorial using iteration
def factorial_iterative(n):
# Initialize result to 1 (factorial of 0 is 1)
result = 1
# Multiply result by every number from 1 to n
for i in range(1, n + 1):
result *= i
return result
# Input from user
num = int(input("Enter a number: "))
# Check if the number is non-negative
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"Factorial of {num} (using iteration) is:
{factorial_iterative(num)}")
Example Output:
For input 5:
Using recursion: Factorial of 5 (using recursion) is: 120
Using iteration: Factorial of 5 (using iteration) is: 120
Both methods return the same result, 120

2.(i). Write a python program to find the greatest among three numbers.
# greatest of three numbers
a=eval(input("enter the value of a:"))
b=eval(input("enter the value of b:"))
c=eval(input("enter the value of c:"))
if (a>b and a>c):
print("the greatest no is",a)
elif(b>a and b>c):
print("the greatest no is",b)
else:
print("the greatest no is",c)
Example Output:
Enter the first number: 12
Enter the second number: 45
Enter the third number: 30
The greatest number among 12.0, 45.0, and 30.0 is: 45.0
This program works for both integers and floating-point numbers.

(ii). Write a program to check the given number is Armstrong number or not.
# Write a program to check the given number is Armstrong number or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
Output:
enter a number:153
153 is an Armstrong number.

3. Create a program to determine whether a string is a palindrome or not


# Function to check if a string is a palindrome
def is_palindrome(input_string):
# Remove spaces and convert to lowercase to ignore case and spaces
cleaned_string = ''.join(char.lower() for char in input_string if
char.isalnum())
# Check if the cleaned string is equal to its reverse
return cleaned_string == cleaned_string[::-1]
# Input from user
user_input = input("Enter a string: ")
# Check if the input string is a palindrome
if is_palindrome(user_input):
print(f"'{user_input}' is a palindrome!")
else:
print(f"'{user_input}' is not a palindrome.")
'''Example Output:
Input: "A man a plan a canal Panama"
Output: 'A man a plan a canal Panama' is a palindrome!
Input: "Hello"
Output: 'Hello' is not a palindrome.'''

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


by the user
# Function to count vowels in a string
def count_vowels(input_string):
# Define a set of vowels (both lowercase and uppercase)
vowels = set("aeiouAEIOU")
# Initialize vowel count to 0
vowel_count = 0
# Iterate over each character in the input string
for char in input_string:
if char in vowels:
vowel_count += 1 # Increment the count if the character is a
vowel
return vowel_count
# Input from user
user_input = input("Enter a string: ")
# Get the count of vowels in the user's input
vowel_count = count_vowels(user_input)
# Display the result
print(f"The number of vowels in the string is: {vowel_count}")
'''Example Output:
Enter a string: Hello World
The number of vowels in the string is: 3
In this example, the vowels are e, o, and o, so the output is 3.'''

5. Write a python program to perform all set operation with example.


# Define two example sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
# Union of sets
def union_sets(a, b):
return a.union(b)
# Intersection of sets
def intersection_sets(a, b):
return a.intersection(b)
# Difference of sets (elements in set_a but not in set_b)
def difference_sets(a, b):
return a.difference(b)
# Symmetric difference (elements in either set, but not both)
def symmetric_difference_sets(a, b):
return a.symmetric_difference(b)
# Subset check (if set_a is a subset of set_b)
def is_subset(a, b):
return a.issubset(b)
# Superset check (if set_a is a superset of set_b)
def is_superset(a, b):
return a.issuperset(b)
# Disjoint check (if sets have no elements in common)
def are_disjoint(a, b):
return a.isdisjoint(b)
# Example usage
print("Set A:", set_a)
print("Set B:", set_b)
print("\nUnion:", union_sets(set_a, set_b)) # {1, 2, 3, 4, 5, 6, 7, 8}
print("Intersection:", intersection_sets(set_a, set_b)) # {4, 5}
print("Difference (A - B):", difference_sets(set_a, set_b)) # {1, 2, 3}
print("Symmetric Difference:", symmetric_difference_sets(set_a, set_b)) # {1,
2, 3, 6, 7, 8}
print("Is A a subset of B?:", is_subset(set_a, set_b)) # False
print("Is A a superset of B?:", is_superset(set_a, set_b)) # False
print("Are A and B disjoint?:", are_disjoint(set_a, set_b)) # False
Output:
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A - B): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Is A a subset of B?: False
Is A a superset of B?: False
Are A and B disjoint?: False

Write a function that takes a number as an input parameter and returns the
corresponding
text in words, for example, on input 452, the function should return ‘Four
Five Two’.
Use a dictionary for mapping digits to their string representation.
def number_to_words(number):
# Dictionary to map digits to their corresponding words
digit_map = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}
# Convert the number to a string so we can iterate over each digit
number_str = str(number)
# Create a list of words corresponding to each digit
words = [digit_map[digit] for digit in number_str]
# Join the words with a space and return
return ' '.join(words)
# Example usage:
result = number_to_words(452)
print(result) # Output: "Four Five Two"
Example Output:
Input: 452 → Output: "Four Five Two"
Input: 908 → Output: "Nine Zero Eight"
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Important questions
UNIT-III-MODULES,PACKAGES,STRINGS
1. Explain how module allows to logically organize Python code.
MODULES:
• A module allows to logically organize Python code.
• Grouping related code into a module makes the code easier to understand
and use.
• A module is a Python object with arbitrarily named attributes that can
bind and reference.
• Simply, a module is a file consisting of Python code.
• A module can define functions, classes and variables.
• A module can also include runnable code.
EXAMPLE:
• The Python code for a module named aname normally resides in a file
named aname.py.
• Example of a simple module, support.py
The import Statement:
• Python source file as a module by executing an import statement in some
other Python source file. The import has the following
syntax −import module1[, module2[,... moduleN]]
• When the interpreter encounters an import statement, it imports the
module if the module is present in the search path.
• A search path is a list of directories that the interpreter searches
before importing a module.
• A module is loaded only once, regardless of the number of times it is
imported.
• This prevents the module execution from happening over and over again if
multiple imports occur.
The from...import Statement:
• The from ...import statement in python imoprts a specified attributes
from a module into the current namespace
• The from...import statement imports all the attributes of a
module into the current namespace.
The from...import has the following syntax − from modname import name1[,
name2[, ... nameN]]
Locating Modules:
• The current directory.
• If the module isn't found, Python then searches each directory in the
shell variable PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
• The module search path is stored in the system module sys as the
sys.path variable.
• The sys.path variable contains the current directory, PYTHONPATH, and
the installation-dependent default.
The PYTHONPATH Variable:
• The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.PYTHONPATH from a Windows system
Namespaces and Scoping:
• Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects (values).
• Access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable shadows the
global variable.
• Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.
• Python makes educated guesses on whether variables are local or
global.It assumes that any variable assigned a value in a function is local.
• Therefore, in order to assign a value to a global variable within a
function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
For example, a variable number in the global namespace.
• Within the function addnumber, assign number a value, therefore Python
assumes number as a local variable.
• However, we accessed the value of the local variable number before
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.
The dir() Function:
• The dir() built-in function returns a sorted list of strings containing
the names defined by a module.
• The list contains the names of all the modules, variables and functions
that are defined in a module. Following is a simple example
globals() and locals() Functions:
• The globals() and locals() functions can be used to return the names in
the global and local namespaces depending on the location from where they are
called.
• If locals() is called from within a function, it will return all the
names that can be accessed locally from that function.
• If globals() is called from within a function, it will return all the
names that can be accessed globally from that function.
• The return type of both these functions is dictionary. Therefore, names
can be extracted using the keys() function.
The reload() Function:
• When the module is imported into a script, the code in the top-level portion
of a module is executed only once.
• Therefore, if you want to reexecute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously imported
module again. The syntax of the reload() function is this −
• Syntax:reload(module_name)
• Example:Here, module_name is the name of the module you want to reload and
not the string containing the module name. For example, to reload hello
module, do the following −
• reload(hello)

2. Explain with example about the packages in python.


PACKAGES IN PYTHON:
A package is a hierarchical file directory structure that defines a single
Python application environment that consists of modules and sub packages and
sub-subpackages, and so on.
Consider a file dots.py available in Phone directory. This file has
following line of source code −
#!/usr/bin/python
defdots():
print"I'm dots Phone"
Similar way, another two files having different functions with the same name
as above −
• Phone/Isdn.py file having function Isdn()
• Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
• Phone/__init__.py
To make all of functions available when imported Phone, need to put explicit
import statements in __init__.py as follows −
from Pots import dots
from Isdn import Isdn
from G3 import G3
After add these lines to __init__.py, have all of these classes available when
import the Phone package.
#!/usr/bin/python
# Now import your Phone Package.
importPhone
Phone.dots()
Phone.Isdn()
Phone.G3()
OUTPUT:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
In the above example, a single functions in each file, keep multiple
functions in files. Define different Python classes in those files and
packages out of those classes.

3. Describe in detail about string functions.


String in Python:
• A string is a sequence of characters.
• A character is simply a symbol. For example, the English language has 26
characters.
• Computers do not deal with characters, they deal with numbers (binary).
Even though characters on user screen, internally it is stored and
manipulated as a combination of 0s and 1s.
• This conversion of character to a number is called encoding, and the
reverse prSocess is decoding. ASCII and Unicode are some of the popular
encodings used.
• In Python, a string is a sequence of Unicode characters. Unicode was
introduced to include every character in all languages and bring
uniformity in encoding.
How to create a string in Python?
• Strings can be created by enclosing characters inside a single quote or
double-quotes.
• Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.
How to access characters of a string?
• Access individual characters using indexing and a range of characters
using slicing.
• Index starts from 0.
• Trying to access a character out of index range will raise an
IndexError.
• The index must be an integer.
• Use floats or other types, this will result into TypeError.
• Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so
on.
Access a range of items in a string by using the slicing operator
:(colon).
• To access an index out of the range or use numbers other than an
integer,
will get errors.
• Slicing can be best visualized by considering the index to be between
the
elements as shown below.
• To access a range, the index that will slice the portion from the
string.
How to change or delete a string?
• Strings are immutable.
• This means that elements of a string cannot be changed once they have
been assigned.
• Simply reassign different strings to the same name.
• cannot delete or remove characters from a string. But deleting the
string
entirely is possible using the del keyword.
Python String Operations:
There are many operations that can be performed with strings which makes
it
one of the most used data types in Python.
Concatenation of Two or More Strings
• Joining of two or more strings is called concatenation.
• The ‘+ ‘operator does this in Python. Simply writing two string literals
together also concatenates them.
• The * operator can be used to repeat the string for a given number of
times.
• Writing two string literals together also concatenates them
like ‘+’ operator.
• To concatenate strings in different lines, use parentheses.
Built-in functions to Work with Python
• Various built-in functions that work with sequence work with strings as
well.
• Some of the commonly used ones are enumerate() and len().
• The enumerate() function returns an enumerate object.
• It contains the index and value of all the items in the string as pairs.
• This can be useful for iteration.
• Similarly, len() returns the length (number of characters) of the
string.
Escape Sequence
• To print a text like He said, "What's there?",
• neither use single quotes nor double quotes.
• This will result in a SyntaxError as the text itself contains both
single and double quotes.
print("He said, "What's there?"")
SyntaxError: invalid syntax
print('He said, "What's there?"')
SyntaxError: invalid syntax
• One way to get around this problem is to use triple quotes.
• Alternatively, we can use escape sequences.
• An escape sequence starts with a backslash and is interpreted
differently.
• If we use a single quote to represent a string, all the single quotes
inside
the string must be escaped.
• Similar is the case with double quotes.
• Here is how it can be done to represent the above text

4. Define methods in a string with an example program using at least 5


methods.
#MISCELLENOUS STRING FUNCTION
join() :sequence joined by a string separator.return join string.
len() :length of the string. returns the length of string .
replace() :update the old occurrences to new return new string
max() :characters in a string. returnmaximumcharacter
min() :characters in a string. Returnminimumcharacter
title(): converts astring in titledcase.uppercasefollows bylowercase.Return
string
istitle(): checks thestring in titlecasereturn true,else false
capitalize() :Capitalize the first letter ofstringReturn string
#BUILD IN STRING FUNCTION
1. islower():given stringhas all lowercase letter true otherwise false
2. isupper(): given stringhas all lower case letter true otherwise false
3. swapcase(): reverse thecase of all string upper to lower vise versa
4. find(): find if a substring occurs in a string for given starting index beg
and
end index as end return index if found or else-1
5. index(): tries find if a substring occurs in a string for given starting
index beg and end index as
end return index of the substring or else rises exception
6. split(): breaks a string which is separated by separator return a list
7. lstrip(): removes all the leading whitespaces instring return the string
minustrailing whitespaces
8. rstrip(): removestrailingwhitespaces in the string return string minus
trailing whitespaces
9. isspace(): is there is any whitespace return true else it return false
10. splitlines(): split a givenstring by newlines(\n)return thestring as alist
with thenewlinesremoved.
11. join(): string sequence joined by string seperator if num which is an
integervalue and if
indicates the new linesneed to be included in the lines.

UNIT-IV LISTS, TUPLES, DICTIONARIES


1. Explain in detail about list operation and its methods.
Lists:
• List is a sequence of items. Values in the list are called elements / items.

It can be written as a list of comma-separated items (values) between square
brackets
[ ].

Items in the lists can be of different data types.
• Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
Operations on list:
create a list:in this way we can create a list at compile time
Indexing:Accessing the item in the list using positive and negative
indexing.
Slicing:Printing a part of the list.
Concatenation:Adding and printing the items of two lists.
Repetition:Create a multiple copies of the same list.
Updating:Updating the list using Index value.
Membership:Returns True if element is in a present in list. Otherwise
False returns false.
Comparison:Used for comparing two lists.Returns True if all elements in
both lists are same.False Otherwise returns false
List slices:
List slicing is an operation that extracts a subset of elements from an list
and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
• default start value is 0
• default stop value is n-1

[:] this will print the entire list

[2:2] this will create a empty slice
List methods:
• Methods used in lists are used to manipulate the data quickly.
• These methods work only on lists.
• They do not work on the other sequence types that are not mutable, that is,
the values
they contain cannot be changed, added, or deleted.
1. Append():
Syntax:list.append(element)
Description:Add an element to the end of the list
2. Insert():
Syntax:list.insert(index,element)
Description:Insert an item at the defined index
3. Extend():
Syntax:list.extend(list)
Description:Extend the list by appending elements from the other list
4 Index():
Syntax:list.index(element)
Description:Returns the index of the first matched item
5 Sort():
Syntax:list.sort()
Description:Sort items in a list in ascending order
6 Reverse():
Syntax:list.reverse()
Description:Reverse the order of items in the list
7 Pop():
Syntax:list.pop()
Description:Removes and returns the last element
8 Pop():
Syntax:list.pop(index)
Description:Remove the particular element present on the index and return
it.
9 Remove():
Syntax:list.remove(element)
Description:Removes an item from the list
10 Count():
Syntax:list.count(element)
Description:Returns the number of occurrences of an element in a list.
11 Copy():
Syntax:list.copy()
Description:Returns a copy of the list.
12 Clear():
Syntax:list.clear()
Description:Removes all items from the list.
13 del():
Syntax:del(list)
Description:delete the entire list.
List built-in functions:
Python’s built-in functions such as min(), max(),len() and sorted() can be
used with list
to obtain needed value and execute various tasks.
a=[1,2,3,4,5]
1. Len()
This function returns the number of items on a list(length of the list).
>>>len(a)
5
2. Max()
This function returns the maximum value in a list.
>>>max(a)
5
3. Min()
This function returns the maximum value in a list.
>>>min(a)
1
4. Sum()
This function returns the sum of all items on a list.
>>sum(a)
15
5. Sorted()
This function returns a sorted list in ascending order.
>>>c=[5,3,4,1,2]
>>>sorted(c)
[1,2,3,4,5]
List using For Loop:
• The for loop in Python is used to iterate over a sequence (list, tuple,
string) or other
iterable objects.
• Iterating over a sequence is called traversal.
• Loop continues until we reach the last item in the sequence.
• The body of for loop is separated from the rest of the code using
indentation.
Syntax:
for val in sequence:
print val
List using While loop:
• The while loop in Python is used to iterate over a block of code as long as
the test
expression (condition) is true.
• When the condition is tested and the result is false, the loop body will be
skipped and
the first statement after the while loop will be executed.
Syntax:
while (condition):
body of while
Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It
keeps on
running. Such loops are called infinite loop.
Mutability:
• Lists are mutable. (can be changed)
• Mutability is the ability for certain types of data to be changed without
entirely
recreating it.
• An item can be changed in a list by accessing it directly as part of the
assignment
statement.
• Using the indexing operator (square brackets[ ]) on the left side of an
assignment, one
of the list items can be updated.
Aliasing(copying):
• Creating a copy of a list is called aliasing. When you create a copy both
list will be
• having same memory location. changes in one list will affect another list.
• Alaising refers to having different names for same list values.
Cloning
• To avoid the disadvantages of copying we are using cloning. creating a copy
of a same
list of elements with two different memory locations is called cloning.
• Changes in one list will not affect locations of another list.
• Cloning is a process of making a copy of the list without modifying the
original list.
List as parameters:
• In python, arguments are passed by reference.
• If any changes are done in the parameter which refers within the function,
then the changes also reflects back in the calling function.
• When a list to a function is passed, the function gets a reference to the
list.
• Passing a list as an argument actually passes a reference to the list, not a
copy of the
list.
• Since lists are mutable, changes made to the elements referenced by the
parameter
change the same list that the argument is referencing

2. Write about tuple operation and tuple methods with example


Tuple:
• A tuple is a set of elements separated by commas and enclosed in
parentheses.
• A tuple is an immutable list. i.e. once a tuple has been created, we can't
add elements to
a tuple or remove elements from the tuple.
• But tuple can be converted into list and list can be converted in to tuple.
• A tuple can also be created without using parentheses.
Benefit of Tuple:
• Tuples are faster than lists.
•If the user wants to protect the data from accidental changes, tuple can be
used.
• Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing -accessing tuple elements
2. Slicing -accessing tuple elements
3. Concatenation -main operations
4. Repetition -main operations
5. Membership -other operations
6. Comparison -other operations
1. Append():
Syntax:list.append(element)
Description:Add an element to the end of the list
2. Insert():
Syntax:list.insert(index,element)
Description:Insert an item at the defined index
3. Extend():
Syntax:list.extend(list)
Description:Extend the list by appending elements from the other list
4 Index():
Syntax:list.index(element)
Description:Returns the index of the first matched item
5 Sort():
Syntax:list.sort()
Description:Sort items in a list in ascending order
6 Reverse():
Syntax:list.reverse()
Description:Reverse the order of items in the list
7 Pop():
Syntax:list.pop()
Description:Removes and returns the last element
8 Pop():
Syntax:list.pop(index)
Description:Remove the particular element present on the index and return
it.
9 Remove():
Syntax:list.remove(element)
Description:Removes an item from the list
10 Count():
Syntax:list.count(element)
Description:Returns the number of occurrences of an element in a list.
11 Copy():
Syntax:list.copy()
Description:Returns a copy of the list.
12 Clear():
Syntax:list.clear()
Description:Removes all items from the list.
13 del():
Syntax:del(list)
Description:delete the entire list.
Tuple methods:
Tuple is immutable so changes cannot be done on the assigned.
Tuple Assignment and Uses of Tuple assignment:
Tuple Assignment:
• Tuple assignment allows, variables on the left of an assignment operator and
values of
tuple on the right of the assignment operator.
• Multiple assignment works by creating a tuple of expressions from the right
hand side,
and a tuple of targets from the left, and then matching each expression to a
target.
• Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
It is often useful to swap the values of two variables
Multiple assignments:
Tuple as return value:
• A Tuple is a comma separated sequence of items.
• A function can return one value. if you want to return more than one value
from a
function. we can use tuple as return value.
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.

3. Describe the methods and operations of dictionaries.


Dictionaries:
• Dictionary is a collection of elements. An element in dictionary has a key:
value pair.
• All elements in dictionary are placed inside the curly braces i.e. { }
• Elements in Dictionaries are accessed via keys and not by their position.
• The values of a dictionary can be any data type.
• Keys mus:t be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Methods in dictionary:
Copy()
Items()
Keys()
Values()
Pop()
Setdefault()
Update()
Fromkeys()
clear()
get()
popitem()
dict.copy():It returns copy of the dictionary. here copy of dictionary ’a’ get
stored in to dictionary ‘b’
dict.items():Return a new view of dict_items() the dictionary's items. It
displays a list of dictionary’s (key, value) tuple pairs.
dict.keys():Return a new view of dict_keys () the dictionary keys.
dict.values():Return a new view of dict_values() the dictionary values.
dict.pop():remove a specified key from a dictionary and return its
corresponding value.
dict.setdefault():Returns the value associated with the specified key if it
exists. If the key does not exist, it adds the key with the specified default
value and returns that value.

4. Difference between List, Tuples and dictionary?


5. Evaluate the different operations like union, intersection and differences
of list using Set and functions
BY USING SETS:
1. Intersection:
Set Intersection in Python
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using
the intersection() method.
Program 8 :
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
Output:
{4, 5}
2. Union:
Set Union in Python
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the
union() method.
Program 7:
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
3. Difference:
Set Difference in Python
Difference of the set B from set A(A - B) is a set of elements that are only
in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using the
difference() method.
Program 9:
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Run Code
Output:
{1, 2, 3}
4. Symmetric Difference:
Set Symmetric Difference in Python
Symmetric Difference of A and B is a set of elements in A and B but not in
both (excluding the
intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished
using the
method symmetric_difference().
Program 10:
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Run Code
Output:
{1, 2, 3, 6, 7, 8}
BY USING FUNCTIONS:
1. Union of Two Lists
The union of two sets includes all elements that are in either set.
def union(list1, list2):
set1 = set(list1)
set2 = set(list2)
return list(set1.union(set2))
# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Union:", union(list1, list2)) # Output: [1, 2, 3, 4, 5, 6]
2. Intersection of Two Lists
The intersection of two sets includes only the elements that are present in
both sets.
def intersection(list1, list2):
set1 = set(list1)
set2 = set(list2)
return list(set1.intersection(set2))
# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Intersection:", intersection(list1, list2)) # Output: [3, 4]
3. Difference of Two Lists
The difference of two sets includes elements that are in the first set but not
in the second set.
def difference(list1, list2):
set1 = set(list1)
set2 = set(list2)
return list(set1.difference(set2))
# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Difference (list1 - list2):", difference(list1, list2)) # Output: [1,
2]
4. Symmetric Difference of Two Lists
The symmetric difference includes elements that are in either of the sets but
not in both.
def symmetric_difference(list1, list2):
set1 = set(list1)
set2 = set(list2)
return list(set1.symmetric_difference(set2))
# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Symmetric Difference:", symmetric_difference(list1, list2)) # O
UNIT V-FILES, MODULES, PACKAGES
Discuss the different modes for opening a file and closing a file.
1. FILE AND ITS OPERATION:
• File is a collection of record.
• A file stores related data, information, settings or commands in
secondary storage device like magnetic disk, magnetic tape, optical disk,
flash memory.
File Type:
1. Text file
2. Binary file
Text file
1. Text file is a sequence of characters that can be sequentially
processed by
a computer in forward direction
2. Each line is terminated with a special character called the E0L or end
of
line character
Binary file
1.A binary files store the data in the binary format(i.e .0’s and 1’s)
2.It contains any type of data (pdf,images,word doc,spreadsheet,zip
files,etc) Mode in File
Module Description
r Read only
w mode Write
a only Appending
r+ only
Read and write only
Differentiate write and append mode:
Write mode
• It is used to write a string in a file
• If file is not exist it creates a new file
• If file is exit in the specified name,the existing content will
overwrite in a file by the given string
Append mode
• It is used to append (add) a string into a file
• If file is not exist it creates a new file
• It will add the string at the end of the old file
File operation:
1. Open ( ) function:
• Pythons built in open function to get a file object.
• The open function opens a file.
• It returns a something called a file object.
• File objects can turn methods and attributes that can be used to collect
2. Read ( ) function
Read functions contains different methods
• read() – return one big string
• readline() – return one line at a time
• readlines() – return a list of lines
A file stores related data, information, settings or commands in secondary
storage device like magnetic disk, magnetic tape, optical disk, flash
memory.
Reading file using looping:
• Reading a line one by one in given file
3. Write ( ) function
This method is used to add information or content to existing file.
Syntax:
file_name.write( )
Example:
fp=open(“a.txt”,”w”)
fp.write(“this file is a.txt”)
fp.write(“to add more lines”)
fp.close()
Output: a.txt
4. Close ( ) function
It is used to close the file.

2. Explain in detail about file methods


Method Description
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating
system's perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file

3. Describe in detail about exception handling with Python program.


Exceptions
• An exception is an error that happens during execution of a program. When
that Error
occurs
Errors in python
• IO Error-If the file cannot be opened.
• Import Error -If python cannot find the module
• Value Error -Raised when a built-in operation or function receives an
argument that
has the right type but an inappropriate value
• Keyboard Interrupt -Raised when the user hits the interrupt
• EOF Error -Raised when one of the built-in functions (input() or
raw_input()) hits an
end-of-file condition (EOF) without reading any data
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point
to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration
and SystemExit.
ArithmeticError Base class for all errors that occur for numeric
calculation.
OverflowError Raised when a calculation exceeds maximum limit for a
numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or
assignment.

4. Describe the use of try block and except block in Python with syntax.
1. Try –Except Statements
• The try and except statements are used to handle runtime errors
Syntax:
try :
statements
except :
statements
The try statement works as follows:-
 First, the try clause (the statement(s) between the try and except keywords)
is
executed.
 If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
 If an exception occurs during execution of the try clause, the rest of the
clause is
skipped. Then if its type matches the exception named after the except
keyword,
the except clause is executed, and then execution continues after the try
statement.
2. Try – Multiple except Statements
o Exception type must be different for except statements
Syntax:
try:
statements
except:
statements
except:
statements
3. Try –Except-Else
o The else part will be executed only if the try block does not raise the
exception.
o Python will try to process all the statements inside try block. If value
error occur,
the flow of control will immediately pass to the except block and remaining
statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
4. Raise statement
• The raise statement allows the programmer to force a specified exception to
occur.
5. Try –Except-Finally
 A finally clause is always executed before leaving the try statement,
whether an
exception has occurred or not.
 The finally clause is also executed “on the way out” when any other clause
of the
try statement is left via a break, continue or return statement.
Syntax
try:
statements
except:
statements
finally:
statements
from * add import add
from * sub import sub
from * mul import mul
from * div import div
import calculator
importsys
sys.path.append(“C:/Python34”)
print ( calculator.add(10,5))
print ( calculator.sub(10,5))
print ( calculator.mul(10,5))
print ( calculator.div(10,5))
1. Why do we go for file?
File can a persistent object in a computer. When an object or state is created
and needs to be persistent, it is saved in a non-volatile storage location,
like a hard drive.

2. What are the three different mode of operations of a file?


The three mode of operations of a file are,
i. Open – to open a file to perform file operations
ii. Read – to open a file in read mode
iii. Write – to open a file in write mode

3. State difference between read and write in file operations.


Read
1. A "Read" operation occurs when a computer
program reads information from a computer
file/table (e.g. to be displayed on a screen).
The "read" operation gets
information out of a file.
2. After a "read", the information from the
file/table is available to the computer program
but none of the information that was read
from the file/table is changed in
any way.
write
1. A "Write" operation occurs when a computer
program adds new information, or changes
existing information in a computer file/table.
2. After a "write", the information from the
file/table is available to the computer program
but the information that was read from the
file/table can be changed in any
way.

4. Define error and exception.


Errors
• Error is a mistake in python also referred as bugs .they are almost always
the fault ofthe
programmer.
• The process of finding and eliminating errors is called debugging
• Types of errors
• Syntax error or compile time error
• Run time error
• Logical error
Exceptions
An exception is an error that happens during execution of a program. When that
Error occurs

5. Give the methods of exception handling.


1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally

6. State the syntax for try…except block


The try and except statements are used to handle runtime errors
Syntax:
try :
statements
except:
statements

7. Write a program to add some content to existing file without effecting the
existing content.
file=open(“newfile.txt”,’a)
file.write(“hello”)
file.close()

8. What is package?
• A package is a collection of python module. Module is a single python file
containing function
definitions
• A package is a directory(folder)of python module containing an additional
init py file, to
differentiate a package from a directory
• Packages can be nested to anydepth, provided that the corresponding
directories contain their
own init py file

9. What is module?
A python module is a file that consists of python definition and statements. A
module can
define functions, classes and variables.
makes the code easier to understand and use.

10. Write the snippet to find the current working directory.


Import os
print(os.getcwd))
Output:
C:\\Users\\Tarun\\Desktop
newfile.txt
Hello!!World!!!
newfile.txt(after updating)
Hello!!!World!!!hello

11. Give the use of format operator


The argument of write has to be a string, so if we want to put other values in
a file, we have to convert them to strings. The easiest way to do that is with
str:
>>> x = 52
>>> fout.write(str(x))
An alternative is to use the format operator, %. When applied to integers, %
is the modulus operator. But when the first operand is a string, % is the
format
operator. The first operand is the format string, which contains one or more
format
sequences, which specify how the second operand is formatted. The result is a
string. For
example, the format sequence '%d' means that the second operand should be
formatted as an
integer (d stands for “decimal”):
>>> camels = 42
>>>'%d' % camels '42'
The result is the string '42', which is not to be confused with the integer
value 42.

12. Write the snippet to find the absolute path of a file.


import os
os.path.abspath('w
rite.py')
Output:
'C:\\Users\\Tarun\\Desktop\\write.py'

13. What is the use of os.path.isdir() function.


os.path.isdir() is a function defined in the package os. The main function of
isdir("some input")
function is to check whether the passed parameter is directory or not.
isdir() function will only return only true or false.

14. What is the use of os.path.isfile() function.


os.path.isfile () is a function defined in the package os. The main function
of isfile ("some input") function is to check whether the passed parameter is
file or not. isfile ()
function will only return only true or false.

15. What is command line argument?


sys.argv is the list of command line arguments passed to the Python program.
Argv represents all the items that come along via the command line input, it's
basically an array holding the command line arguments of our program.

You might also like