0% found this document useful (0 votes)
6 views20 pages

Python QB

The document provides an overview of Python applications, features, and data types, including numeric, string, sequence, mapping, set, boolean, and binary types. It explains control flow statements like if-elif-else, membership and identity operators, and the use of comments in Python. Additionally, it covers variable naming conventions and command line arguments with example codes for better understanding.

Uploaded by

sakuli7474
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)
6 views20 pages

Python QB

The document provides an overview of Python applications, features, and data types, including numeric, string, sequence, mapping, set, boolean, and binary types. It explains control flow statements like if-elif-else, membership and identity operators, and the use of comments in Python. Additionally, it covers variable naming conventions and command line arguments with example codes for better understanding.

Uploaded by

sakuli7474
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

Python Qb

[Link]:
1)Web Applications.
1) Desktop GUI Applications
2) Software Development
3) Scientific and Numeri
4) Business Applications
5) Console Based Application
6) Audio or Video based Applications
7) 3D CAD Applications
8) Enterprise Applications 10) Applications for Images

[Link]:
1. Easy to learn and Use:
2. Interpreted Language:
3. Free and Open Source:
4. Object Oriented Programming:
5. Cross-platform and Portable language:
6. Large Standard Library:
7. Dynamically Typed Language:
8. Support Garbage Collection:
9. Dynamically Typed Language:
10. Integrated Language:

3. ans in model paper winter 2023

[Link] types:
Numeric Types (int, float, complex) Integers, floating point numbers and complex numbers present under
2. String Type (str)
the Numeric Data
3. Sequence Types (list, tuple, range)
4. Mapping Type (dict) Type category.
5. Set Types (set, frozenset) They are defined as int, float and complex class in Python.
6. Boolean Type (bool)
7. Binary Types (bytes, bytearray, memoryview).
1. Integer is a combination of 0 to 9 digits numbers without decimal point. Integer number may be positive or
negative. Integers can be of any length, it is only limited by the memory available.
Example: a=10 print("Value of a=",a," and data type is",type(a));

