Move from Excel to Python with Pandas Transcripts
Chapter: Appendix: Python language concepts
Lecture: Concept: if/else

Login or purchase this course to watch this video and the rest of the course contents.
0:02 The most common control flow structure in programming has to be the "if" statement. Let's see how we do "if" statements in Python.
0:10 Here we have a simple console program, probably this bit of code is running in some kind of a loop or something like that,
0:16 and we are asking the user for input saying "what is your command?", either list the items by typing L or exit from the program by hitting x.
0:24 And we capture that string and we say "if", so simple keyword "if"... some boolean test, so in this case the command is == 'L'
0:33 so that means is the command equal to L: (colon) and then define what we are going to do in that case.
0:38 In this case we are going to list the items, we could do multiple lines, we are just doing one here.
0:43 Now we don't say "else if", in Python we say "elif", for short, but then we just have another test,
0:49 so if it's not L and the command happens to be x, then we are going to exit. And those are the two options that we are expecting,
0:55 but if we get something that we don't expect, like "hello there", or empty enter or something like that,
1:01 we'll be in this final bit here where it says "Sorry, that wasn't understood". So we start with "if" some kind of boolean expression, and remember,
1:09 we could just say "if" command: and leverage the truthiness of that value, and that would run if they provided some kind of input at all,
1:16 but if we want to test for else, we say if command == 'L', we have these additional as many as you want "else if" tests
1:22 and there is a final optional "else" clause.


Talk Python's Mastodon Michael Kennedy's Mastodon