Bytes

If Else Statement in Python

Module - 3 Loops and Iterations in Python
If Else Statement in Python

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 :man_shrugging:.

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. :thinking:

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:

if condition:
    statement

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 :man_shrugging:. Any line of code outside the statement is automatically evaluated in both scenarios ūü§Ě.

Example:

payment = "Successful"
if payment == "Successful":
    print("Yes Payment is done")
  • 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:

if condition:
    statement(s)
else:
    statement(s)

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.¬†

credit_score = 720

if credit_score > 700:
    print("Congratulations, your loan application has been approved!")
else:
    print("We're sorry, your loan application has been rejected.")

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:

if condition_1:
    statement_1
    if condition_2:
        statement_2
    elif condition_3:
        statement_3
    else:
        statement_4
else:
    statement_5

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:

hours_worked = 45
hourly_rate = 20

if hours_worked <= 40:
    payment = hours_worked * hourly_rate
else:
    overtime_hours = hours_worked - 40
    payment = 40 * hourly_rate + overtime_hours * hourly_rate * 1.5
    
    if hours_worked > 60:
        payment += overtime_hours * hourly_rate * 0.5
        
print("Total payment:", payment)
  • 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:

if condition1:
    statement1
elif condition2:
    statement2
else:
    statement3

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:

# Get input from the user
hours_worked = int(input("Enter the number of hours worked: "))

# Define the hourly rate and calculate the payment amount
hourly_rate = 10  # $10 per hour
if hours_worked <= 0:
    payment_amount = 0
elif hours_worked <= 40:
    payment_amount = hours_worked * hourly_rate
else:
    # For hours worked above 40, apply 1.5 times the hourly rate for overtime
    overtime_hours = hours_worked - 40
    payment_amount = 40 * hourly_rate + overtime_hours * hourly_rate * 1.5

# Display the payment amount to the user
print("The payment amount is $", payment_amount)
  • 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?

a = 5

if a > 4:
    print("A")
elif a > 2:
    print("B")
else:
    print("C")
  1. A 
  2. B  
  3. C 
  4. None of the above

Answer: A

Online Python Compiler
Open Compiler
Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

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

© 2023 AlmaBetter