2. Floating point number is a combination of 0 to 9 digits number with decimal point. Floating point number may
be positive or negative. A floating point number is accurate up to 15 decimal places. Float can also be scientific
numbers with an "e" to indicate the power of 10.
Example: a=10.45 b=12e4 print("Value of a=",a," and data type is",type(a)); print("Value of b=",b," and data type
is",type(b));

3. Complex number is a combination of real and imaginary parts. In python, complex numbers are written with a
"j" as the imaginary part. Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.
Example: b=4+3.4j print("Value of b=",b," and data type is",type(b));

4. The collections of characters is known as String. Characters may be alphabets, numbers or special symbols.
String should be represented by using single quotes or double quotes. For String data type,predefined class str is
used. Positive and Negative index associated with the String value. String positive index should begin with 0 and
end with SIZE-1. Negative index should begin with -1 from the last element. Multi-line strings can be denoted
using triple quotes, ''' or """. When we use plus (+) sign with String then it work as concatenation operator and
when we use asterisk(*) sign with String then it work as repetition operator. Strings are immutable. It means once
it is created, you can not change it later. Subscript [] and index number is used to access any particular element
from the string. We can use slice [:] operators to access the data of the strings.
Example: str1="VJTech Academy"; print(str1); print(str1[:]); print(str1[7:]); print(str1[2:6]); print(str1+"
Awasari"); print(str1*2);
When you run the above program, the output will be: VJTech Academy VJTech Academy Academy Tech VJTech
Academy Awasari VJTech AcademyVJTech Academy

5. List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the
items in a list do not need to be of the same type. List is a collection of mixed data types of items. List should be
represented by using square bracket [ ]. For List data type,predefined class list is used. Positive and Negative index
associated with the list items. List positive index should begin with 0 and end with SIZE-1. Negative index should
begin with -1 from the last element. Lists are mutable. It means once it is created, you can change it later.
Subscript [] and index number is used to access any particular element from the list. We can use slice [:] operator
to access the items of the list.
Example: a = [5,10,15,20,25,30,35,40] print(a) print(a[2]) print(a[0:3]) print(a[5:])
When you run the above program, the output will be: [5, 10, 15, 20, 25, 30, 35, 40] 15 [5, 10, 15] [30, 35, 40]

6. Set is an unordered collection of unique items. - Set is defined by values separated by comma inside braces { }.
- Items in a set are not ordered. - We can perform set operations like union, intersection on two sets. - Set have
unique values. They eliminate duplicates. - Set are unordered collection of items and index numbers are not
associated with it. Hence the slicing operator [:] does not work.
- Example: a = {5,10,15,20,25,30,35,40} print(a) When you run the above program, the output will be: {35, 5, 40,
10, 15, 20, 25, 30} set is mutable.i.e we can perform remove or add operation
to it.
7. Dictionary is an ordered collection of items and it should be represented by using (key:value) pairs format. - It
is generally used when we have a huge amount of data. - Dictionaries are optimized for retrieving data. We must
know the key to retrieve the value. - In Python, dictionaries are defined by using curly bracket {} with each item
being a pair in the form key:value. - Key and value can be of any data type.

- Example: d = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}; print("First city is ",d[1]); print("Fourth city is
",d[4]); print (d); print ([Link]()); print ([Link]());

When you run the above program, the output will be: First city is Pune Fourth city is Thane {1: 'Pune', 2: 'Solapur',
3: 'Tuljapur', 4: 'Thane'} dict_keys([1, 2, 3, 4]) dict_values(['Pune', 'Solapur', 'Tuljapur', 'Thane'])

Tuple :
Tuple is an ordered sequence of items.
- All the items in a Tuple do not need to be of the same type.
- Tuple is a collection of mixed data types of items.
- Tuple should be represented by using parentheses ().
- For Tuple data type,predefined class tuple is used.
- Positive and Negative index associated with the Tuple items.
- Positive index should begin with 0 and negative index should begin with -1 from the last element.
- Tuple are immutable. It means once it is created, you can not change it later.
- Subscript [] and index number is used to access any particular element from the Tuple.
- We can use slice [:] operator to access the range of items from the Tuple.
- Tuples are used to read only data and it is faster than list as it cannot change dynamically.
- Example: a = (5,10,15,20,25,30,35,40)
print(a) When you run the above program, the output will be:
print(a[2]) (5, 10, 15, 20, 25, 30, 35, 40)
print(a[-3]) 15
print(a[0:3]) 30
print(a[5:]) (5, 10, 15) (30, 35, 40)
[Link] operators:
- in and not in are the membership operators in Python.
- They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).
- In a dictionary we can only test for presence of key, not the value.
- Following are the Membership operators in Python:
Operator Meaning:
in -True if value/variable is found in the sequence
not in-True if value/variable is not found in the sequence
- Example:
x=[10,20,30,40,50]
print("10 in x =>", 10 in x);
print("10 not in x =>", 10 not in x);
print("120 in x =>", 120 in x);
print("120 not in x =>", 120 not in x);
When you run the above program, the output will be:
10 in x => True
10 not in x => False
120 in x => False
120 not in x => True
Identity operators:
- is and is not are the identity operators in Python.
- Identity operators are used to compare the objects/variables.
- They are used to check if two values (or variables) are located on the same part of the memory.
- Following are the identity operators in Python:
Operator Meaning:
Is-True if operands are indentical
is not- True if operands are not identical
- Example:
x=10;
y=10;
z=20;
print("x is y =>", x is y);
print("x is not y =>", x is not y);
print("x is not z =>", x is not z);
print("x is z =>", x is z);
When you run the above program, the output will be:
x is y => True
x is not y => False
x is not z => True
x is z => False
6. if-elif-else statement is one of the types of Decision making statement. if, elif and else all are predefined
keywords which should be written in small letters. (chapter2)
Syntx: if condition-1:
statements --- ---
elif condition-2:
statements --- ---
elif condition-3:
statements --- ---
else:
statements ---
Program controller first test the condition-1, if condition-1 is True then program controller executes the body of if
statement. If condition-1 is false then program controller test the condition-2, if condition-2 is True then it will
executes the body of if statement. If all conditions are False then program controller executes else block statements.

Example:
marks=int(input("Enter your Marks:"))
if marks>=75: print("You got Distinction"); elif marks>=60: print("You got First Class"); elif marks>=40:
print("You are Pass only"); else: print("You are Fail");
When you run the above program, the output will be:
Enter your Marks:89 You got Distinction - In the above example, When variable marks value is 89, then ‘You got
Distinction’ is printed. When variable marks value is 66, then ‘You got First Class’ is printed. When variable
marks value is 45, then ‘You are Pass only’ is printed. When variable marks value is 35, then ‘You are Fail’ is
printed.

7. if-else statement is one of the types of Decision making statement. if and else both are predefined keywords
which should be written in small letters. (if elif else already ready above)
Syntx: if condition:
statement-1 --- ---
else:
statement-1 --- ---
Program controller first test the condition, if condition is True then program controller executes the body of if
statement. If condition is False then program controller executes the body of else statements. In Python
programming language, any non-zero and non-null values are assumed as TRUE, and if it is either zero or null,
then it is assumed as FALSE value. if-else statement flowchart:
Example: a=int(input("Enter first Number:"))
b=int(input("Enter second Number:"))
if a==b:
print("Both Numbers are Equals");
else:
print("Both Numbers are not Equals");
When you run the above program, the output will be:
Enter first Number:15
Enter second Number:15
Both Numbers are Equals

8. Most of the programming languages like C, C++, Java use curly brackets { } to define a block of code. Python
uses indentation. A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. If we use
indentation in Python then the code look neat and clean. Generally four whitespaces are used for indentation or we
can use single Tab.
Example: for i in range(1,11):
if i == 5:
break
print(i)

Variable is an Identifier which can change value during the execution of program. Variable act as a container for
storing the value. A variable is a named location used to store data in the memory. In python, there is no need of
declaration of variables by using the data type. We can directly use the variable name for storing the value and its
data type is decided dynamically as per the stored value on it. Following are the rules which we use while
constructing the variable Name.
1. Variable name must start with a alphabets or the underscore(_) character.
2. It may combine with Numbers(0-9).
3. Variable name should not start with Numbers(0-9).
4. Keywords cannot be used as an Variable name.
5. It does not allowed any white space between Variable name.
6. It does not allowed any special symbols except underscore in Variable name.
7. Variable name is case-sensitive (Eg. VJTECH, VJTech and vjtech are three different variables).
8. Variable name can be of any length.
Example: #Valid variable names: vjtech = "Vishal Sir" vj_tech = 123 _vj_tech = 34.56 vjTech = 3+5.6j VJTECH
= (10,20,30,40) vjtech123= [12,4.5,67,89] # Invalid variable names: 2vjtech = 123 vj#tech = "Vishal Sir" VJ Tech
= 678.99

9. Explain use of Pass and Else, elif keyword in python.(both note above)
pass is a predefined keyword in Python which should be written in small letters. In Python programming, pass is a
null statement. The difference between a comment and pass statement in Python is that, while the interpreter
ignores a comment entirely, pass is not ignored. However, nothing happens when pass is executed. It results into
no operation (NOP).
Syntax: pass else and elif explaination is left
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They
cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body
that does nothing. The else block runs only if no exception occurs in the try block.
Example: # Program to show the use of pass keyword
numbers=[10,20,30,40,50]
If an exception occurs, the else block does not execute.
for val in numbers: Python allows the use of else with loops (for, while)
pass The else block in a loop executes only if the loop runs
When you run the above program, the output will be blank:
completely without encountering a break statement.
____

10. What is command line argument? Write python code to add two numbers given as input from command
line arguments and print its sum.
Python command line arguments are input parameters passed to the script when executing them.
Almost all programming langauge provide support for command line arguments.
Then we also have command line options to set some specific options for the program.
There are many options to read python command line arguments . syntax eg
The three most common ones are:
python [Link] The elif keyword in Python stands for "else if". It is
Python getopt module used in conditional statements to check multiple
Pyhton argparse module conditions one after another.
Program:
if condition1:
Import sys
x=int([Link][1]) # Executes if condition1 is True
y=int([Link][2]) elif condition2:
sum=x+y # Executes if condition1 is False and condition2 is
Print(“the addition is :”,sum) True
Output: elif condition3:
64 # Executes if condition2 is False and condition3 is
the addition is:10 True
11) Explain how to perform comment in Python .
else:
Comments are very important while writing a program. # Executes if none of the above conditions are True
It describes what's going on inside a program so that a person looking at the source code can understand the code
easily.
You might forget the key details of the program you just wrote in a mon th's time.
So taking time to explain these concepts in form of comments is always helpful.
Comment is a part of documentation which helps us to give more detail information about the code.
Python Interpreter ignores the comments, it will not run.
There are two types of comments present in Python.
1. Single line comments
2. Multi-line comments Single line comments

In Python, we use the hash (#) symbol to write a single line comment.
-Single line comment begin with # symbol and end with the end of line.
We can cover multiple lines by using single line comment, for that you have to write # symbol for beginning of
each line.
Example: #This is Python Program which display Message.
#This program developed by VJTech Academy
print("Welcome to world of Python Language");
- Multi-line Comments:
In Python, multi-line comments begin with three times either single quotes (''') or double quotes (""") and end with
three times either single quotes (''') or double quotes (""").
These triple quotes are generally used for multi-line strings. But they can be used as multi-line comment as well.
Example: """This is Python Program which display Hellp Message.
This program developed by VJTech Academy"""
print("Welcome to world of Python Language");

