To start writing an if statement in Python, follow this basic syntax:
python
if condition:
# code to execute if condition is True
Here's the breakdown:
- Begin with the keyword
if
. - Leave a space and write a condition that evaluates to a Boolean value (
True
orFalse
). - End the line with a colon
:
. - On the next line, indent your code (usually 4 spaces) to indicate the block of code that will run if the condition is
True
.
For example:
python
x = 10
if x > 5:
print("x is greater than 5")
In this example, if x
is greater than 5, the print statement will execute
. You can also write a one-line if statement if you have only one statement to execute:
python
if x > 5: print("x is greater than 5")
This is less common but valid for simple conditions
. In summary, the key steps to start an if statement in Python are:
- Use the
if
keyword. - Write a condition (Boolean expression).
- Add a colon
:
. - Indent the following block of code that runs if the condition is true