0% found this document useful (0 votes)
10 views

Python Programming- UNIT 1

This document provides an overview of lists and tuples in Python, detailing their characteristics, operations, and methods. It explains how to create, access, update, and manipulate lists, including features like indexing, slicing, and built-in functions. Additionally, it contrasts lists with tuples, highlighting their mutable versus immutable nature and the syntax used to define them.

Uploaded by

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

Python Programming- UNIT 1

This document provides an overview of lists and tuples in Python, detailing their characteristics, operations, and methods. It explains how to create, access, update, and manipulate lists, including features like indexing, slicing, and built-in functions. Additionally, it contrasts lists with tuples, highlighting their mutable versus immutable nature and the syntax used to define them.

Uploaded by

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

Python Programming

UNIT- II

List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type it means we can modify its element after it is created. A list can be defined as a
collection of values or items of different types. The items in the list are separated with the
comma (,) and enclosed with the square brackets [].
A single list may contain DataTypes like Integers, Strings, as well as Objects. A list can
contain any kind of data, i.e., it’s not mandatory to form a list of only one data type. The list
can contain any kind of data in it.
A list can be defined as below
1. L1 = ["John", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1and L2 using type() function then it will come out to be a list
as follows:
print(type(L1))
print(type(L2))
Output:
<class 'list'>
<class 'list'>

Characteristics of Lists
The list has the following characteristics:
o The lists are ordered.
o The element of the list can be accessed by index.
o The lists are the mutable type.
o A list can store various number of elements.
Example 1: Creating a list in Python

# Python program to demonstrate creation of List

# Creating a List
List = []
print("Blank List: ")
print(List)

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

Output
Blank List:
[]

List of numbers:
[10, 20, 14]

List indexing
Elements stored in the lists are associated with a unique integer number known as an index.
The first element is indexed as 0, and the second is 1, and so on. So, a list containing six
elements will have an index from 0 to 5. For accessing the elements in the List, the index is
mentioned within the index operator ([ ]) preceded by the list's name.
Another way we can access elements/values from the list in python is using a negative index.
The negative index starts at -1 for the last element, -2 for the last second element, and so on.
My_List = [3, 4, 6, 10, 8]

# Accessing values stored in lists using positive index


print("Values accessed using positive Index.")
print(My_List[2])
print(My_List[4])

# Accessing values stored in lists using negative index


print("Values accessed using negative Index.")
print(My_List[-1])
print(My_List[-5])

OUTPUT:

Values accessed using positive Index.


6
8
Values accessed using negative Index.
8
3

We also have nested Lists in python. For nested Lists, we first access the index at which the
inner list is stored/indexed in the outer list using the index operator. Then we access the
element from the inner list using the index operator again. It is known as nested indexing. It
is like we access elements in a 2-dimensional array. Unlike in this, we have many elements in
the inner list, but arrays only have a single value at that index.
# Nested List
nested_List = [[6, 2, 8], [1, 3.5, "Interviewbit"],
"preparation"]
print(nested_List[0][1])
print(nested_List[1][2])

OUTPUT:

2
Interviewbit

Updating List in Python


Lists are mutable, meaning that their existing values stored at the indexes can be changed. To
change or update the list elements, the assignment operator (=) is used.
My_List = [3, 4, 6, 10, 8, 5]
print(My_List)
# Changing value to index 3.
My_List[3] = 7
print(My_List)
# Changing value to index -1, i.e the last value.
My_List[-1] = 15
print(My_List)

OUTPUT:

[3, 4, 6, 10, 8, 5]
[3, 4, 6, 7, 8, 5]
[3, 4, 6, 7, 8, 15]

List Operations in Python

Concatenation: One list may be concatenated with itself or another list using ‘+’ operator.

List1 = [1, 2, 3, 4]
List2 = [5, 6, 7, 8]
concat_List = List1 + List2
print(concat_List)

OUTPUT:

[1, 2, 3, 4, 5, 6, 7, 8]

Repeating the elements of the list: We can use the ‘*’ operator to repeat the list elements as
many times as we want.

my_List = [1, 2, 3, 4]
print(my_List*2)

OUTPUT:

[1, 2, 3, 4, 1, 2, 3, 4]

Membership Check of an element in a list: We can check whether a specific element is a


part/ member of a list or not.

my_List = [1, 2, 3, 4, 5, 6]
print(3 in my_List)
print(10 in my_List)
print(10 not in my_List)

OUTPUT:

True
False
True

Iterating through the list: We can iterate through each item within the list by employing a
for a loop.

my_List = [1, 2, 3, 4, 5]
for n in my_List:
print(n)

OUTPUT:

1
2
3
4
5

Finding the length of List in python: len() method is used to get the length of the list.

my_List = [1, 2, 3, 4, 5]
print(len(my_List))

OUTPUT:

Slicing a List in Python

In Python, we can access the elements stored in a range of indexes using the slicing operator
(:). The index put on the left side of the slicing operator is inclusive, and that mentioned on
the right side is excluded.

Slice itself means part of something. So when we want to access elements stored at some part
or range in a list we use slicing.

my_List = ['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
# Accessing elements from index beginning to 5th index
print(my_List[:6])
# Accessing elements from index 3 to 6
print(my_List[3:7])
# Accessing elements from index 5 to end
print(my_List[5:])
# Accessing elements from beginning to end
print(my_List[:])
# Accessing elements from beginning to 4th index
print(my_List[:-6])
OUTPUT:

['i', 'n', 't', 'v', 'i', 'e']


['v', 'i', 'e', 'w']
['e', 'w', 'b', 'i', 't']
['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
['i', 'n', 't', 'v']

List Methods in Python


In python, the method is like a function that performs some task but can only be called on
objects. Methods are related to objects and may change the object’s state.
1. append() - Add an item to the ending of the list.

currencies = ['Dollar', 'Euro', 'Pound']

# append 'Yen' to the list


currencies.append('Yen')

print(currencies)

Output:
['Dollar', 'Euro', 'Pound', 'Yen']

2. extend() - Add items of one list to another list.

# create a list
prime_numbers = [2, 3, 5]

# create another list


numbers = [1, 4]

# add all elements of prime_numbers to numbers


numbers.extend(prime_numbers)

print('List after extend():', numbers)

Output:
List after extend(): [1, 4, 2, 3, 5]

3. insert() - Adds an item at the desired index position.

# create a list of vowels


vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)


vowel.insert(3, 'o')

print('List:', vowel)

Output:
List: ['a', 'e', 'i', 'o', 'u']

4. remove() - Remove the primary item from the list with the required value.

# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]

# remove 9 from the list


prime_numbers.remove(9)

# Updated prime_numbers List


print('Updated List: ', prime_numbers)

Output:
Updated List: [2, 3, 5, 7, 11]

pop()
5. Remove the item from the required index within the list, and return it.
-

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]

# remove the element at index 2


removed_element = prime_numbers.pop(2)

print('Removed Element:', removed_element)


print('Updated List:', prime_numbers)

Output:
Removed Element: 5
Updated List: [2, 3, 7]

6. clear() - Remove all items from the list.

prime_numbers = [2, 3, 5, 7, 9, 11]


# remove all elements
prime_numbers.clear()

# Updated prime_numbers List


print('List after clear():', prime_numbers)

Output:
List after clear(): []

Returns the index of the specified element in the list. Raises ValueError if an item isn’t
7. index() -
found within the list.

animals = ['cat', 'dog', 'rabbit', 'horse']

# get the index of 'dog'


index = animals.index('dog')

print(index)

Output: 1

8. count() - Returns the frequency of an element appearing in the list.

# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]

# check the count of 2


count = numbers.count(2)

print('Count of 2:', count)

Output:
Count of 2: 3

Sorts the objects of the list in ascending or descending order. It uses a compare function if
9. sort() -
passed as an argument.

prime_numbers = [11, 3, 7, 5, 2]

# sorting the list in ascending order


prime_numbers.sort()
print(prime_numbers)
Output:
[2, 3, 5, 7, 11]
To sort the list in descending order an additional argument is passed in parentheses.
reverse = True

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort(reverse=True)

# print vowels
print('Sorted list (in Descending):', vowels)

Output:
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

10. reverse()- Reverse the order of the list items in place.

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]