12) Write a program to check whether a number is palindrome

no=int(input("Enter a number"))
rev=0
temp=no
while(no!=0):
d=no%10
rev=(rev*10)+d
no=no//10
if(temp==rev):
print("Number is palindrome")
else:
print("Number is not palindrome")

13. Write Python code for finding greatest among four numbers.

a=3
b=8
c=10
d=90
if(a>b):
if(a>c):
print("Greater number is ",a)
elif(a>d):
print("Greater number is ",a)
else:
print("Greater number is ",a) print a instead of d

else:
if(b>c):
print("Greater Number is",b)
c>d elif(b>d):
print("Greater Number is",c)
else:
print("Greater number is ",d)
O/p=Greater number is 90

[Link] a Python program to calculate sum of digit of given number

no=int(input("Enter a number"))
sum=0
while(no!=0):
d=no%10
sum=sum+d
no=no//10
print("Sum of digit=",sum)

14. ask to mam

15. Write a program to print following:


1
1 2
1 2 3
1 2 3 4 i for row and j for cols
for i in range(1,5):
for j in range(1,i+1):
print(j,end='')
print()
17) Explain mutable and immutable data structures.
Immutable data structures:
[Link](int,float,complex)
[Link]
[Link]
Mutable data structures:
[Link]
[Link]
[Link]
Explain all this with example.(number explain with this subtype)

18) Explain with example different operations that can be performed on a list?
Main op^n:
Indexing
Traversing
Slicing list and others datatypes method ,function
Extra : note separately because its make to u confuse.
del,pop,remove,update
Explain this with refer winter 2022 model paper page no :8|20

19) Describe different methods of list in python.


1) len() :- This method is used to find out the how many items present in list.
- Example:
a = [10,20,30,40,50]
print("Length of list=",len(a))
- Output: Length of list= 5 2)

