Conditional Statements in Python (if/else/elif)
Key Takeaways
The video covers conditional statements in Python, including if, else, and elif statements, and how to use them to control the flow of a program based on conditions or decisions. It provides a step-by-step tutorial on how to work with conditional statements, including the basic syntax, boolean expressions, and conditional logic.
Full Transcript
hello and welcome to this course on conditionals in Python in this very first video we won't be looking at any code at all instead what I want to do here is explain the main idea behind conditionals so that you develop an intuition for them and then in the following videos what we'll do is we're going to be layering code on top of that intuition and then we'll go into the e syntax in detail so you'll know how to use these so let's start with an example imagine I go to work every day and I work in this office at the end of a long day I'm looking forward to going home so this is my house and what I would prefer to do since it's been a long day and I'm quite tired is to go straight home we can call this my default path and unless something gets in the way this is what I would prefer to do but how do I know if something has gotten in the way well there's another step or another element here called a decision point and that's the moment just before I leave the office where I ask myself if there's anything in my fridge at home if there isn't I'm going to be hungry tonight so rather than go straight home what I'll do is I'll swing by the supermarket we can call this the alternate path so there are these three elements a default path a decision point and an alternate path and these are the key ingredients to conditionals you could say in life but also in Python so let's consider an example that's a bit closer to Python imagine that this is your code editor this dark blue Square and on it you have some green lines these are lines of code right and if you've been writing Python and you haven't been using conditionals until now this is probably what your code looks like every line starts on the far left as far to the left as possible and when python execute your code it reads the lines one by one so this is sort of the default path you can consider that python is a bit lazy and would rather stay as far to the left as possible unless something forces Python to take a different path what conditionals allow us to do is to take one or more lines of code this is called a sweet or a block of code and indent them and by indenting them what we're doing is we're removing these lines of code from the main flow of this program so this code won't be executed every time that our script gets run so that's all well and good we have a main flow of our program and we have an optional block of code but the problem is Python doesn't know what to do here it doesn't know if it should run the optional block of code or if it should just ignore it and that's where the decision point comes in the decision point is a conditional structure which appears here on the last non indented line it contains a boolean that is to say an expression that resolves into true or false if it's true then Python will run the indented block of code and if it's false then it will ignore the indented block of code and jump to the next line which isn't indented a good metaphor for this is a railroad switch so we have the main flow of this code and then there is an alternate path you can think of those as two parallel train tracks and the decision point is the railroad switch which decides which path we're going to take so you can see we have the three key ingredients for conditional structures in Python there's a default path there's a decision point and there's an alternate path and the decision point determines whether we stay on the default path or we jump onto the alternate path so that's the main idea behind conditionals here we are looking at some code this is an IDE which I have opened in front of me and I have a very short very simple script it's just five lines five print statements so let's try running that and seeing what it does so when it runs it prints five statements right and this is like a simple agenda for the day so it starts with cutting up and it ends with going to bed this is going to be useful to explain conditionals because as I mentioned in the previous video conditionals allow us to take a block of code and remove it from the main flow of the script and so just by counting the number of statements that get printed out here we can see if lines of code ran or didn't run so let's say that on this particular day I don't want to mow the lawn walking the dog is enough of a task for today so I want to remove mowing the lawn the way I would do this and which we mentioned in the previous video is by indenting this line I'm going to move my cursor here then I indent it actually those are four spaces now watch what happens when I save so two things happened and you may have had to be paying very close attention to notice them but the first is that here on line two this red squiggly thing appears so it's telling me that there's something here which the IDE doesn't like the other thing which happens is that here in the problems tab there's a one so there is at least one problem with my code I'm going to start by ignoring these warnings and running my code anyway so this gives me a bit more information it tells me that there is an unexpected indent that's the arrow type it's an indentation error so if we think back to that analogy in the previous video with the two train tracks it's easier to understand this error what we have here is a main train track running along or starting on the left most part of the IDE what I did when I indented this line of code is I created a new train track a parallel train track but the problem is there's no railroad switch so there's no way to get from one track to the other and Python doesn't know if it should make the switch or under what circumstances it should make the switch and that's where the conditional statement comes in the conditional statement creates a smooth on-ramp to this other parallel train track and it also gives some reason or some logic to drive the decision whether or not to make that jump so I'll start by hitting return here so I have another line and then on what is now line two I'm going to create a conditional structure and I'll start with an if statement this is the simplest most basic conditional expression that we have in Python and the basic syntax looks like this it starts with a keyword if and this is purple so you can see that my IDE is recognizing this as a keyword and then it ends with a colon so the next question becomes what should come between the if statement and this colon well what we'll have here is a boolean statement and the boolean is some expression which resolves into true or false actually it's a truth e or false e as we'll see in a minute but let's start with true and false that's the simplest case we can we can think of so set this to true using just the keyword true and you see that when I save the problem count disappeared so now there are no problems and that red squiggly thing whose I don't actually know is also gone so Python seems happy with this let's try running it and seeing what happens okay so that ran correctly and we got five statements printed out now if we go back to these lines two and three reading this just in English already makes quite a lot of sense so if something do what's indented here and since in this case we said if true and true is always true then line three gets executed if we wanted to leave this line out we would set the boolean statement on line to to false so let's try running that just to confirm that I'm not making things up and you see this time four lines of code were printed out so one of them was left out and the one which was left out was line three okay so far so good so true and false are quite straightforward but there are cases which are not as clear or are not as intuitive these are values which are referred to as being true fee or false II so they're not quite true not quite false but they're truth II so an example of something which is false II is the number zero so you can see here again we got four lines so zero is false any other number including negative numbers is considered truth e so let's stick with pythonic tradition and try number 42 and in that case we get five lines so any number is truth e another false value is the value none the keyword none so if I say if none then I get four lines none can also be used indirectly so let's say I had a variable for instance a dog's name and I set that to none and I say if dog name then this is still none it's just via a variable and that's also considered false e ne populated variable is considered truth e so it doesn't matter what kind of value I have in the variable that variable will be considered truth e so for instance if I named my dog Fido then that's truthy and five lines are being printed out the actual value doesn't matter it could be wrong in the larger context of the program something else which you will often see used in conditional expressions and we'll look at this in a little bit more detail in the next video is comparison operators so if I were to say a dog name was equal to phyto which is true then this would be true if I say it's different or not equal then that's false II will be looking a bit more closely at comparison operators and how they can be combined with conditional expressions in the next video since the structures will be using their lend themselves more easily to comparisons but this was the if statement the simplest conditional expression we can have in Python in this video I'm going to be showing you how to select one of several code blocks so I'm going to start with an example which is very similar to what we did in the previous video so when I run this all of the lines print out because I've set my condition to true but what if I have enough time to do one thing so either I will mow the lawn or I will walk the dog well there is another structure I can use another keyword and it sounds a lot like English so when you read this even if you're not thinking in a pythonic way but just reading English it's already very intuitive that key word is the word else so let's first run this and you can see this time four lines of code were printed out let's step through this code quickly so python hits line - there's a conditional expression there and the boolean is true so it mows the lawn because this ran then what comes afterwards or the next indented block which is after the else doesn't run and then it picks up again here on line six so you remember that if statements are sort of an on/off switch for an indented block of code well the else gives us an alternative so if this had been set to false and then we ran this we would again get four lines printed out except this time we walk the dog instead of mowing the lawn so what the else is doing is it's giving us an alternative if the code which is indented after the if statement doesn't run then the else will run but only one of these will run okay so this allows us to select one out of two code blocks but what if we have more code blocks which we want to choose from there's a third statement which we can use and that's the Elif Elif is a condensation of else/if and you can think of it as an additional if statement let me show you with an example so as I mentioned the Elif is sort of a second if statement so when this runs line two is false so this indented block of code gets ignored Python then hits line four this is true so this will run and we'll visit grandma however the else will be left out since already one of the preceding ifs or elif's was true let's try running this just to make sure I'm telling the truth and you can see in this case we visit grandma but we don't walk the dog and we don't mow the lawn okay so there are a few things to keep in mind here the first is that in this example we only have one Elif but actually you could have had many of them in fact you can have an arbitrary number of elif's another thing to keep in mind is that the else isn't obligatory we have one here but you could also just not have one in that case it could be possible that no indented blocks of code will run because it's possible that both the if is false and all of the elif's resolved to false the else acts as a kind of catch-all and it will run if and only if all of the other conditionals was false another thing you need to keep in mind is you need to be very careful when writing out these statements you need to debug carefully because as soon as one of these statements is true the others are completely ignored for example if I set the very first one to true and then have something nonsensical here so this which is obviously false if I run this watch what happens I didn't get an error everything went well and the reason for that is that as as Python hits this true boolean and runs line three when it's done with line three it jumps down to line eight and it completely ignores everything here and it doesn't check it for well for anything so you can have something like this which you know it's not even wrong it's just completely invalid and it doesn't get checked my IDE is warning me but if you're not using an IDE if you're just using a flat text editor or you're just not careful bugs can slip in this way so while testing do make sure that you test every possible condition another thing to keep in mind is that the first in that that block of code which has a true conditional will run and the others will be completely left out so you should pay attention and make sure that you are ordering them according to your own priorities so the one which is most important to you comes first so that one runs in case several conditions are true in fact speaking of several true conditions I can show you what happens one several of these conditions is true so if I run this we mow the lawn but we didn't visit Grandma even though that was true as well so you know to rub this in again the first true conditional will have its code block executed and the rest of them will be left out so if you have an else statement in there at most one of these blocks of code will be run if you have no else statements it's possible that none of them will be run if they're all false so in the previous video I mentioned that in this video we would circle back to comparison operators and use them in an example here so I'll make some quick adjustments to my code okay so here on line one I've set a temp variable this is the day's temperature and is currently set to zero so it's kind of a cold day I have a comment here specifying that these are a centigrade so if the temperature is below 15 degrees centigrade it's a bit warm but it's not super hot it's kind of a good temperature to mow the lawn since that's a physical activity if the temperature is below zero then it's quite a cold day and maybe I should go visit grandma and make sure she's okay otherwise if I did neither of these things then I can walk the dog because I have time so let's see what happens when I run this so you can see in this case I mowed the lawn since the temperature is below fifteen this was true everything else was ignored both this condition the Elif and the if were true this is a very simple example but it's a good example of a common use of conditional statements where you will have some value which falls on some kind of scale and then using ifs Elif and Elsa's you are responding to those different circumstances and to different values which are allowing you to adjust the way your code responds to those circumstances so we looked at three key words here we revisited if I also introduced a leaf and else please don't forget to test these thoroughly make sure that you order the indented blocks of code according to your priorities and remember this is a good way to have your code respond to different conditions or different inputs or different things that might be happening in this video I'm going to be telling you about two things first I'm going to introduce ways in which you can write conditional expressions on a single line and then after that I'm going to introduce the path statement the path statement isn't actually a conditional expression but it's something which is useful to know if you're starting to write code which contains conditional expressions okay so let's start with those one-line conditionals the first one I'm going to show you looks like this so I set up my conditional over here and you can see that the ID is happy it's not complaining about anything and next I bring one or more of the statements which would have been indented up into a single line so let's see what happens when I run this so you can see everything ran correctly I didn't get any errors my IDE also didn't complain at me the way this worked is the conditional expression gets evaluated the boolean gets evaluated in this case it's true and then all of the lines or all of the statements which follow it and which are separated by semicolons get executed so this works my IDE is happy Python seems happy there were no errors what's the problem well this is considered unpaid for neck in fact in pep eight you are actively discouraged from using this structure or this pattern and that might be a bit hard to understand with an example like the one we have here which is you know a bit trivial but the problem with this way of writing conditional statements on a single line is that they can quickly get out of hand as soon as you are working on some code which is non-trivial it might also be code you are not familiar with so you're reading someone else's code then this can be quite tricky to understand and it can get quite confusing and therefore error-prone so I guess what I'm saying is this works but please don't use it the main reason I'm showing you how this works or that it does work is because you may come across it in some code that you see and so it's important that you understand what it is you're looking at so don't daisy chain statements after conditional expressions what you can do instead is to sandwich conditional expressions between statements let me show you what I mean so here I have a single line on line 1 and there are actually two expressions or two python statements and sandwiched between them is a conditional expression so if true else something else and this is quite intuitive you can read this just with your English reading hat on rather than your Python hat on and it already makes a lot of sense so do this if true otherwise do something else and let's see what happens when we run this so you can see we got up since this is true but we didn't mow the lawn since this is true and we've already run this statement so this is one way in which you can write conditional statements on a single line this is considered very pythonic you are encouraged to use this the reason this is preferred is because you have two statements right you're choosing from between two statements so this is much easier for people to wrap their heads around when they're reading your code okay let me reset my code here so the last thing I wanted to show you in this video is the path statement and the path statement is very useful when you're writing out code and you're including conditional statements so let's say that I have a program in my head and right now what I'm doing is I'm typing it I'm making my idea into a reality and my idea includes different decision steps so I could have one here on line two and what I've done now is I'm sort of setting up the scaffolding for my code so I will have a decision structure here and I will have something which comes here but I haven't written that yet and probably like many of you I'm planning on writing my code iteratively so step by step and I've saved this work in progress but you can see that my IDE is already not happy it's telling me there's a problem and if I try running this for instance because I'm testing my code I get an error and the error is that there is nothing indented here so we have a conditional structure and this should be a launching off point for potentially an indented block of code it's a railroad switch remember except we have a railroad switch but a single train track so how do we get around this well that's where we can use the path statement so this is purple you can see that it's being recognized by my IDE as a keyword I'd no longer have any warnings about problems I've saved this code already and when I run it nothing happens I didn't get any errors so what it does is it allows me to build out my scaffolding sort of the logic that I have in mind but I don't have to complete all of the indented blocks of code before I can sort of test the rough logic of my solution so path statements are very useful for that so we looked at two things here we looked at two different ways in which you can write conditional statements on a single line one of them was a way you should write them and another was a way you should not be writing them but you should be aware of both next we looked at the path statement so that's it for this video in the next one I'll remind you of all of the different things that we looked at in this course and what videos we discuss them in so that you can go back and review if you need to this is our summary video and in it I'm going to go over the main ideas that we saw in each of the previous videos for each concept we discuss here I'm going to be reminding you of which video we encountered that topic in so that if you want to go back and review you'll know where to find it in the very first video in the intro video we talked about the main ideas behind conditionals in Python and I mentioned that there are three key elements there is a default path so this is sort of the main flow of your script then there is a decision point and finally there's an alternate path the decision point contains the conditional structure and it contains a boolean expression so something that resolves to true or false or actually truthy or false II and depending on whether or not it's truth or false II then the alternate path gets run or it doesn't next in the video after that we looked at the if statement so the if statement is the simplest conditional expression you can have the syntax starts with a keyword if and it ends with a colon what comes between the if and the colon is a boolean statement so this is anything which can be understood as true or false or truthy or false II and you can think of the if statement is a kind of on/off switch for the indented block of code so if the boolean resolves to something truthy then that block of code will be run and if not it will just be ignored and left out in the video after that I told you about the Elif and elf statements so if if is a kind of on-off switch for an indented block of code then Elif and else allow you to make selections between several indented blocks of code there are a few key things to keep in mind here one is that the first of these statements which is true will have its code block executed and all of the other ones will simply be left out and ignored so you have to be careful when you're ordering these make sure that the order in which you write them reflects your order of preference another thing to keep in mind is that the else is a kind of catch-all so if none of the boolean statements in the if or in any of the elif's was true then the else will run and it'll always run the else is optional you don't have to include one and you can have as many elif's as you want but keep in mind that at most one of the indented blocks of code will run next in the video after that we looked at single line conditionals and there are two ways to write these the first is actually discouraged so this is a structure where you have an if statement followed by a colon and then you have different statements which are separated by semicolons now this is discouraged and it's not considered pythonic because although the example we looked at was relatively trivial since we want to focus on the syntax as soon as you're writing something a bit more interesting so not trivial then these can get difficult to read and difficult to follow another kind of single line conditional which is encouraged is that where you squeeze or you sort of sandwich the conditional structure between two statements so you have the first statement then you have an if boolean else and then a second statement and this reads pretty much the way you would read it in English so the first statement will be run if the boolean is true the-- otherwise the other statement will be run and that brings us to the end of the last video of this course i hope you enjoyed this journey i hope you learned something new keep in mind there's always a lot to learn there's a lot to read and there's a lot to watch over at real python so i hope you'll be visiting us and i look forward to seeing you again bye bye
Original Description
In this step-by-step tutorial you'll learn how to work with conditional ("if then else elif") statements in Python. Master if-statements step-by-step and see how to write complex decision making code in your programs.
In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.
→ Learn more about conditional statements in Python: https://realpython.com/python-conditional-statements/
→ Take our quiz and check your learning progress: https://realpython.com/quizzes/python-conditional-statements/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Prompt Craft
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
How to Create a Second Version of Yourself Inside Obsidian Using AI (Step-by-Step Guide)
Medium · ChatGPT
How to prepare for Spain civil service TIC exam using AI in 2026
Dev.to · David García
Going Viral! How I Created AI Kissing Videos Step by Step Easily Using AIAI.com
Medium · AI
How to prepare TIC teacher exams in Spain with AI (oposiciones 2026)
Dev.to AI
🎓
Tutor Explanation
DeepCamp AI