Unit 2,3,4 QB Key
Unit 2,3,4 QB Key
Program:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
Program:
nterms = int(input("Enter number of values : "))
list1 = [ ]
for val in range(0,nterms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,nterms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
2. List out the operators in Python and Analyse the operator precedence of arithmetic
operators in Python.
Operators:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators:
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is the 5//2=2
quotient in which the digits after the decimal point are removed
Examples Output:
a=10 a+b=15
b=5 a-b= 5
print("a+b=",a+b)
print("a-b=",a-b) a*b= 50
print("a*b=",a*b) a/b= 2.0
print("a/b=",a/b) a%b=0
print("a%b=",a%b)
a//b=2
print("a//b=",a//b)
a**b= 100000
print("a**b=",a**b)
Comparison (Relational)Operators:
Comparison operators are used to compare values.
It either returns True or False according to the condition. Assume, a=10 and b=5
!= If values of two operands are not equal, then condition becomes true. (a!=b) is
true
> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Example
Output: a>b=> True a>b=> False
a=10 a==b=> False
b=5 a!=b=> True
print("a>b=>",a>b) a>=b=> False
print("a>b=>",a<b) a>=b=> True
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left c = a + b assigns value of a + b into c
side operand
+= Add AND It adds right operand to the left operand and c += a is equivalent to c
assign the result to leftoperand =c+a
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is', a and b) not x is False
print('a or b is' ,a or b)
print('not a is', not a)
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in binary)and
Example Output
a = 60 # 60 = 0011 1100
Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is-61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a|b; # 61 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a^b; # 49 = 00110001
print "Line 3 - Value of c is ", c
c =~a; # -61 = 11000011
print "Line 4 - Value of c is ", c
c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
print "Line 6 - Value of c is ", c
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary
or not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators areused.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
Identity Operators:
• They are used to check if two values (or variables) are located on the same partof
the memory.
Example
Output
x =5
False
y =5
True
x2 = 'Hello'
y2= 'Hello'
print(x1 is not y1)
print(x2 is y2)
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
Operator Description
~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)
a=9-12/3+3*2-1 A=2*3+4%5-
a=? 3/2+6 A=6+4%5- find m=?
a=9-4+3*2-1 3/2+6 A=6+4- m=-43||8&&0||-2
a=9-4+6-1 3/2+6 A=6+4- 1+6 m=- 43||0||-2
a=5+6-1 a=11- A=10-1+6 m=1||-2 m=1
1 a=10 A=9+6 A=15
Program:
Program:
In computer programming, we use the if statement to run a block code only when a certain
condition is met.
For example, assigning grades (A, B, C) based on marks obtained by a student.
1. if the percentage is above 90, assign grade A
2. if the percentage is above 75, assign grade B
3. if the percentage is above 65, assign grade C
In Python, there are three forms of the if...else statement.
1. if statement
2. if...else statement
3. if...elif...else statement
1. Python if statement
if condition:
# body of if statement
number = 10
Output
Number is positive.
The if statement is easy
In the above example, we have created a variable named number. Notice the test condition,
number > 0
number = -5
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement is always executed')
Output
Positive number
This statement is always executed
In the above example, we have created a variable named number. Notice the test condition,
number > 0
Since the value of number is 10, the test condition evaluates to True. Hence code inside the
body of if is executed.
If we change the value of variable to a negative integer. Let's say -5.
number = -5
The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, then we use
the if...elif...else statement.
The syntax of the if...elif...else statement is:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Here,
Output
Zero
This statement is always executed
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)
number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
For example, if we want to show a message 100 times, then we can use a loop. It's just a
simple example; you can achieve much more with loops.
There are 2 types of loops in Python:
for loop
while loop
In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc. For
example,
Output
Swift
Python
Go
JavaScript
Here, val accesses each item of sequence on each iteration. The loop continues until we reach
the last item in the sequence.
Output
P
y
t
h
o
n
values = range(4)
# iterate from i = 0 to i = 3
for i in values:
print(i)
Output
0
1
2
3
In the above example, we have used the for loop to iterate over a range from 0 to 3.
The value of i is set to 0 and it is updated to the next number of the range on each iteration.
This process continues until 3 is reached.
Iteration Condition Action
It is not mandatory to use items of a sequence within a for loop. For example,
languages = ['Swift', 'Python', 'Go']
Hello
Hi
Hello
Hi
Hello
Hi
Python while loop is used to run a block code until a certain condition is met.
The syntax of while loop is:
while condition:
# body of while loop
Here,
1
2
3
4
5
# program to calculate the sum of numbers until the user enters zero
total = 0
number = int(input('Enter a number: '))
while number != 0: # add numbers until number is zero
total += number # total = total + number
number = int(input('Enter a number: ')) # take integer input again
print('total =', total)
Output
Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11
In the above example, the while iterates until the user enters zero. When the user enters zero,
the test condition evaluates to False and the loop ends.
Program:
ii) To find the biggest and smallest element in the list. (5)
Program:
def small_large(list1):
length = len(list1)
list1.sort()
print("Largest element is:", list1[length-1])
print("Smallest element is:", list1[0])
# Driver Code
list1=[12, 45, 2, 41, 31, 10, 8, 6, 4]
small_large(list1)
(or)
# Driver Code
list1 = [12, 45, 2, 41, 31, 10, 8, 6, 4]
small_large(list1)
6. What are the basic operations in the list that can be performed in Python?
Explain each operation with its syntax and example.
7. Write a python program
(i) To test whether a given year is leap year or not. (5)
Program:
year = int(input("Enter a year: "))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Program:
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
Program:
Program:
n = int(input(“Enter a number”))
my_sum = 0
for i in range(1, n):
if(n % i == 0):
s=s+i
if (s == n):
print("The number is a perfect number")
else:
print("The number is not a perfect number")
Python Lists
In Python, a list is a collection of ordered and indexed elements of different data types. In
Python, the list and its elements are mutable. That means, the list and its elements can be
modified at any time in the program. In Python, the list data type (data structure) has
implemented with a class known as a list. All the elements of a list must be enclosed in
square brackets, and each element must be separated with a comma symbol. In Python, the
list elements are organized as an array of elements of different data types. All the elements of
a list are ordered and they are indexed. Here, the index starts from '0' (zero) and ends with
In Python, the list elements are also indexed with negative numbers from the last
element to the first element in the list. Here, the negative index begins with -1 at the
last element and decreased by one for each element from the last element to the first
element.
Syntax
list_name = [element_1, element_2, element_3, ...]
For example, consider the following code for creating a list which stores the details of a
student.
Python code to illustrate creating a list
In Python, a list can also be created using list() constructor. The list() constructor takes only
one argument.
Syntax
list_name = list([element_1, element_2, element_3, ...])
For example, consider the following code for creating a list using list() constructor which
In Python, the list elements are organized using index values that start with '0' (zero) at first
element and ends with 'length of the list - 1' at last element. The individual elements of a list
Syntax
list_name[index]
For example, consider the following code for accessing individual elements of a list.
Python code to illustrate accessing elements of a list.
In Python, we can also access a subset of elements from a list using slicing. We can access
any subset of elements from a specified starting index to ending index. In list slicing, the
default starting index is '0' and the default ending is 'length of the list - 1'.
Syntax
list_name[starting_index : ending_index]
For example, consider the following code for accessing a subset of elements from a list.
Python code to illustrate accessing a subset of elements from a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(student_data[2:4]) # Accessing elements from index 2 to 3
print(student_data[:4]) # Accessing elements from index 0 to 3
print(student_data[2:]) # Accessing elements from index 2 to last element
In Python, an element of a list can be changed at any time using index value.
Syntax
list_name[index] = new_value
For example, consider the following code for changing an element of a list.
Python code to illustrate changing an element of a list.
The Python provides the following built-in methods to remove elements from a list.
remove(value)
pop()
clear()
del
remove(value) - This method removes the specified element from the list. If the specified
element is not found in the list, then the execution terminates with an error message.
pop( ) or pop(index) - This method removes the last element from the list. But, when it is
used with an index value, it removes the value at the specified index from the list.
clear( ) - This method removes all the elements from the list. The clear( ) method makes the
list empty.
del Keyword - This keyword removes the complete list from the memory. After del keyword
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f'The list is - {my_list}')
my_list.remove(6)
print(f'The list after removing 6 is - {my_list}')
my_list.pop()
print(f'The list after pop is - {my_list}')
my_list.pop(2)
print(f'The list after pop with index 2 is - {my_list}')
my_list.clear()
print(f'The list after clear is - {my_list}')
del my_list
#print(f'The list after del keyword used is - {my_list}') # GENERATES ERROR
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)
Output
[1, 4, 9, 16, 25]
# Displaying list
print(List)
Output
[1, 2, 3]
Output
[0, 2, 4, 6, 8, 10]
# Empty list
List = []
for character in 'Geeks 4 Geeks!': # Traditional approach of iterating
List.append(character)
# Display list
print(List)
Output
['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
Above is the implementation of the traditional approach to iterate through a list, string,
tuple, etc. Now, list comprehension in Python does the same task and also makes the
program more simple.
List Comprehensions translate the traditional iteration approach using for loop into a simple
formula hence making them easy to use. Below is the approach to iterate through a list,
string, tuple, etc. using list comprehension in Python.
Output
['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
Output
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Now by using nested list comprehensions, the same output can be generated in fewer lines
of code.
Program:
L1 = [1, 4, 5, 6, 5]
L2 = [3, 5, 7, 2, 5]
# using naive method to concat
for i in L2 :
L1.append(i)
# Printing concatenated list
print ("Concatenated list using naive method : " + str(L1))
(or)
L1 = [1, 4, 5, 6, 5]
L2 = [3, 5, 7, 2, 5]
11. Explain break, continue and pass statements in python with example.
Using loops in Python automates and repeats the tasks in an efficient manner. But
sometimes, there may arise a condition where you want to exit the loop completely, skip an
iteration or ignore that condition. These can be done by loop control statements. Loop
control statements change execution from their normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports
the following control statements:
Break statement
Continue statement
Pass statement
The break statement in Python is used to terminate the loop or statement in which it is
present. After that, the control will pass to the statements that are present after the break
statement, if available. If the break statement is present in the nested loop, then it
terminates only those loops which contain the break statement.
Syntax of Break Statement
The break statement in Python has the following syntax:
Example:
In this example, we will see the usage of break statements with Python loops and strings.
First, we will use the break statement with for loops to exit out of the for loop when
specific characters are encountered in the string. Then we will perform the same operation
but with the while loop.
# Python program to demonstrate break statement
s = 'geeksforgeeks'
# Using for loop
for letter in s:
print(letter)
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
i=0
Output:
g
e
Out of for loop
g
e
Out of while loop
Example:
In this example, we will see the usage of break statements with nested for loops in Python.
If the break statement is declared within the inner for loop, then the control comes out of
only that loop. The outer for loops still continues to work.
Output:
3 2
4 2
4 3
# loop from 1 to 10
for i in range(1, 11):
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end = " ")
Output:
1 2 3 4 5 7 8 9 10
As the name suggests pass statement simply does nothing. The pass statement in Python is
used when a statement is required syntactically but you do not want any command or code
to execute. It is like a null operation, as nothing will happen if it is executed. Pass
statements can also be used for writing empty loops. Pass is also used for empty control
statements, functions, and classes.
Syntax of Pass Statement
The pass statement in Python has the following syntax:
function/ condition / loop:
pass
Example:
In this example, we will use the pass statement with an empty for loop and an
empty Python function. We just declared a function and write the pass statement in it.
When we try to call this function, it will execute and not generate an error.
Then we use the pass statement with an if condition within a for loop. When the value of
“i” becomes equal to ‘k’, the pass statement did nothing, and hence the letter ‘k’ is printed.
s = "geeks"
# Empty loop
for i in s:
pass # No error will be raised
# Empty function
def fun():
pass
# Pass statement
for i in s:
if i == 'k':
print('Pass executed')
pass
print(i)
Output:
g
e
e
Pass executed
k
s
12. Write a python program to manipulate the items present in the library using
List.
Program:
lib = ["Books"]
print()
print("7.Exit")
print()
while(True):
if(choice == 1):
lib.append(value)
elif(choice == 2):
elif(choice == 3):
position = int(lib.index(value))
lib[position]= New
elif(choice == 4):
lib.remove(value)
elif(choice == 5):
print(lib)
elif(choice == 6):
print("Total number of an items in library")
print(len(lib))
elif(choice == 7):
break
else :
continue