2) append() :- To add an item to the end of the list, we use the append() method
- Example: using append we can add single item in list
a = [10,20,30,40,50]
append(60)
print("All Items of list=", a)
- Output: All Items of list= [10, 20, 30, 40, 50, 60]

3) extend() :- To add no of items to the end of the list, we use the extend() method.
- Example:
a = [10,20,30,40,50] using extend we can add multiple item in list
extend([60,70,80]);
print("All Items of list=", a)
- Output: All Items of list= [10, 20, 30, 40, 50, 60, 70, 80]

4) insert() :- To add an item at the specified index, we use the insert() method
- Example:
a = [10,20,30,40,50] insert(index,add _value)
insert(1,15) print("All Items of list=", a)
- Output: All Items of list= [10, 15, 20, 30, 40, 50, 60]

5) del :- The del keyword is used to delete the specified index value or it can also delete the complete list -
Example: a = [10,20,30,40,50]
del a[1] print("list after deleting index 1 value=", a)
#if you want to delete complete list del a
- Output: list after deleting index 1 value= [10, 30, 40, 50]

6) remove() :- This method is used to remove the specified item from the list.
- Example:
a = [10,20,30,40,50]
remove(40)
print("list after removing 40 value=", a)
- Output: list after removing 40 value = [10, 20, 30, 50]

7) pop() :- This method is used to remove the specified index value from the list or it will remove the last value
if index is not specified.
- Example:
a = [10,20,30,40,50]
pop(1)
print("list after removing index 1 value=", a)
pop() print("list after removing last value=", a)
- Output:
list after removing index 1 value= [10, 30, 40, 50]
list after removing last value= [10, 30, 40] 7)

8) clear() :- This method is used to make an empty list.


- Example:
a = [10,20,30,40,50]
clear()
print("List of Values=",a)
- Output: List of items= []

20) List and Explain built-in List function and methods in Python with example.
Functions:(rest of above)methods aslo above

9) index() :- This method finds the given element in a list and returns its index number.
If the same element is present more than once, the method returns the index of the first occurrence of the element. -
Example:
a = [10,20,30,40,50]
print("Index of 30 element=", [Link](30))
- Output:
Index of 30 element= 2 9)

10) count() :- This method counts how many times an element present in a list and returns it.
- Example:
a = [10,20,30,40,50,30,30]
print("Count of 30 =", [Link](30))
- Output: Count of 30

11) sort() :- This method sorts the elements of a given list in a specific order - Ascending or Descending. -
Example:
a = [10,20,30,40,50,30,30]
sort();
print("Sort the element in Ascending order =", a)
b = [10,20,30,40,50,30,30]
[Link](reverse=True)
print("Sort the element in Descending order =", b)
- Output:
Sort the element in Ascending order = [10, 20, 30, 30, 30, 40, 50]
Sort the element in Descending order = [50, 40, 30, 30, 30, 20, 10]

12) reverse() :- This method is used to reverses the elements of given list.
- Example:
a = [10,20,30,40,50]
reverse();
print("Reverse the list elements =", a)
- Output:
Reverse the list elements = [50, 40, 30, 20, 10]

13) copy() :- This method is used copy all elements of one list to another list.
- Example:
a = [10,20,30,40,50]
b=[Link]();
print("Copied list b elements =", b)
- Output:
Copied list b elements = [10, 20, 30, 40, 50] 13)

14) min() :- This method is used to find out the minimum element in the list.
- Example: a = (10,20,30,40,50,30,30)
print("Minimum element =", min(a))
- Output: Minimum element = 10 14)

15)max() :- This method is used to find out the maximum element in the list.
- Example:
a = (10,20,30,40,50,30,30)
print("Maximum element =", max(a))
Output:
Maximum element = 50

21) Explain with example different ways to delete an element from the given list?
Del(),pop(),remove() this ways refers from que no 19.

22) Explain different ways to add objects / elements to list.


Append(),extend(),insert() refer from que no 19.

23) Write syntax for a method to sort a list.


sort() :- This method sorts the elements of a given list in a specific order - Ascending or Descending.
[Link]();
[Link](reverse=True)
Example:
a = [10,20,30,40,50,30,30]
sort();
print("Sort the element in Ascending order =", a)
b = [10,20,30,40,50,30,30]
[Link](reverse=True)
print("Sort the element in Descending order =", b)
- Output:
Sort the element in Ascending order = [10, 20, 30, 30, 30, 40, 50]
Sort the element in Descending order = [50, 40, 30, 30, 30, 20, 10]

24) Is tuple mutable? Justify your answer. Demonstrate any two methods of tuple.
No,tuple is not mutable.
Reason:
Tuple is an ordered sequence of items.
All the items in a Tuple do not need to be of the same type.
Tuple is a collection of mixed data types of items.
Tuple are immutable. if you try to modify a tuple,python will raise a TypeError .
It means once it is created, you can not change it later. because tuples are immutable in [Link] cant modify
Their values cannot be modified. a tuple once its created,but if it contains mutable objects
[Link] heterogenous data structure and used for grouping data. like(list,dictionary)those object can still be modified.
Subscript [] and index number is used to access any particular element from the Tuple.
We can use slice [:] operator to access the range of items from the Tuple.
Tuples are used to read only data and it is faster than list as it cannot change dynamically.
Methods:
1) len() :- This method is used to find out the how many items present in tuple.
- Example:
a = (10,20,30,40,50) count(x)
print("Length of Tuple=",len(a))
- Output:
index(X)
Length of Tuple= 5 explainatonn in notebook
2) del :- The del keyword is used to delete the tuple completely.
- Example:
a = (10,20,30,40,50)
del a
print(a);
Output: NameError: name 'a' is not defined

