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:.
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: 🔢
How to write If-else statement in Python?
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 🤝.
payment = "Successful" if payment == "Successful": print("Yes Payment is done")
2. If Else:
Naveena reviews syntax for if else statements.
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.
3. Nested IF Statement:
Naveena reviews syntax for nested if statements.
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 .
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)
4. If-Elif-Else Statement:
Naveena reviews syntax for if elif else statements.
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.
# 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)
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.
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
Answer: B. A single-line if statement can contain multiple conditions, whereas a multi-line if statement can only contain one condition
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
Answer: B. By using comparison operators
a = 5 if a > 4: print("A") elif a > 2: print("B") else: print("C")
Related Tutorials to watch
Top Articles toRead