A conditional statement is a set of rules performed if a certain condition met
CONDITIONAL STATEMENT IN PYTHON
1. IF STATEMENT IN PYTHON 3
The if statement is used to check a condition and if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional
a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")
1.1 Program: To check if a number is positive, negative or zero.
while True: number = int(input("Enter number: ")) # checking the number if number < 0: print("The entered number is negative.") elif number > 0: print("The entered number is positive.") elif number == 0: print("Number is zero.")
1.2 Program: To check if a number is even or odd.
while True: num = int(input("Enter any number: ")) no = num % 2 if no == 0: print(num, "is an even number") elif no == 1: print(num, "is an odd number")
LOOPS IN PYTHON 3
1. WHILE STATEMENT IN PYTHON 3
The while statement allows you to repeatedly execute a block of statements as long as a
condition is true. A while statement is an example of what is called a looping statement. A
while statement can have an optional else clause.
i = 1 while i < 6: print(i) i = i + 1
2. FOR LOOP IN PYTHON 3
The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence.
for i in range(1, 5): print(i) print('The for loop is over')
How it works?
In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range function. For example, range (1,5) gives the sequence [1, 2, 3, 4]. By default, range takes a step count of 1.
Now, if we supply a third number to range, then that becomes the step count.
for x in range(2, 30, 3): print(x)
We can also use ‘for loop’ in lists, tuple etc. We will discuss the concept of lists in later section.
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
BREAK & CONTINUE STATEMENT IN PYTHON 3
Both break and continue statements are used in loops. Break is used to stop the execution of loops and to execute the next instruction while continue statement rejects all statement in current iteration and gives control back to the starting of the loop.
1. BREAK STATEMENT
With the break statement we can stop the loop even if the while condition is true:
i = 1 while i < 6: print(i) if i == 3: break i = i + 1
2. CONTINUE STATEMENT
With the continue statement we can stop the current iteration, and continue with the next:
i = 0 while i < 6: i += 1 if i == 3: continue print(i)
# Note that number 3 is missing in the result
With the continue statement try this also:
i = 0 while i < 6: print(i) if i == 3: continue i += 1