3) index() :- This method finds the given element in a tuple and returns its index number.
If the same element is present more than once, the method returns the index of the first occurrence of the
element.
- Example:
a = (10,20,30,40,50)
print("Index of 30 element=", [Link](30))
- Output:
Index of 30 element= 2

3) count() :- This method counts how many times an element present in a tuple and returns it.
- Example: a = (10,20,30,40,50,30,30)
print("Count of 30 =", [Link](30))
- Output: Count of 30 = 3

4) min() :- This method is used to find out the minimum element in the Tuple.
- Example:
a = (10,20,30,40,50,30,30)
print("Minimum element =", min(a))
- Output:
Minimum element = 10

5) max() :- This method is used to find out the maximum element in the Tuple.
- Example:
a = (10,20,30,40,50,30,30)
print("Maximum element =", max(a))
- Output:
Maximum element = 50

25)Describe Tuples in Python. concise code:l.f are very compact and


Refer que no:4 can be defined in a single line.
Anonymous code:l.f are A. means they
26)Write use of lambda function in python. dont need to declare function name.
The [Link],which is aslo called anonymous function.
l.f can make your code more readable
A lam. can rake any number of arguments, but can only have one expression.
Syntax: by avoiding the need for a separate
lambda arguments:expresion definition.
Example:
x=lambda a,b:a*b
Print(x(10,5)
Output:50

27) Explain with example different operations that can be performed on a tuple?
Concentation,repetiton,membership,iteration,indexing,slicing
1)Tuples can be concatenated using the + operator. This operation combines two or more tuples to create a new
tuple.
Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a tuple are
combined.
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')
tup3 = tup1 + tup2
print(tup3)
2) Repetition operation on tuples.

To repeat the same tuple for a particular number of times, then the following ways can be used.

 Using the ‘*’ operator.


 Using the repeat() function.

Using the ‘*’ operator.

The * symbol is commonly used to indicate multiplication, however, it becomes the repetition operator when the
operand on the left side of the * is a tuple. The repetition operator duplicates a tuple and links all of them together.
Even though tuples are immutable, this can be extended to them.

Example 1

In the following example code, we use the multiplication operation to form a tuple with repeated values.

Open Compiler
num_tuple = (10, 20, 30) * 5print(num_tuple)

Output

The output is as follows;

(10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30)

Example 2

Here we repeat a single-valued tuple. We use the comma to denote that this is a single-valued tuple.

Open Compiler
num_tuple = (10,) * 5print(num_tuple)

Output

The output of the above code is as follows;

(10, 10, 10, 10, 10)


Using the repeat() function.

The repeat() is imported from the itertools module. In the repeat() function we give the data and the number of times
the data to be repeated as arguments

Syntax

repeat(data,N)

Where.

data – the data that needs to be repeated.

N – It specifies the number of times the data should be repeated.

Example

In the following example, we repeat a tuple by using the repeat() function.

Open Compiler
import itertools
num_tuple = (10,20)
res = tuple([Link](num_tuple, 5))print(res)

Output

The output of the above code is as follows;

((10, 20), (10, 20), (10, 20), (10, 20), 0, 20))


Rest of operation are lefft to explain.
s=(10,20,50,40,90)
s
28)Write a python program to input any two tuples and interchange the tuple variables.
(10, 20, 50, 40, 90)
min(s)
t1=(1,7,9,6)
t2=(4,3,2,5) 10
print("values of tuple t1 before interchange",t1) max(s)
print("values of tuple t2 before interchange",t2) 90
temp=0 len(s)
temp=t1 5
t1=t2 s1=(20,10,78)
t2=temp s1
print("values of tuple t1 after interchange",t1)
print("values of tuple t2 after interchange",t2)
(20, 10, 78)
cmp(s,s1)
29)List and Explain built-in function on Tuple in Python with example. Traceback (most recent call last):
Min(),max(),len()(refer from qu no 24) File "<pyshell#20>", line 1, in <module>
Cmp(tuple1,tuple2) cmp(s,s1)
Compare elements of both tuples NameError: name 'cmp' is not defined
Tuple(seq) type(s)
Convert a list into tuple
<class 'tuple'>
cmp is deprecated
Type(obj)
Return the type of the object
(exampe is left to explain)

30)Write output:
T=(‘spam’,’Spam’,’SPAM!’,’SapPm’)
a) print(T[2])
b) b) print(T[-2])
c) c) print(T[2:])
d) d) print(list(T))
Output:
SPAM!
SPAM!
('SPAM!', 'SapPm’')(carefully read the brackets of ans.)
['spam', 'Spam', 'SPAM!', 'SapPm’']

31)Differentiate between list and Tuple.


