📚 What is an 'if' Statement?
In Python, an if statement lets you run certain code only when a condition is true. It's like asking a question and then doing something based on the answer.
📝 Quick Study Guide
- 🔑 Condition: A statement that can be either
True or False.
- ⚙️ Syntax:
if condition: followed by indented code.
- 💡 Indentation: Python uses indentation (spaces) to know which code belongs inside the
if statement.
- ➕
else: Optional. Runs code if the if condition is False.
- 🔗
elif: Short for "else if". Checks another condition if the first if was False.
🧪 Examples
Here are some simple examples:
- Example 1:
age = 12
if age >= 13:
print("You are a teenager.")
else:
print("You are not a teenager.")
- Example 2:
score = 75
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good job!")
else:
print("Keep practicing.")
🧠 Practice Quiz
- What keyword starts an 'if' statement in Python?
start
if
condition
then
- What symbol is used to check if two values are equal in an 'if' statement?
=
==
!=
<>
- What happens if the condition in an 'if' statement is False?
- The code inside the 'if' statement runs.
- The code inside the 'else' statement runs (if there is one).
- The program crashes.
- Nothing happens.
- Which of the following is the correct way to write an 'if' statement?
if condition then:
if condition:
if (condition)
if condition
- What does 'elif' stand for?
- else if
- end if
- else ignore
- easy if
- What is the purpose of indentation in an 'if' statement?
- To make the code look pretty.
- To tell Python which code belongs to the 'if' statement.
- To confuse the programmer.
- It has no purpose.
- What will be the output of the following code?
x = 5
if x > 10:
print("x is greater than 10")
else:
print("x is not greater than 10")
x is greater than 10
x is not greater than 10
- Error
- Nothing
Click to see Answers
- B
- B
- B
- B
- A
- B
- B