C – Decision Making

C - Decision Making

Conditions and Statements

if ,if –else, elif

Conditions and if statements are programming constructs used to make decisions in code based on certain conditions.

A condition is an expression that evaluates to a Boolean value, which is either true or false. For example, 2 < 3 is a condition that evaluates to true because 2 is less than 3, whereas 5 > 10 is a condition that evaluates to false because 5 is not greater than 10. An if statement is used to execute a block of code if a condition is true. Here’s an example:

				
					if x > 0:
    print("x is positive")

				
			

In this example, the condition x > 0 is checked. If it evaluates to true, the code inside the if statement (in this case, the print statement) is executed. If the condition is false, the code inside the if statement is skipped.

You can also use an else statement to specify what should happen if the condition is false. For example:

				
					if x > 0:
    print("x is positive")
else:
    print("x is not positive")

				
			

In this example, if the condition x > 0 is true, the first print statement is executed. Otherwise, the second print statement (inside the else block) is executed.

You can also use an elif statement to specify additional conditions to check. Here’s an example:

				
					if x > 0:
    print("x is positive")
elif x < 0:	
    print("x is negative")
else:
    print("x is zero")

				
			

In this example, if x is greater than 0, the first print statement is executed. If x is less than 0, the second print statement is executed. Otherwise, if x is exactly 0, the third print statement is executed.

Join To Get Our Newsletter
Spread the love