Bytes

If Else Statement in Python

Last Updated: 12th December, 2023

Overview:

Condition checking and if-else statements are vital parts of programming because they control the flow of execution . The if-else statement in Python enables decision-making in code. It determines whether to execute a block of statements based on the result of a condition check 🔍. The statements in the if block runs if the condition is true . Otherwise, the else block's statements run.

If..Else.. statements-min.png

Why use if-else statements in Python?

If-else statements are fundamental constructs in Python used to make decisions based on a certain condition. These statements are used extensively in the industry to create complex decision-making algorithms.

For instance, consider the case of a payment processing system that needs to decide whether a payment transaction is fraudulent or legitimate. The system may use if-else statements to evaluate various parameters associated with the transaction, such as the amount, the location, and the cardholder details. If any of these parameters fail to meet the criteria defined by the system, the transaction will be flagged as fraudulent, and appropriate action will be taken. 

Another example of if-else statements is in web development, where these statements are used to validate user inputs, such as login credentials or form submissions. If the user input is valid, the program will execute specific actions, such as logging the user in or saving the form data to a database. However, if the input is invalid, the program will return an error message or prompt the user to correct their input.

If-else statements are widely used to create complex decision-making algorithms that help businesses automate their processes and reduce human error. They are a powerful tool for developers 💻 , allowing them to develop applications that efficiently perform complex operations.🚀

Python has several mathematical logics, which we frequently employ when we are using if else to evaluate circumstances around scenarios like those illustrated below: 🔢

  1. The Equals: The scenario is one in which we wish to determine whether variables a and b, denoted by the expression "a == b," are equal. 🤝
  2. The Not Equals: The scenario is one in which we wish to see if variable 'a' and variable 'b' are not equal, as shown by the statement 'a!= b'. ❌
  3. The less than: The situation where we wish to determine if the variable "a" is less than variable "b" is denoted as "a < b." ⬅️
  4. The less than or equal to: The scenario where we wish to verify whether a variable is less than or equal to a variable b is known as the "a less than or equal to b" scenario, denoted "a <= b." ⬅️🤝
  5. The Greater Than: The scenario is one in which we wish to determine whether the variable "a" is bigger than variable "b," which is indicated by the notation "a > b." ➡️
  6. The larger than or equal to: This scenario occurs when the expression "a >= b" is used to indicate that the variable "a" is greater than or equal to the variable "b." ➡️🤝

How to write If-else statement in Python?

  1. If statement

Syntax:

Loading...

The test expression is examined first. The body of the if statement is performed if the expression returns true. The statement that appears following the if statement is executed if it is false. Any line of code outside the statement is automatically evaluated in both scenarios 🤝.

Example:

Loading...
  • In the above example, the if statement checks if the value of the payment is equal to Successful.
  • If it is, the statement prints, "Yes, Payment is done."
  • If it is not the case, the statement does not execute.

2. If Else:

Naveena reviews syntax for if else statements.

Syntax:

Loading...

The test expression is first examined. 🔍 The sentences in the if block's body will be executed if true.  The statements listed below the if block is then carried out.  The lines in the else body are performed if the test expression returns false results, and the sentences after the if-else are executed. 

Loading...

This code checks if credit_score is greater than 700.

  • It uses a relational operator to compare the value of the variable credit_score greater than 700.
  • If the variable's value exceeds 700, it prints, "Congratulations, your loan application has been approved!".
  • Else, it prints, "We're sorry, your loan application has been rejected.

3. Nested IF Statement:

Naveena reviews syntax for nested if statements.

Syntax:

Loading...

The syntax starts by checking the condition_1 ; if it is true, it will execute statement_1 . After that, it will check condition_2  and execute statement_2  if true. If condition_2 is false , it will check condition_3  and execute statement_3  if true. If condition_3 is false , it will then execute statement_4 . If condition_1 is false , it will skip all the inner statements and execute statement_5 .

Example:

Loading...
  • In this example, the first if statement checks whether the employee worked less than or equal to 40 hours, in which case they will be paid their regular hourly rate for all their hours worked. 
  • If the employee worked more than 40 hours, the nested if statement calculates their payment with overtime pay.
  • If the employee worked over 60 hours, they would receive an additional bonus payment of half the overtime pay. 
  • Finally, the total payment is printed on the console.

4. If-Elif-Else Statement:

Naveena reviews syntax for if elif else statements.

Syntax:

Loading...

The if-elif statement checks multiple conditions. If Test Expression1 is true, its body runs. Else, Test Expression2 is matched. If true, elif1 runs. Else, Test Expression 3 is checked. If true, elif2 runs. Else, . Any code below the if-elif statement then executes.

Example:

Loading...
  • In this example, the user is prompted to enter the number of hours worked ⏰, and the program calculates the payment amount based on the following rules:
  • If the number of hours worked is zero or negative, the payment amount is zero.
  • If the number of hours worked is less than or equal to 40, the payment amount is simply the number of hours worked times the hourly rate .
  • If the number of hours worked is greater than 40, the payment amount is calculated as the payment for the first 40 hours (which is just the number of hours times the hourly rate) plus 1.5 times the hourly rate for each hour worked above 40 .

Conclusion:

The if-else statement is a decision-making statement in Python that determines whether to execute a block of statements based on the result of a condition check. If-else statements are used in the industry to create complex decision-making algorithms, such as fraud detection 🔒 in payment processing systems 💰 and form validation 📝 in web development 💻. The syntax for the if statement 🔢, if-else statement, and nested if statement 🔁 is presented.

Key takeaways:

  1. This lesson explains the use of if-else statements in Python for decision-making in code.
  2. An if statement checks a condition and runs a block of code if the condition is true.
  3. An else statement runs a block of code if the if statement's condition is false.
  4. A nested if statement has an if statement inside an if statement. It checks multiple conditions.
  5. An if-elif-else statement checks multiple conditions. Elif checks more conditions, and else runs a block of code if none of the conditions are true.
  6. The lesson also covers different mathematical logics used in if-else statements, such as equals, not equals, less than, greater than, and more.

Quiz:

  1. What is the difference between an if..else statement and an if..elif..else statement?
    1. An if..elif..else statement allows for multiple conditions to be checked whereas an if..else statement only allows for two conditions to be checked 
    2. An if..else statement allows for multiple conditions to be checked whereas an if..elif..else statement only allows for two conditions to be checked 
    3. An if..else statement allows for only one condition to be checked whereas an if..elif..else statement allows for multiple conditions to be checked

Answer: C. An if..else statement allows for only one condition to be checked whereas an if..elif..else statement allows for multiple conditions to be checked

  1. What is the difference between a single-line if statement and a multi-line if statement?
    1. A single-line if statement can only contain one condition, whereas a multi-line if statement can contain multiple conditions 
    2. A single-line if statement can contain multiple conditions, whereas a multi-line if statement can only contain one condition 
    3. A single-line if statement can contain multiple conditions, whereas a multi-line if statement can contain multiple conditions

Answer: B. A single-line if statement can contain multiple conditions, whereas a multi-line if statement can only contain one condition

  1. What is the advantage of using an if..elif..else statement over an if..else statement?
    1. An if..elif..else statement allows for multiple conditions to be checked, whereas an if..else statement only allows for two conditions to be checked 
    2. An if..elif..else statement allows for more efficient code, whereas an if..else statement requires more lines of code 
    3. An if..elif..else statement allows for more efficient code, whereas an if..else statement does not

Answer: A. An if..elif..else statement allows for multiple conditions to be checked, whereas an if..else statement only allows for two conditions to be checked

  1. How can you check if a certain condition is true or false in an if..else statement?
    1. By using the "if" keyword 
    2. By using comparison operators 
    3. By using the "else" keyword

Answer: B. By using comparison operators

  1. What is the output of the following code?
Loading...
  1. A 
  2. B  
  3. C 
  4. None of the above

Answer: A

Module 3: Loops and Iterations in PythonIf Else Statement in Python

Top Tutorials

Related Articles

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

Š 2024 AlmaBetter