# reverse the order of list elements


prime_numbers.reverse()

print('Reversed List:', prime_numbers)

Output:
Reversed List: [7, 5, 3, 2]

11. copy()- Return a shallow copy of the list i.e. two lists share the identical elements via reference.

# mixed list
prime_numbers = [2, 3, 5]

# copying a list
numbers = prime_numbers.copy()

print('Copied List:', numbers)

Output:
Copied List: [2, 3, 5]
Built-in List Methods/Functions in Python
Functions are a group of instructions that typically operate on sequences or objects in python.
Python provides plenty of built-in functions for lists.
1. len()- Calculates and returns the length or size of the list

languages = ['Python', 'Java', 'JavaScript']

# compute the length of languages


length = len(languages)

print(length)

Output: 3

2. max()- Returns the item with maximum value within the list

numbers = [9, 34, 11, -4, 27]

# find the maximum number


max_number = max(numbers)

print(max_number)
Output: 34

3. min()- Returns the item with minimum value within the list

numbers = [9, 34, 11, -4, 27]

# find the smallest number


min_number = min(numbers)

print(min_number)

Output: -4

4. list()- Return the list containing the elements of the iterable.

text = 'Python'

# convert string to list


text_list = list(text)

print(text_list)

# check type of text_list


print(type(text_list))

