Describe the various control statement with example.
Q.) Describe the various control statement with example.
Subject: Object Oriented Programming MethodologyControl Statements
- if statement: The if statement is used to execute statements if a specified condition is true.
if condition:
statements
For example, the following code checks if a variable x
is greater than 0 and prints "Positive" if it is:
x = 5
if x > 0:
print("Positive")
- elif statement: The elif statement is used to handle additional conditions if the first if condition is false.
if condition1:
statements
elif condition2:
statements
For example, the following code checks if a variable x
is greater than 0, and if it is, it prints "Positive". If x
is less than 0, it prints "Negative":
x = -5
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
- else statement: The else statement is used to execute statements if none of the previous conditions are true.
if condition1:
statements
elif condition2:
statements
else:
statements
For example, the following code checks if a variable x
is greater than 0, and if it is, it prints "Positive". If x
is less than 0, it prints "Negative". If x
is equal to 0, it prints "Zero":
x = 0
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
- for loop: The for loop is used to iterate over a sequence of items.
for item in sequence:
statements
For example, the following code iterates over a list of numbers and prints each number:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
- while loop: The while loop is used to execute statements while a specified condition is true.
while condition:
statements
For example, the following code prints numbers from 1 to 10:
num = 1
while num <= 10:
print(num)
num += 1
- break statement: The break statement is used to exit a loop prematurely.
for item in sequence:
if condition:
break
statements
For example, the following code iterates over a list of numbers and prints each number until it reaches the number 5. Then, it exits the loop:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
print(number)
if number == 5:
break
- continue statement: The continue statement is used to skip the current iteration of a loop and continue with the next iteration.
for item in sequence:
if condition:
continue
statements
For example, the following code iterates over a list of numbers and prints each number except for the number 5:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number == 5:
continue
print(number)