Thursday 15 February 2024

if and else in python


if Statements

if statements allow your code to make decisions. They test a condition and execute a block of code only if the condition is True. Here's the basic syntax:


if condition:
    # Code to execute if condition is True



age = 25
if age >= 18:
    print("You are eligible to vote")

else Statements

The else statement provides code to run if the if condition is False.


if condition:
    # Code to execute if condition is True
    # Code to execute if condition is False



number = 7
if number % 2 == 0:
    print("Number is even")
    print("Number is odd")

Key Points:

  • Indentation: Python relies on indentation to define code blocks. Make sure to indent the code within the if and else blocks.

  • Multiple Conditions (elif): Use elif to build chains of decisions (if...elif...else).

  • Boolean Expressions: The conditions after if and elif should be expressions that evaluate to True or False (e.g., using comparison operators like ==, >, <).

Example with elif:


score = 75
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
    print("Grade: D")

Example 1: Traffic Light Simulation


color = "green"

if color == "red":
elif color == "yellow":
else# Assuming it's green here

Example 2: Number Guessing Game


import random  # Import for generating random numbers

secret_number = random.randint(1, 50)
guess = int(input("Guess a number between 1 and 50: "))

if guess == secret_number:
    print("You guessed it correctly!")
    if guess > secret_number:
        print("Too high, try again.")
        print("Too low, try again.")

Example 3: Login Validation


username = "admin"
password = "secret123"

user_input = input("Enter username: ")
password_input = input("Enter password: ")

if user_input == username and password_input == password:
    print("Access granted.")
    print("Invalid credentials.")

Example 4: Even or Odd


num = int(input("Enter a number: "))

if num % 2 == 0:
  print("The number is even.")
  print("The number is odd.")

Example 5: Calculating Discounts


price = float(input("Enter the price of the item: "))

if price >= 1000:
    discount = price * 0.15  # 15% discount
    print("You get a discount of", discount)
    final_price = price - discount
    print("Final price:", final_price)
    print("No discount applicable.")

Example 6: Leap Year Checker


year = int(input("Enter a year: "))

if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print("It's a leap year!")
            print("Not a leap year.")
        print("It's a leap year!")
    print("Not a leap year.")

Example 7: Simple Calculator (using nested if-else)


num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operator == "+":
    print(num1, "+", num2, "=", num1 + num2)
elif operator == "-":
    print(num1, "-", num2, "=", num1 - num2)
elif operator == "*":
    print(num1, "*", num2, "=", num1 * num2)
elif operator == "/":
    if num2 == 0# Check for division by zero
        print("Error: Cannot divide by zero")
        print(num1, "/", num2, "=", num1 / num2)
    print("Invalid operator.")

Let's delve into some potential interview questions about if-else statements in Python, along with strong answers.

Beginner Questions

  • "Explain the basic purpose of if, else, and elif statements in Python."

  • Answer:

  • "if: Executes a code block if a certain condition is True.

  • else: Executes a code block if the if condition is False.

  • elif: Used to create additional, alternative conditions to check if the original if condition is False."

  • "Describe the importance of indentation within if-else blocks."

  • Answer: "Indentation is crucial in Python. It defines which code belongs to the if, elif, and else blocks. Incorrect indentation leads to syntax errors or unexpected program behavior."

Intermediate Questions

  • "Can you write an example demonstrating how to use nested if-else statements?"

  • Answer: "Certainly, consider a grade calculator:
    score = 82
    if score >= 90:
      print("Grade: A")
        if score >= 80:
            print("Grade: B")
            print("Grade: C")

  • "How do you incorporate logical operators (and, or, not) within if conditions?"

  • Answer: "Logical operators combine multiple conditions:
    if age >= 18 and has_license:
        print("Eligible to drive")

  • "What is the concept of short-circuit evaluation in the context of if-else?"

  • Answer: "Python sometimes skips evaluating the second operand in a logical expression if the first operand determines the result (e.g., in or if the first condition is True, in and if the first condition is False). This can potentially affect performance."

Advanced Questions

  • " In what scenarios might using multiple if statements be less efficient than elif chains?"

  • Answer: "With multiple separate if statements, every condition is evaluated. elif chains stop evaluation once a condition is True, potentially saving computational steps."

  • "Can you think of creative ways to make code more concise or readable using if-else statements?"

  • Answer: "Yes, sometimes we can use the ternary operator for simple conditions: result = 'Eligible' if age >= 18 else 'Not eligible'. Also, early returns with multiple if blocks can often help simplify logic flow."

Interviewer Tips

  • Adapt Difficulty: Cater the questions to the candidate's experience level.

  • Practical Examples: Ask them to code small solutions with if-else.

  • Reasoning: Dive into their thought process on why they make certain choices within their use of if-else.

Let me know if you'd like more questions, variations on these, or a focus on specific skill levels!

08 if and else in python

No comments:

Post a Comment

Note: only a member of this blog may post a comment.