Output:
['P', 'y', 't', 'h', 'o', 'n']
<class 'list'>

5 Test each element of the list as true or not on the function passed as an
filter(function,sequence)-
. argument there to and returns a filtered iterator.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# returns True if number is even


def check_even(number):
if number % 2 == 0:
return True

return False

# Extract elements from the numbers list for which check_even() returns
True
even_numbers_iterator = filter(check_even, numbers)

# converting to list
even_numbers = list(even_numbers_iterator)

print(even_numbers)

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

Returns a list after applying the function passed as an argument to every


6. map(function, iterator)-
element of the iterable.

numbers = [2, 4, 6, 8, 10]

# returns square of a number


def square(number):
return number * number

# apply square() function to each item of the numbers list


squared_numbers_iterator = map(square, numbers)

# converting to list
squared_numbers = list(squared_numbers_iterator)
print(squared_numbers)
Output: [4, 16, 36, 64, 100]
7. all()- Returns True if all the items/elements present within the list are true or if the list is empty.
boolean_list = ['True', 'True', 'True']

# check if all elements are true


result = all(boolean_list)

print(result)

Output: True

sorts the elements of a given iterable in a specific order (ascending or descending) and
8. sorted()-
returns it as a list.

numbers = [4, 2, 12, 8]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output: [2, 4, 8, 12]

9. reversed()- computes the reverse of a given sequence object and returns it in the form of a list.
seq_string = 'Python'

# reverse of a string
print(list(reversed(seq_string)))

Output: ['n', 'o', 'h', 't', 'y', 'P']

10. sum()- Returns the sum of all the elements present within the list.

marks = [65, 71, 68, 74, 61]

# find sum of all marks


total_marks = sum(marks)

print(total_marks)

Output: 339

Special features of List:


The various features of a list are:
 Ordered: Lists maintain the order in which the data is inserted.
 Mutable: In list element(s) are changeable. It means that we can modify the items
stored within the list.
 Heterogenous: Lists can store elements of various data types.
 Dynamic: List can expand or shrink automatically to accommodate the items
accordingly.
 Duplicate Elements: Lists allow us to store duplicate data.

Tuple
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets. A tuple can have any
number of items and they may be of different types (integer, float, list, string, etc.).
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5);

A tuple can also be created without using parentheses. This is known as tuple packing.

my_tuple = 3, 4.6, "dog"


print(my_tuple)

Output
(3, 4.6, 'dog')

The empty tuple is written as two parentheses containing nothing −


tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is
only one value −
tup1 = (50,);
Accessing Tuple Elements
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside
of the tuple index range(6,7,... in this example) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result
in TypeError.

# Accessing tuple elements using indexing


my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0])
print(my_tuple[5])

Output
p
t

2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.

# Negative indexing for accessing tuple elements


my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

print(my_tuple[-1])
print(my_tuple[-6])

Output:
t
p

3. Slicing
We can access a range of items in a tuple by using the slicing operator colon [:]

#Accessing tuple elements using slicing


my_tuple = ('p','r','o','g','r','a','m')

# elements 2nd to 4th


print(my_tuple[1:4])

# elements beginning to 2nd


print(my_tuple[:-7])

# elements 5th to end


print(my_tuple[4:])

# elements beginning to end


