If Else and Ternary Operator in Python

Python Ternary and Logic Quiz

🧠 Python Control Structures & Ternary Logic

🧩 What are Control Structures?

Control structures guide the flow of your Python programs. The key conditional structures are:

  • if: Executes a block if a condition is true.
  • elif: Else if, checks another condition if previous ones failed.
  • else: Executes a block if all previous conditions are false.

🔍 Example


x = 5
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")
  

📊 Relational & Logical Operators

Operator Meaning Example
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equala >= b
<=Less than or equala <= b
andLogical ANDa > 0 and b > 0
orLogical ORa > 0 or b > 0
notLogical NOTnot a == b

🤹‍♂️ Ternary Operator

A shorthand for if-else.

max = a if a > b else b

✅ Reads: “If a is greater than b, set max = a, otherwise max = b.”

🌐 Nested Example


result = "A" if marks > 90 else "B" if marks > 70 else "C"
  
➤ Check marks > 90 → Yes → A
➤ No → Check marks > 70 → Yes → B
➤ No → C

🧪 Python Ternary & Logical Operator Quiz

Test your understanding of Python's conditional logic with 25 interactive questions below!

🧠 10 Python Programming Challenges

These problems will help you practice Python's control structures including if, elif, else, logical operators, and ternary expressions.

🚀 Let's Begin

1. Greater Number

Take two numbers as input. Print the greater number using if-else.

2. Grade Calculator

Input a student's marks (0–100). Use if-elif-else to print:

  • 90–100: Grade A
  • 75–89: Grade B
  • 50–74: Grade C
  • Below 50: Fail

3. Even or Odd

Take a number as input and print whether it is even or odd using the ternary operator.

result = "Even" if num % 2 == 0 else "Odd"
    

4. Login System

Ask for username and password. Check using if whether they match predefined values.

5. Leap Year Checker

Write a program to check if a year is a leap year.

Use nested if for the logic:

- Divisible by 4
  - Not divisible by 100 unless divisible by 400
    

6. Smallest of Three

Take 3 numbers and print the smallest using nested ternary operator.

smallest = a if (a < b and a < c) else (b if b < c else c)
    

7. Password Strength

Check if password contains more than 8 characters, has a digit, and a capital letter using logical operators.

8. Voter Eligibility

Check if the user is 18 or older. If yes, print “Eligible to vote”, else “Not eligible”.

9. Number Sign

Take a number and print whether it is positive, negative, or zero using if-elif-else.

10. Calculator (Basic)

Take two numbers and an operator (+, -, *, /) as input and perform the operation using if or match-case (Python 3.10+).


📌 Notes

  • For each problem, also try solving using a ternary operator if applicable.
  • Add validations where needed — e.g., for division by zero.

Post a Comment

0 Comments

Me