32) Compare list and dictionary
List Tuple
[Link] are Tuples are List Dictionary
mutable immutable
[Link] consume Tuple consume [Link] is [Link]. Is a
more memory less memory as collection of hashed
compared to index values structure of
the list. pairs as that key and value
[Link] have Tuple does not of array in pairs.
several built-in have many c++
methods built-in [Link] is Dict. Is
methods created by created by
[Link] In tuple,it is placing placing
unexpected hard to take elements in elements in {}
changes and place. [ ] separated as
errors are more by “key”:”value”,
likely to occur. commas”,” Each key
[Link] list has the tuple has value pair is
the variable the fixed length separated
length. comma “,”
[Link] indices The key of
[Link] operation Tuple
of list are dictionary can
are more error operation are
integer be of any data
prone. safe.
starting from type
[Link] iteration Tuple iteration 0
is slower and is is faster.
[Link] The elements
time
elements are are accessed
consuming
accessed via via key-values
[Link] is useful Tuple is useful indices.
for insertion for readonly
[Link] order There is no
and deletion operation like
of the guarantee for
operation. accessing
elements maintaining
elements.
entered are order.
maintained.
33) Explain with example different operations that can be performed on a Set?
1. len() :-
This method is used to find out the how many items present in list.
- Example:
a = {10,20,30,40,50}
print("Length of set=",len(a))
- Output:
Length of set= 5

3) add() :-
To add new item to the set, we use the add() method
- Example:
a = {10,20,30,40,50}
[Link](60)
print("All elements of set=", a)
- Output:
All elements of set= {40, 10, 50, 20, 60, 30}

4) update() :- To add multiple items to the set, we use the update() method.
- Example:
a = {10,20,30,40,50}
a. update([60,70,80]);
print("All elements of set=", a)
Output: All elements of set= {70, 40, 10, 80, 50, 20, 60, 30}

5) del :- The del keyword is used to delete the set completely.


- Example:
a = {10,20,30,40,50}
del a
print(a)
- Output: NameError: name 'a' is not defined

6) remove() :- This method is used to remove the specified item from the set.
- Example: show error :keyerror
a = {10,20,30,40,50}
a. remove(40)
print("Set after removing 40 value=", a)
- Output: Set after removing 40 value= {10, 50, 20, 30}

7) pop() :- This method is used to remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed. The return value of the pop() method is the removed item.
- Example:
a = {10,20,30,40,50}
print("Removed Element=", [Link]())
- Output: Removed Element= 40

8) clear() :- This method is used to make an empty list.


- Example:
a = {10,20,30,40,50}
clear() [Link]()
print("Set elements=",a)
- Output: Set elements= set()

9) union() :- This method return a set that contains all items from both sets, duplicates are removed.
Aslo use or operator | I.e a|b
- Example:
a = {10,20,30,40,50}
b={20,60,70}
c=[Link](b)
print("Union set=",c)
- Output: Union set= {50, 20, 70, 40, 10, 60, 30}

10) difference() :- This method return set that contains the items that only exist in set a, and not in set b.
Aslo use - operator ie.a-b
- Example:
a = {10,20,30,40,50}
b={20,60,70}
c=[Link](b)
print("Difference set=",c)
- Output: Difference set= {40, 10, 50, 30}
[Link](20)
11)intersection() :- This method return a set that contains the sitems that exist in both set a and [Link] use &
operator ie. a&b discard(): {1, 2, 3, 4}
use to delete specific [Link](90)
- Example: s
a = {10,20,30,40,50}
ele from set.
but an element is not present {1, 2, 3, 4}
b={20,60,70}
c=[Link](b) in set and we can perform [Link](90)
print("Intersection set=",c) this opertion then error
Traceback (most recent call last):
- Output: Intersection set= {20} it dont show error. File "<pyshell#11>", line 1, in <module>
[Link](90)
11) symmetric_difference():Return s.d of two sets as a new set. KeyError: 90
Aslo use ^ operator .it display uncommon elements from two sets and return new set.
a = {10,20,30,40,50}
b={20,60,70}
c=a.symmetric_difference(b)
print("symmetric_difference set=",c)
- Output: symmetric_difference set= {70, 40, 10, 50, 60, 30}

34) Write python program to perform following operations on Set (Instead of Tuple)
i) Create set
ii) Access set Element
iii) Update set
iv) Delete set

#To create a set


s1={30,61,11,45,10,90,70}

#To access element from set


print(s1)

#To add element into set using add method


[Link](29)
print(s1)

#To update set using update method


[Link]([‘s’,’p’])
print(s1)

#To delete element from set using discard() method


[Link](60)
print(s1)

#To delete element from set using remove() method


[Link](10)
print(s1)

#To delete element from set using pop() method (here is unorderd list present so any one element is deleted)
[Link]()
print(s1)
Output:
{61, 90, 70, 10, 11, 45, 30}
{70, 10, 11, 90, 29, 30, 34, 45, 61}
{70, 10, 11, 's', 90, 29, 30, 34, 45, 'p', 61}
{70, 10, 11, 's', 90, 29, 30, 34, 45, 'p'}
{70, 11, 's', 90, 29, 30, 34, 45, 'p'}
{11, 's', 90, 29, 30, 34, 45, 'p'}
35) List and Explain built-in function on Set in Python with example.
Refer to 32 que no