print(my_tuple[:])
Output
('r', 'o', 'g')
('p', 'r')
('r’, ‘a’, ‘m’)
('p', 'r', 'o', 'g', 'r', 'a', 'm')

Built-in Tuple Functions


Python includes the following tuple functions –
1. len() - This function returns the number of elements present in a tuple.
Example:
tup = (1,2,3)
print(len(tup))

Output: 3

2. count() - This function will help us to find the number of times an element is present in
the tuple.
Example:
tup = (22, 45, 23, 78, 22, 22, 6.89)
tup.count(22)

Output: 3

3. index() - The tuple index() method helps us to find the index or occurrence of an
element in a tuple. This function basically performs two functions:
 Giving the first occurrence of an element in the tuple.
 Raising an exception if the element mentioned is not found in the tuple.

Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
print(tup.index(45))
print(tup.index(890))

Output:
2
7

4. sorted() - This method takes a tuple as an input and returns a sorted list as an output.
Moreover, it does not make any changes to the original tuple.

Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
sorted(tup)

Output:
[1, 2, 2.4, 3, 4, 22, 45, 56, 890]

5. min() - gives the smallest element in the tuple as an output. Hence, the name is min().

Example:
s = (85, 55, 47, 98, 32, 65, 62, 54)
x = min(s)
print(x)

Output:
32

6. max() - gives the largest element in the tuple as an output. Hence, the name is max().

Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
max(tup)

Output
890

7. sum() - gives the sum of the elements present in the tuple as an output.
Example:
tup = (22, 3, 45, 4, 2, 56, 890, 1)
sum(tup)

Output:
1023

Tuple Operations

Operator Example

The + operator returns a tuple containing all the elements of the t1= (1,2,3)
first and the second tuple object.
t2= (4,5,6)
t1+t2
Output:
(1, 2, 3, 4, 5, 6)
Operator Example

The * operator Concatenates multiple copies of the same tuple. t1= (1,2,3)
t1*4
Output:
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

Dictionary
The dictionary is an unordered collection that contains key:value pairs separated by commas
inside curly brackets {}.
Dictionary holds pairs of values, one being the Key and the other corresponding pair element
being its Key:value. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
dict={'Name':'Ravi',"Age":'32'}

Accessing Values in Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets.

my_dict = {'name': 'Jack', 'age': 26}


print(my_dict['name'])

Output:
Jack

Changing and Adding Dictionary elements


Dictionaries are mutable. We can add new items or change the value of existing items using
an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.

# Changing and adding Dictionary Elements


my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27
print(my_dict)

# add item
my_dict['address'] = 'Downtown'
print(my_dict)

Output:

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Removing elements from Dictionary


All the items 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:
1. del keyword:

test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}


# Printing dictionary before removal
print("The dictionary before performing remove is : ", test_dict)
# Using del to remove a dict removes Mani
del test_dict['Mani']
# Printing dictionary after removal
print("The dictionary after remove is : ", test_dict)

Output:
The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha': 21}
The dictionary after remove is : {'Arushi': 22, 'Haritha': 21}

2. clear() method:

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
squares.clear()
print(squares)

Output: {}
Dictionary built in functions
1. len()- Return the length (the number of items) in the dictionary.

# Dictionary Built-in Functions


squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(len(squares))

Output: 6

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

# Dictionary Built-in Functions


squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(sorted(squares))
Output: [0, 1, 3, 5, 7, 9]

Dictionary Methods
1. clear()- The clear() method removes all items from the dictionary.

# dictionary
numbers = {1: "one", 2: "two"}

# removes all the items from the dictionary


numbers.clear()
print(numbers)

Output: {}

2. copy()- They copy() method returns a copy (shallow copy) of the dictionary.

original_marks = {'Physics':67, 'Maths':87}

copied_marks = original_marks.copy()
print('Original Marks:', original_marks)
print('Copied Marks:', copied_marks)

Output: Original Marks: {'Physics': 67, 'Maths': 87}


Copied Marks: {'Physics': 67, 'Maths': 87}

3. fromkeys()- The fromkeys() method creates a dictionary from the given sequence of
keys and values.

# keys for the dictionary


alphabets = {'a', 'b', 'c'}

# value for the dictionary


number = 1
# creates a dictionary with keys and values
dictionary = dict.fromkeys(alphabets, number)
print(dictionary)

Output: {'a': 1, 'c': 1, 'b': 1}

4. get()- The get() method returns the value for the specified key if the key is in the
dictionary.

marks = {'Physics':67, 'Maths':87}

print(marks.get('Physics'))

Output: 67

5. items()- The items() method returns a view object that displays a list of dictionary's
(key, value) tuple pairs.

marks = {'Physics':67, 'Maths':87}

print(marks.items())

Output: dict_items([('Physics', 67), ('Maths', 87)])

6. keys()- The keys() method extracts the keys of the dictionary and returns the list of
keys as a view object.

numbers = {1: 'one', 2: 'two', 3: 'three'}

# extracts the keys of the dictionary


dictionaryKeys = numbers.keys()
print(dictionaryKeys)

Output: dict_keys([1, 2, 3])

7. pop()- The pop() method removes and returns an element from a dictionary having the
given key.

# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }

element = marks.pop('Chemistry')
print('Popped Marks:', element)

Output:
Popped Marks: 72
8. update()- The update() method updates the dictionary with the elements from another
dictionary object or from an iterable of key/value pairs.

marks = {'Physics':67, 'Maths':87}


internal_marks = {'Practical':48}

marks.update(internal_marks)
print(marks)

Output:
{'Physics': 67, 'Maths': 87, 'Practical': 48}

Python Control Flow Statements and Loops


In Python programming, flow control is the order in which statements or blocks of code are
executed at runtime based on a condition.
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.
You can execute different blocks of codes depending on the outcome of a condition.
Condition statements always evaluate to either True or False.

There are four types of conditional statements.


1. if statement
2. if-else
3. if-elif-else
4. nested if

If statement
In control statements, the if statement is the simplest form. It takes a condition and evaluates
to either True or False.
If the condition is True, then the True block of code will be executed, and if the condition is
False, then the block of code is skipped, and the controller moves to the next line

number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output

36
Next lines of code

If – else statement
The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.
If the condition is True, then statement 1 will be executed If the condition is False, statement
2 will be executed.
Example

password = input('Enter password ')

if password == "PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")

Output 1:

Enter password PYnative@#29

Correct password

Output 2:

Enter password PYnative

Incorrect Password

If-elif-else statement
In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions
one after another. This is useful when you need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple
conditions one by one and if the condition fulfills, then executes that code.
Example

def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")

user_check(1)
user_check(2)
user_check(3)
user_check(4)

Output:

Admin
Editor

Guest

Wrong entry

Nested if-else statement


In Python, the nested if-else statement is an if statement inside another if-else statement. It is
allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is useful
when we want to make a series of decisions.
Example: Find a greater number between two numbers

num1 = int(input('Enter first number '))


num2 = int(input('Enter second number '))

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)

Output 1:

Enter first number 56

Enter second number 15

56 is greater than 15

Output 2:

Enter first number 29

Enter second number 78

29 is smaller than 78

Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the
condition is True. We also call it a loop statements.
Python provides us the following two loop statement to perform some actions repeatedly
1. for loop
2. while loop
For loop in Python
Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple.
Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
loop body
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.

# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

print("The sum is", sum)

Output:

The sum is 48

for loop with range()


The range() function returns a sequence of numbers starting from 0 (by default) if the initial
limit is not specified and it increments by 1 (by default) until a final limit is reached.
The range() function is used with a loop to specify the range (how many times) the code
block will be executed. Let us see with an example.

Example:

for num in range(10):


print(num)

Output:

6
7

While loop in Python


In Python, the while loop statement repeatedly executes a code block while a particular
condition is true.
In a while-loop, every time the condition is checked at the beginning of the loop, and if it is
true, then the loop’s body gets executed. When the condition became False, the controller
comes out of the block.
Example to calculate the sum of first ten numbers

num = 10
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print("Sum of first 10 number is:", sum)

Output

Sum of first 10 number is: 55

Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain
manner. For this purpose, we use three types of transfer statements.
1. break statement
2. continue statement
3. pass statements

Break Statement
The break statement is used inside the loop to exit out of the loop. It is useful when we want
to terminate the loop as soon as the condition is fulfilled instead of doing the remaining
iterations. It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately
Example of using a break statement

for num in range(10):


if num > 5:
print("stop processing.")
break
print(num)

Output

stop processing.

Continue statement
The continue statement is used to skip the current iteration and continue with the next
iteration.
Example of a continue statement

for num in range(3, 8):


if num == 5:
continue
else:
print(num)

Output

6
7

Pass statement
A pass statement is a Python null statement. When the interpreter finds a pass statement in
the program, it returns no operation. Nothing happens when the pass statement is executed.
It is useful in a situation where we are implementing new methods or also in exception
handling. It plays a role like a placeholder.
Example

months = ['January', 'June', 'March', 'April']


for mon in months:
pass
print(months)

Output

['January', 'June', 'March', 'April']

You might also like