Python for beginners: Conditions in Python

2018-07-24
Python for beginners Conditions in Python Is Shown in an illustrated image

Python is a very friendly programming language that is easy to learn. This article takes a look at conditional statements and how to use them in Python.

What are conditional statements:

Conditional statements are used to change the behavior of a program depending on whether certain conditions are true. Used in almost every programming language, conditional statements generally take the form of an if or switch condition.

The “if” condition:

In Python, an if-statement consists of the word “if,” followed by the condition and then a colon. The colon is required since it separates the header of the statement from the body. It is important to take care with your indentations in Python, as improper indentation may result in errors that are difficult to troubleshoot. The condition after the if word has one of two possibilities. If it is true, then all the following statements will get executed. If the condition is false, the program will skip the lines of code associated with the if-statement and move on to whatever comes after.


Once you have set up your if-statement, you need to give the computer instructions to follow if the condition is true. Begin by typing a single tab space, which is the equivalent to using four spaces, to tell the computer to include the line. Each line of code that will be included with the if-statement needs to begin with that tab space.

Compound statements:

Compound if-statements consist of a header and a body. The header is the if statement and the body if whatever indented code you write below. The code can contain another if-statement with more, double-indented code. There’s no limit to the number of if-statements you can write inside one another.

What “else”:

What if we want one thing to happen when a condition it true and something else when the statement is false? We can address that by using an if-else statement. The statement is checked to see if it is true. If it is, then the code block written under the “if” is run. If the statement evaluates to false, all of the statements under the “else” statement are run instead. Only one block of code can be chosen.


Got excited. You can practice what you have just read in one of the available RoboGarden challenges. Start your learning journey with RoboGarden now.


Python Series Introduction to Python

相关的博客

Start Python coding

Let's start python coding with RoboGarden learning journey.

Got an invite