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 text expression is True
.
If the text expression is
False
, the statement(s) is not executed.
In Python, the body of the
if
statement is indicated by the indentation. 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
.Example: Python if Statement:
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.") # indented
print("This is always printed.") # Unindented
num = -1
if num > 0:
print(num, "is a positive number.") # indented
print("This is also always printed.") # Unindented
Output:
3, is a positive number.
This is always printed.
This is also always printed.
Python if...else Statement:
Syntax of if...else
if test expression: Body of if else: Body of else
The
if..else
statement evaluates test expression
and will execute body of if
only when test condition is True
.
If the condition is
False
, body of else
is executed. Indentation is used to separate the blocks.Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = -3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output:
Negative Numer
Python if...elif...else Statement:
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The
elif
is short for else if. It allows us to check for multiple expressions.
If the condition for
if
is False
, it checks the condition of the next elif
block and so on.
If all the conditions are
False
, body of else is executed.
Only one block among the several
if...elif...else
blocks is executed according to the condition.
The
if
block can have only one else
block. But it can have multiple elif
blocks.Example of if...elif...else
# In this program, we check if the number is positive or negative or zero and
# display an appropriate message
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Positive Number
Python Nested if statements:
We can have a
if...elif...else
statement inside another if...elif...else
statement. This is called Nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so must be avoided if we can.
Python Nested if Example:
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
Python for Loop:
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.
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # List of numbers
sum = 0 # variable to store the sum
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum) # Output: The sum is 48
The range() function:
We can generate a sequence of numbers using
range()
function. Examaple:
range(10)
will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as
range(start,stop,step size)
. step size defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function
list()
.
For Example:
1. print(range(10)) # Output: range(0, 10)
2. print(list(range(10))) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3. print(list(range(2, 8))) # Output: [2, 3, 4, 5, 6, 7]
4. print(list(range(2, 20, 3)) # Output: [2, 5, 8, 11, 14, 17]
We can use the range() function in for loops to iterate through a sequence of numbers.
It can be combined with the
len()
function to iterate though a sequence using indexing.
For Example:
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
Output:
I like pop
I like rock
I like jazz
for loop with else
A for loop can have an optional else block as well. The
else
part is executed if the items in the sequence used in for loop exhausts.
Break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
For Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output:
0
1
5
No items left.
No comments:
Post a Comment