Write a Python program for Linear search.
If you are searching for a Python code for Linear search, then this blog will be useful for you.
CONCEPTS INVOLVED
What is a Linear Search?
Linear search is a method of finding elements within a list. It is also called a sequential search. It is the simplest searching algorithm because it searches the desired element in a sequential manner.
It compares each and every element with the value that we are searching for. If both are matched, the element is found, and the algorithm returns the key’s index position.
How to create a list?
In Python programming, a list is created by placing all the items (elements) inside square brackets []
, separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []# list of integers
my_list = [1, 2, 3]# list with mixed data types
my_list = [1, "Hello", 3.4]
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
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.
What is if…else statement in Python?
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else
statement is used in Python for decision making.
Python if Statement Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression
and will execute statement(s) only if the test expression is True
.
If the test expression is False
, the statement(s) is not executed.
In Python, the body of the if
statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True
. None
and 0
are interpreted as False
.
Python print()
The print() function prints the given object to the standard output device (screen) or to the text stream file.
SOURCE CODE
OUTPUT
To know more about python, click the link below: