Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Conditional execution in Python is handled with the If statement. So, let's go ahead and make a working copy of conditionals.py, call it conditionals-working.py, and we'll Open that up and start by just defining a couple of variables. a and b equals 0 and 1. If we want to just execute some code, if a is less than b, all we do is we type if a < b: print ('this is true').
Now, when I save that and run it, you see that 'this is true' got printed. So, this print statement executed, and the way this works is the if keyword introduces the conditional, and the expression here, a is less than b, and that could be any expression that evaluates to True or False and a colon introduces the suite of code and so this could be a suite of code. It could be a number of things, and that gets executed if this expression evaluates to true. If the expression does not evaluate to true - I'll just change this 0 to 1, and a is no longer less than b, save that and run it - then nothing happens at all.
So, if we want something different to happen, if the expression is false, then I can simply say else and a colon and another suite of code, it is not True. So, if I save that and run it, then we get that here it is not true, and if I make this 1 a 0 again, save and run, then we get 'this is true.' So, this expression can actually be any expression that evaluates to true or false, and so I could just actually put the word True there, and it'll be true, save and run, this is true, or I can put the word False there, and save and run, and we get, 'it is not true.' So, that is the if and else in Python.
If is a keyword, and then it's followed by any expression that evaluates true or false and a colon and then a suite of code, and the optional else will execute its suite of code, if the condition is false and not true.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 101483 Viewers
61 Video lessons · 88250 Viewers
71 Video lessons · 72117 Viewers
56 Video lessons · 103881 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.