Logical Operators
Logical operators are used to combine conditional statements:
1. Logical AND: True if both the operands are true
2. Logical OR: True if either of the operands is true
3. Logical NOT: Reverse the result, i.e.) returns False if the result is true
Example: AND
a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("The numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
print("The numbers are greater than 0")
else:
print("At least one number is not greater than 0")
16
Example: OR a = 10
b = -10
c=0
if a > 0 or b > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")
if b > 0 or c > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")
Example: NOT x = 5
print(not(x > 3 and x < 10))
17
Loops in Python
In Python, there are two types of loops:
(1.) For loop (2.) While loop
Syntax: for variable in [iterable]: Syntax: while expression:
# actions statement(s)
print(variable) print(statements)
for number in [1, 2, 3, 4, 5]: count = 0
print(number) while (count < 9):
print 'The count is:', count
for number in [1, 2, 3, 4, 5]: count = count + 1
square = number * number print ("Good bye!“)
print(square)
x =0
for x in "Apple": while x < 5:
print(x) x=x+1
18= ‘, x)
print(‘x
numbers = [1, 2, 3, 4, 5, 6, 7, 8] i=1
for x in numbers: while i <= 10:
if x >= 4: print('6 * ',(i), '=',6 * i)
break(or)continue if i >= 5:
print(x) continue(or)break
i=i+1
Note: With the continue statement we can stop the current iteration, and continue
with the next:
x=0
while x < 5:
x += 1
if x > 3:
continue(or)break
print(‘x = ', x)
19
Exercise:
1.) Print First 10 natural numbers using while loop ?
2.) Calculate the sum of all numbers from 1 to a given number say 10?
3.) Write a program in Python to display the Factorial of a number?
20