Python Fundamentals Control Flow
Transcript from the "Control Flow" Lesson
>> Nina Zakharenko: The if statement, the contents of the if statement will only run if the condition is true, otherwise they don't. So if 3 is less than 5,
>> Nina Zakharenko: We should see that printed out. If we do it the other way around,
>> Nina Zakharenko: If 3 is greater than 5,
>> Nina Zakharenko: We won't see anything. You don't need parentheses in your if statement here like you might in other languages, you just have to put a condition.
>> Nina Zakharenko: If statements also work with truthiness. So let's say a is an empty list and I say if a print("Hello"), what am I gonna see?
[00:00:56] Nothing, right. What if I had a variable b, a list that had some items in it, and I say, if b print("Hello"), what will I see?
>> Speaker 2: You'll see it.
>> Nina Zakharenko: I'll see it, yeah, it's truthy. So,
>> Nina Zakharenko: If statements have a few more components to them. We know that the code in the if statement only runs if the if statement is true, right?
[00:01:30] So I say a is true, if a print("Hello"). It'll run, right? If we want something to run in the opposite case, if a is not true, we'll say else, and use the colon and say Goodbye, right? So that prints out Hello if a was false, and we wrote the same code,
>> Nina Zakharenko: We'll get Goodbye.
>> Nina Zakharenko: One other thing here is else if. So let's say a is equal to true, and b is equal to true. So I can say, actually, sorry, let's make a false, and b true. So I can say, if a, right, if a is true, we're gonna print out 1.
[00:02:37] Otherwise, I will say that with else if or in Python abbreviated to elif. Also with a colon, oops.
>> Nina Zakharenko: We need a condition here, and else if is not an else statement. So we'll check for something else. We'll say, elif b is true, print("2"). And then else means if neither of those conditions are met, print this other thing.
[00:03:14] And you can have as many else ifs in your code as you want to. So in this case, it'll print out two. a was not true, so we skipped this. But this condition was true and so we went in here, and then we skipped the else because we found a condition that matched.