Search Bar

Friday 26 May 2023

"Python Programming" Tut#09 | "If-else", "elif" statements

Python Tutorial 09

If-else statement

In Python, the if-else statement is used to perform different actions based on a certain condition. It allows you to execute a block of code if a condition is true, and another block of code if the condition is false.

The general syntax of the if-else statement in Python is as follows:

"Python Programming" Tutorial 09 | "If-else", "elif" statements
"Python Programming" Tutorial 09 | "If-else", "elif" statements

Here's an example of how you can use if and else in Python:
"Python Programming" Tutorial 09 | "If-else", "elif" statements
"Python Programming" Tutorial 09 | "If-else", "elif" statements

In Example 1, the condition x > 5 is evaluated. If it is True, the code block indented under the if statement is executed. Otherwise, if the condition is False, the code block indented under the else clause is executed.

In Example 2, the if statement is followed by an elif statement, which stands for "else if". Multiple elif statements can be used to check additional conditions. The conditions are evaluated one by one, and when a condition is True, the corresponding code block is executed. If none of the conditions are True, the code block under the else clause is executed.

Remember to indent the code consistently within the if, elif, and else blocks to define the scope of each code block.

You can also use multiple elif (short for "else if") statements to check for multiple conditions. Here's an example:

"Python Programming" Tutorial 09 | "If-else", "elif" statements
"Python Programming" Tutorial 09 | "If-else", "elif" statements

In this example, the code assigns a grade based on the score. Depending on the value of the score variable, the code will execute the corresponding block of code. If none of the conditions are true, the code block under the else statement will be executed.

0 comments:

Post a Comment