36) Describe Dictionary with example?


-Dictionary is an ordered collection of items and it should be represented by using (key:value) pairs format.
- It is generally used when we have a huge amount of data.
- Dictionaries are optimized for retrieving data.
We must know the key to retrieve the value.
- In Python, dictionaries are defined by using curly bracket {} with each item being a pair in the form of key:value.
- Key and value can be of any data type.
- Example:
d = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("First city is ",d[1]) print("Fourth city is ",d[4])
print (d)
When you run the above program, the output will be:
First city is Pune Fourth city is Thane {1: 'Pune', 2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}

37) Explain creating Dictionary and accessing Dictionary Elements with example.
-Dictionary is an ordered collection of items and it should be represented by using (key:value) pairs format.
-In Python, dictionaries are defined by using curly bracket {} with each item being a pair in the form of key:value.
- Key and value can be of any data type.
-We can create a dictionary by placing a comma separated list of key:value pairs in curly bracket.
Python provides a built in function dict() for creating a dictionary.
+ Example:(carefully note this brackets are differ in 3 ways) add the syntax:
1. x = dict(name = "sam", age = 18, country = "india") <dict_name>={key1:value1,key2:value2...}
print(x)
2. X=dict({1:”red”, 2:”blue”,3:”cyan”})
print(x)
3. x=dict([(1,”mango”), (2,”chiku”), (3,”apple”)])
print(x)
+accessing :
Python dictionary method get() returns a value for the given key. If key is not available then returns default value
None.
Syntax
[Link](key, default = None)
Example:
d={1:100,2:200,3:300,4:400,5:500}
print(d)
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
[Link](3)#using get ()method
300
d[4]
400

38) Explain with example different operations that can be performed on a Dictionary?
1) len() :- This method is used to find out the how many items (key:value pairs) present in dictionary.
- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Length of Dictionary=",len(a))
- Output:
Length of Dictionary= 3

2) del :- The del keyword is used to delete the specified key name or it can also delete the complete dictionary -
Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
del a[1] print("list after deleting key 1 =", a)
#if you want to delete complete dictionary
del a
- Output:
list after deleting key 1 = {2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}

3) pop() & popitem() :- The pop() method is used to remove the specified key value from the dictionary.
The popitem() method is used to remove the last inserted element from the dictionary.
- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
pop(1)
print("Dictionary after removing key 1=", a)
popitem()
print("Dictionary after removing last element=", a)
- Output:
Dictionary after removing key 1= {2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}
Dictionary after removing last element= {2: 'Solapur', 3: 'Tuljapur'}

4) clear() :- This method is used to make an empty list.


- Example: a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
clear()
print("Elements of Dictionary=",a)
- Output:
#blank { }

5) copy() :- This method is used copy all elements of one dictionary to another dictionary.
- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
b=[Link]();
print("Copied dict b elements =", b)
- Output: Copied dict b elements = {1: 'Pune', 2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}

6) min() :- This method is used to find out the minimum key element in the dictionary.
- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Minimum key element =", min(a))
- Output:
Minimum key element = 1

7) max() :- This method is used to find out the maximum key element in the dictionary.
- Example: a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Maximum key element =", max(a))
- Output: Maximum key element = 4

8) get() :- This method is used to returns the value for the specified key if key is in dictionary.
- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Value =", [Link](3))
- Output: Value = Tuljapur

9) update() :- This method is used to updates the dictionary. If key value is already present then its corresponding
value will get changed. If key value not present then it will add new entry in the dictionary.
- Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
[Link](d1)
print(d)
d1 = {3: "three"}
# adds element with key 3
[Link](d1)
print(d)
- Output:
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'}

10) keys() & values() :- The keys() method display list of all keys in the dictionary. The values() method display
list of all values in the dictionary.
- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("All Keys=",[Link]())
print("All Values=",[Link]())
- Output:
All Keys= dict_keys([1, 2, 3, 4])
All Values= dict_values(['Pune', 'Solapur', 'Tuljapur', 'Thane'])
39) Explain different functions or ways to remove key:value pair from dictionary.
We can remove a particular item in a dictionary by using the method
pop() -It reuire at least on argument. it returns value which is removed
from dictonary.
⦿ Popitem() can be used to remove and return an arbitrary element from
the dictionary. it removes last element from dictionary. does not require
any argument. It require zero arugments.
⦿ This method removes as element with the provided key and return the
value.
⦿ All elements can be removed at once using the clear() method.
⦿ We can also use the del keyword to remove individual items or the
entire dictionary itself.
Example:
Output:
d={1:100,2:200,3:300,4:400,5:500}
print(d) {1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
[Link](4) {1: 100, 2: 200, 3: 300, 5: 500}
print(d) {1: 100, 2: 200, 3: 300}
[Link]() {}
print(d) Traceback (most recent call last):
d1={1:100,2:200,3:300,4:400,5:600}
[Link]()
File "C:/pythonsetup/[Link]", line 11, in <module>
print(d1) print(d)
del d NameError: name 'd' is not defined
print(d)

40) List and Explain built-in function on Dictionary in Python with example.
all()-Return True if all keys of the dictionary are True (or if the dictionary is empty).

