The "if..elif..else" statement is used for decision making based on some conditions.
The syntax of "if" statement is
if test expression:
statement(2)
In [1]:
x = 1
if x > 0:
print(x,"is positive number")
Pls note the indentation is important in Python. All the statements that is part of if statement must be indented.
In [2]:
x = 1
if x > 0:
print(x,"is positive number")
print('Outside of if condition')
In [3]:
x = 1
if x >= 0:
print(x,"is positive number")
else:
print(x,"is negative number")
print('End of if..else..')
In [4]:
x = -5
if x == 0:
print(x,"is zero")
elif x > 0:
print(x,"is positive")
else:
print(x,"is negative")
print('End of if statement')
In [5]:
x = 8
if x == 0:
print(x,"is zero")
elif x > 0:
if x == 10:
print(x,"is equal to 10")
elif x > 10:
print(x,"is greater than 10")
else:
print(x,"is lesser than 10")
else:
print(x,"is negative")
print('End of if statement')
In [6]:
sum = 0 # variable to hold the sum
nums = [1,2,3,6,8] # list of numbers
for num in nums:
sum += num
print(sum)
In [7]:
digits = [0,1,5]
for i in digits:
print(i)
else:
print('No more digits to print')
Range function is used to generate sequence of numbers. For example range(5) will generate 5 numbers starting from 0 to 4.
The syntax for range function is: range(start,stop,increment)
In [8]:
# range function with required sequence of numbers
print(range(10)) # this will not print sequence of numbers but generated on the fly.
# range function to start with 1 to 10 (note the stop argument is always treated as stop -1)
print(list(range(1,11)))
# range function different start and stop
print(list(range(2,8)))
# range function with start,stop and increment parameters
print(list(range(0,10,2)))
In [9]:
colors = ['Blue','White','Green']
for i in range(len(colors)):
print('I like',colors[i],'color')
While loop is used to iterate over a block of code as long as the test expression is true. Please note in python any non-zero value is True and zero is interpreted as False.
Mainly used when we do not know how many times to iterate
while test_expression:
# body of while
In [14]:
sum = 0
i = 1
while i <= 10:
sum += c
i += 1
print(sum)
In [11]:
n = 5
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print(sum)
In [15]:
counter = 0
while counter < 3:
counter += 1
print('Inside Loop')
else:
print('Inside Else')
In [17]:
for val in "string":
if val == "i":
break
print(val)
print("The End")
In [18]:
for val in "string":
if val == "i":
continue
print(val)
print("End Loop")
Pass statement is generally used as a placeholder for loop or function or classes as they cannot have empty body. So "Pass" is used to construct the body that does nothing.
The difference between comment (#) and "pass" is that python interpreter ignores the comments while it treat "pass" as no operation.
In [19]:
def dummy():
pass
dummy()
In [20]:
for i in range(3):
pass