Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views41 pages

Unit 2,3,4 QB Key

The document provides Python programs for calculating the distance between two points, circulating values in a list, generating Fibonacci sequences, and checking Armstrong numbers. It also details various types of operators in Python, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators, along with their precedence. Additionally, it explains control statements like if, if...else, and if...elif...else for conditional branching in Python.

Uploaded by

priyaa16svv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views41 pages

Unit 2,3,4 QB Key

The document provides Python programs for calculating the distance between two points, circulating values in a list, generating Fibonacci sequences, and checking Armstrong numbers. It also details various types of operators in Python, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators, along with their precedence. Additionally, it explains control statements like if, if...else, and if...elif...else for conditional branching in Python.

Uploaded by

priyaa16svv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

1.

Write a Python program to find


(i) The distance between two points (5)

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)

(ii) Circulate the values of n variables. (5)

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:

-Python language supports the following types of operators


 Arithmetic Operators
 Comparison (Relational)Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.

Assume, a=10 and b=5


Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

// 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

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is

becomes true. not true.

!= 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

-= Subtract It subtracts right operand from the left operand c -= a is equivalent to c


AND and assign the result to left operand = c -a

*= Multiply It multiplies right operand with the left c *= a is equivalent to c


AND operand and assign the result to left operand = c *a

/= Divide It divides left operand with the right operand c /= a is equivalent to c


AND and assign the result to left operand = c /ac
/= a is equivalent to c
= c /a

%= Modulus It takes modulus using two operands and assign c %= a is equivalent to c


AND the result to left operand =c%a

**= Exponent Performs exponential (power) c **= a is equivalent to c


AND calculation on operators = c ** a
and assign value to the left operand

//= Floor It performs floor division on operators and c //= a is equivalent to c


Division assign value to the left operand = c // a
Logical Operators:
-Logical operators are the and, or, not operators.

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

y = 4 (0000 0100 in binary)

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

depends on the order of operations.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

-For mathematical operators, Python follows mathematical convention.


-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) is a
useful way to remember the rules:
• Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-
2) is8.
• You can also use parentheses to make an expression easier to read,asin(minute
* 100) / 60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and2
*3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5,
not 4, and 6+4/2 is 8, not5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
Examples:

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

3. i) Write a Python program to print the Fibonacci sequence. (4)

Program:

n =input(“Enter the number “)


num1 = 0
num2 = 1
next_number = num2
count = 1

while count <= n:


print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()

ii) Write a Python program to check the Armstrong number. (6)

Program:

n=int(input(“Enter the number to check:”))


s=n
b = len(str(n))
sum1 = 0
while n != 0:
r = n % 10
sum1 = sum1+(r**b)
n = n//10
if s == sum1:
print("The given number", s, "is armstrong number")
else:
print("The given number", s, "is not armstrong number")
4. Explain about the Iteration / Control statements in Python.
(or) Explain various selection, branching, conditional statements with example.
(or) Outline the conditional branching statements in Python with an example.

Python if...else Statement

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

The syntax of if statement in Python is:

if condition:
# body of if statement

The if statement evaluates condition.


1. If condition is evaluated to True, the code inside the body of if is executed.
2. If condition is evaluated to False, the code inside the body of if is skipped.
Working of if Statement
Example 1: Python if Statement

number = 10

# check if number is greater than 0


if number > 0:
print('Number is positive.')

print('The if statement is easy')

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

Here, since number is greater than 0, the condition evaluates True.


If we change the value of variable to a negative integer. Let's say -5.

number = -5

2. Python if...else Statement

An if statement can have an optional else clause.


The syntax of if...else statement is:
if condition:
# block of code if condition is True
else:
# block of code if condition is False
The if...else statement evaluates the given condition:
If the condition evaluates to True,
 the code inside if is executed
 the code inside else is skipped
If the condition evaluates to False,
 the code inside else is executed
 the code inside if is skipped

Working of if...else Statement


Example 2. Python if...else Statement

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

3. Python if...elif...else Statement

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,

1. If condition1 evaluates to true, code block 1 is executed.


2. If condition1 evaluates to false, then condition2 is evaluated.
a. If condition2 is true, code block 2 is executed.
b. If condition2 is false, code block 3 is executed.

Working of if...elif Statement


Example 3: Python if...elif...else Statement
number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')

Output

Zero
This statement is always executed

Python Nested if statements

We can also use an if statement inside of an if statement. This is known as a nested


if statement.
The syntax of nested if statement is:

# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)

Example 4: Python Nested if Statement

number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')

# Output: Number is positive


In the above example, we have used a nested if statement to check whether the given number
is positive, negative, or 0.

Python for Loop

In computer programming, loops are used to repeat a block of code.

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,