any()-Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len()-Return the length (the number of items) in the dictionary.

cmp()-Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.


(ask to mam about example)

41) Write any four methods of dictionary.


Refer que no 38
Clear,copy,get(),popitems,pop(),….

42) Explain operations performed on strings.


String Slicing: String Traversal:
› A piece of string is known as slice. Traversal is a process in which we access all the elements of the string
› To cut a substring from string is called string one by one using for and while loop.
slicing. +example :
› Slice operator is applied to a string with the use >>> s=“Welcome”
of square bracket[]. >>>for c in s:
› Ending limit exclude the last index (n-1). print(c,end=“”)
› A slice 3:7 means 3rd, 4th, 5th and 6th position Output=Welcome
character.
› Syntax: +operator:
● Stringname[start_index:end_index] The concatenation operator(+) is used to join two strings.
● Stringname[start_index:end_index: step_size] Example:
› Example: >>>”Hello”+”sam”
● >>>s=“Hello” >>>Hellosam
● >>>s[0:2]
● he *operator:
‘in’ and ‘not in’ operator in Strings: The multiplication operator is used to concatenate the same string
› The ‘in’ operator is used to check whether a multiple times. It is called repetition operator.
character or a substring is present in a string Example:
or not. >>> s1=“Hello”
› The expression returns a Boolean value. >>>s2=3*s1
› Example: ‘Hello Hello Hello’
>>> s=“Hello” >>> ‘He’ in s #o/p True
43) Give the output of Python Code,
Str=”Maharashtra State Board of Technical Education”
print(str[15::1])
print(str[-10:-1:2])

Output:
te Board of Technical Education
dcto

44) Write down the output of the following Python code


>>>indices=['zero','one','two','three','four','five']
i)>>>indices[:4]
ii) >>>indices[:-2]
Output:
indices[:4]
['zero', 'one', 'two', 'three']
indices[-2]
'four'

45) Write python program to perform following operations on Sets;


i) Create set ii) Access set Element iii) Update set iv) Delete set
(repeated que.)

46) Write a program to create dictionary of students that includes their ROLL NO. and NAME.
i) Add three students in above dictionary
ii) Update name = ‘Shreyas’ of ROLL NO = 2
iii) Delete information of ROLL NO = 1

>>> dict1={1:"Vijay",2:"Santosh", 3:"Yogita"}


>>>print(dict1)

(1: 'Vijay', 2: 'Santosh', 3: 'Yogita') {1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}


ii)

>>>dict1[2]="Shreyas" - Example:
d ={1: "one", 2: "three"}
>>>print(dict1) d1 = {2: "two"}
# updates the value of key 2
(1: 'Vijay', 2: 'Shreyas', 3: 'Yogita')
[Link](d1)
iii) print(d)
d1 = {3: "three"}
>>>[Link](1) # adds element with key 3
[Link](d1)
Vijay' print(d)- Output:
{1: 'one', 2: 'two'}
>>>print(dict1)
{1: 'one', 2: 'two', 3: 'three'}
(2: 'Shreyas', 3: 'Yogita')

47) Write the output of the following:


i) >>> a = [ 2, 5, 1, 3, 6, 9, 7 ]
>>> a [ 2 : 6 ] = [ 2, 4, 9, 0 ] a[2:6(6-1=5)]
>>> print (a)
Output:[2, 5, 2, 4, 9, 0, 7]

ii) >>> b = [ “Hello” , “Good” ]


>>> b. append ( “python” )
>>> print (b)
Output:['Hello', 'Good', 'Python']
iii) >>> t1 = [ 3, 5, 6, 7 ]
>>> print (t 1 [2]) O/p:
>>> print (t 1 [–1]) 6
>>> print (t 1 [2 :]) 7
>>> print (t 1 [:])
[6,7]
[3,5,6,7,]
48) Print the following pattern using loop:
1010101
1 0 1 0 1
1 0 1
1
n=8
k=2*n-1
for i in range (n-2,-1,-2):
for j in range (k,-1,-1):
print(" ",end="")
k=k+1
for j in range(0,i+1):
if(j%2==0):
print("1",end="")
else:
print("0",end="")

print()

49) What is the output of the following program? correct code:


dict1 = {‘Google’ : 1, ‘Facebook’ : 2, ‘Microsoft’ : 3} dict1 = {'Google': 1, 'Facebook': 2, 'Microsoft': 3}
dict2 = {‘GFG’ : 1, ‘Microsoft’ : 2, ‘Youtube’ : 3} dict2 = {'GFG': 1, 'Microsoft': 2, 'Youtube': 3}
dict1 update(dict2);
for key, values in dictl items( ): [Link](dict2) # Merging dict2 into dict1
print (key, values)

Output: for key, value in [Link]():


Google 1 print(key, value)
Facebook 2
Microsoft 2
GFG 1
Youtube 3

50) Write a program function that accepts a string and calculate the number of uppercase letters and lower
case letters.
def st():
s=str(input("enter any string"))
print(s)
u=0
l=0
for i in s:
if([Link]()):
u+=1
else:
l+=1
print("upper case letter",u)
print("lower case letter",l)
st()

Output:
enter any stringSAkshi
SAkshi
upper case letter 2
lower case letter 4

You might also like