languages = ['Swift', 'Python', 'Go', 'JavaScript']

# run a loop for each item of the list


for language in languages:
print(language)

Output

Swift
Python
Go
JavaScript

In the above example, we have created a list called languages.


Initially, the value of language is set to the first element of the array,i.e. Swift, so the print
statement inside the loop is executed.
language is updated with the next element of the list, and the print statement is executed
again. This way, the loop runs until the last element of the list is accessed.

for Loop Syntax

The syntax of a for loop is:


for val in sequence:
# statement(s)

Here, val accesses each item of sequence on each iteration. The loop continues until we reach
the last item in the sequence.

Flowchart of Python for Loop

Working of Python for loop

Example: Loop Through a String


for x in 'Python':
print(x)

Output

P
y
t
h
o
n

Python for Loop with Python range()


A range is a series of values between two numeric intervals.
We use Python's built-in function range() to define a range of values. For example,

values = range(4)

Here, 4 inside range() defines a range containing values 0, 1, 2, 3.


In Python, we can use for loop to iterate over a range. For example,
# use of range() to define a range of values
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

1st True 0 is printed. i is increased to 1.

2nd True 1 is printed. i is increased to 2.

3rd True 2 is printed. i is increased to 3.

4th True 3 is printed. i is increased to 4.

5th False The loop is terminated

Using a for Loop Without Accessing Items

It is not mandatory to use items of a sequence within a for loop. For example,
languages = ['Swift', 'Python', 'Go']

for language in languages:


print('Hello')
print('Hi')
Output

Hello
Hi
Hello
Hi
Hello
Hi

Python while Loop

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. A while loop evaluates the condition


2. If the condition evaluates to True, the code inside the while loop is executed.
3. condition is evaluated again.
4. This process continues until the condition is False.
5. When condition evaluates to False, the loop stops.

Flowchart of Python while Loop


Flowchart of while Loop

Example: Python while Loop

# program to display numbers from 1 to 5


# initialize the variable
i=1
n=5
while i <= n: # while loop from i = 1 to 5
print(i)
i=i+1
Output

1
2
3
4
5

Example 2: Python while Loop

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

5. Write a Python program


i) To find how many times an element occurred in the list. (5)

Program:

def countX(lst, x):


count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count

# Driver Code / Main function


lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x=8
print('{} has occurred {} times'.format(x,countX(lst, x)))

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)

def small_large (list1):


largest = list1[0]
lowest = list1[0]
for item in list1[1:]:
if item > largest:
largest = item
if item < lowest:
lowest = item

print("Largest element is:", largest)


print("Smallest element is:", lowest)

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

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year

if (year % 400 == 0) and (year % 100 == 0):


print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year

elif (year % 4 ==0) and (year % 100 != 0):


print("{0} is a leap year".format(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))

(ii)To find the sum of n natural numbers. (5)

Program:

# Sum of natural numbers up to num

num = int(input(“Enter a number:”)

if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

8. Write a python program


(i)To check if a number is a palindrome. (5)

Program:

num = input("Enter a number")


if num == num[::-1]:
print("Yes its a palindrome")
else:
print("No, its not a palindrome")
(ii) To check whether a given number is perfect number. (5)

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

9. Describe the following:

i) Creating the list. (2)


ii) Accessing values in the lists. (3)
iii) Updating the list. (3)
iv) Deleting the list elements. (2)

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

'number of elements - 1'.

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

Creating a list in Python


The general syntax for creating a list is as follows.

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

student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]


print(student_data)

When we run the above code, it produces the output as follows.

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

stores the details of a student.


Python code to illustrate creating a list using list() constructor.

student_data = list([1, 'Rama', '2nd Year', 'CSE', 85.80])


print(type(student_data))
print(student_data)

When we run the above code, it produces the output as follows.

Accessing Elements of a list in Python

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

are accessed using the index values.

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.

student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]


print(f'Roll Number: {student_data[0]}\n'
f'Name of the Student: {student_data[1]}\n'
f'Branch: {student_data[3]}\n'
f'Year: {student_data[2]}\n'
f'Percentage: {student_data[4]}')

When we run the above code, it produces the output as follows.

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

When we run the above code, it produces the output as follows.

Changing an Element of a list in Python

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.

student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]


student_data[1] = 'Seetha'
print(student_data)
When we run the above code, it produces the output as follows.

Removing elements from a list in Python

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

used with a list, we can not use it again.

For example, consider the following code.


Python code to illustrate remove operation in a list.

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

When we run the above code, it produces the output as follows.


10. i) Illustrate List comprehension with suitable example. (5)

A Python list comprehension consists of brackets containing the expression, which is


executed for each element along with the for loop to iterate over each element in the Python
list.
Python List Comprehension Syntax
Syntax: newList = [ expression(element) for element in oldList if condition ]
Parameter:
 expression: Represents the operation you want to execute on every item within
the iterable.
 element: The term “variable” refers to each value taken from the iterable.
 iterable: specify the sequence of elements you want to iterate through.(e.g., a
list, tuple, or string).
 condition: (Optional) A filter helps decide whether or not an element should be
added to the new list.
Return:The return value of a list comprehension is a new list containing the modified
elements that satisfy the given criteria.
Python List comprehension provides a much more short syntax for creating a new list
based on the values of an existing list.
List Comprehension in Python Example
Here is an example of using list comprehension to find the square of the number in Python.

numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)

Output
[1, 4, 9, 16, 25]

Iteration with List Comprehension


In this example, we are assigning 1, 2, and 3 to the list and we are printing the list using
List Comprehension.

# Using list comprehension to iterate through loop


List = [character for character in [1, 2, 3]]

# Displaying list
print(List)

Output
[1, 2, 3]

Even list using List Comprehension


In this example, we are printing the even numbers from 0 to 10 using List Comprehension.
Python3

list = [i for i in range(11) if i % 2 == 0]


print(list)

Output
[0, 2, 4, 6, 8, 10]

List Comprehensions vs For Loop


There are various ways to iterate through a list. However, the most common approach is to
use the for loop. Let us look at the below example:

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

# Using list comprehension to iterate through loop


List = [character for character in 'Geeks 4 Geeks!']
# Displaying list
print(List)

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.

ii) Write a Python program to concatenate two lists. (5)

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]

# using + operator to concat


L3 = L1 + L2

# Printing concatenated list


print ("Concatenated list using + : " + str(L3))

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

Break Statement in Python

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:

for / while loop:


# statement(s)
if condition:
break
# statement(s)
# loop end

Working of Python Break Statement


The working of the break statement in Python is depicted in the following flowchart:

Working of Python Break Statement

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

print("Out of for loop")


print()

i=0

# Using while loop


while True:
print(s[i])

# break the loop as soon it sees 'e'


# or 's'
if s[i] == 'e' or s[i] == 's':
break
i += 1

print("Out of while loop")

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.

# Python program to demonstrate


# break statement with nested
# for loop

# first for loop


for i in range(1, 5):
# second for loop
for j in range(2, 6):

# break the loop if


# j is divisible by i
if j%i == 0:
break

print(i, " ", j)

Output:
3 2
4 2
4 3

Continue Statement in Python


Continue is also a loop control statement just like the break statement. continue statement is
opposite to that of the break statement, instead of terminating the loop, it forces to execute
the next iteration of the loop. As the name suggests the continue statement forces the loop
to continue or execute the next iteration. When the continue statement is executed in the
loop, the code inside the loop following the continue statement will be skipped and the next
iteration of the loop will begin.
Syntax of Continue Statement
The continue statement in Python has the following syntax:
for / while loop:
# statement(s)
if condition:
continue
# statement(s)
Working of Python Continue Statement
The working of the continue statement in Python is depicted in the following flowchart:

Working of Python Continue Statement


Example:
In this example, we will use Python continue statement with for loop to iterate through a
range of numbers and to continue to the next iteration without performing the operation on
that particular element when some condition is met.

# Python program to demonstrate continue statement

# 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

Pass Statement in Python

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.

# Python program to demonstrate pass statement

s = "geeks"

# Empty loop
for i in s:
pass # No error will be raised
# Empty function
def fun():
pass

# No error will be raised


fun()

# 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:

print(" Creation of items present in library")

lib = ["Books"]

print()

print("1.Add an item in library")

print("2.Position of an item in library")

print("3.Change an item in library")

print("4.Remove an item in library")

print("5.Display all items in library")

print("6.Number of items present in library")

print("7.Exit")

print()
while(True):

choice = int(input("Enter your choice: "))

if(choice == 1):

print("Adding an item in library")

value = input("Enter the item: ")

lib.append(value)

print("Succesfully an item was added in library!!!!!")

elif(choice == 2):

print("Displaying Position of an item in library")

value = input("Enter the item: ")

print(" Position of the ",value,"is:",lib.index(value))

elif(choice == 3):

print("Changing an item in library")

value = input("Enter the old item to change: ")

New = input("Enter the new item to change: ")

position = int(lib.index(value))

lib[position]= New

print("Succesfully an item was changed in library!!!!!")

elif(choice == 4):

print("Removing an item in library")

value = input("Enter the item: ")

lib.remove(value)

print("Succesfully an item was removed in library!!!!!")

elif(choice == 5):

print("Displaying items in library")

print(lib)

elif(choice == 6):
print("Total number of an items in library")

print(len(lib))

elif(choice == 7):

break

else :

continue

You might also like