What Will I Learn?
In this tutorial we'll be learning about conditionals and how we can control what statements get executed depending on whether certain values evaluate to true or false, and we've mentioned in previous tutorial that these true and false values are called boolean.
- You will learn how to use if statement
- You will learn how to use elif statement
- You will learn how to use else statement
Requirements
- Python2 / Python3
- Idle
Difficulty
- Basic
Tutorial Contents
So let's look at one of the simplest conditionals that we can write.
if True:
print("Conditional Was True")
So we're going to write an if statement and we'll say if and now the condition that we want to check whether it evaluates to true or false so we're just going to make this obvious for now and just say true then we'll put in a colon and hit enter, and now in the next line we want to be sure that we're indented over so that we're writing code within our if block so now we'll just print out a string here and I'll just say conditional was true,
Conditional Was True
so now if I save that and run it then we can see that it printed out that our condition was true. Now this print statement will only be executed if the condition after our if statement evaluates to true.
So what if I was to instead change this over to false
if False:
print("Conditional Was True")
now if I run this
====================== RESTART: /Jack/Desktop/main.py ======================
and we can see that it didn't print out the statement within our if block, now conditionals are usually not hard-coded to true and false values like this, we really want to put in some code that evaluates to true or false.
So for example I'm going to create a variable here
language = 'Python'
if language == 'Python':
print("Conditional Was True")
And I'll just call this variable language and I'll set this equal to Python, so now let's say that we only want to execute this print statement if the language is equal to Python so to do this we can say if language equals equals Python now notice that we have a double equals here, so this tests for equality, now this is different from the single equal sign which is for assigning values. So with this double equals here we're testing for equality and this will evaluate to true or false, and that will determine if the code in our if statement is executed,
Conditional Was True
so if we run this then we can see that it executed our print statement that the condition was true.
Now there are a lot of different comparisons that we can test for, and I've got these written out and a snippets file here
So that we have them as a reference. Now we went over some of these and our numbers tutorial but let's go ahead and just look through here really quick, so double equals test for equality, exclamation point equals test if something is not equal, greater than sign is for greater than. less than sign is for less than, greater than equal to is for greater than or equal to, less than equal to is for less or equal.
And then we have this object identity. Now some people wonder what the difference is between this and the double equal signs but when we use this is keyword check we're actually checking if values have the same ID or basically whether they're the same object in memory.
And we're going to look at an example of this in just a bit, but right now let's move on to else statements, so what if we wanted to execute one portion of our code if our language was equal to Python, but another portion of our code if it wasn't, so to do this we're going to use an else statement
language = 'Python'
if language == 'Python':
print("Language is Python")
else:
print("No match")
so first I'm going to change my print statement here and just print this to say that the language is Python, and now we want to execute some code if the language is not equal to Python, so to do this we're just going to put in an else statement and make sure that your else is back here on our base line and not within our if statement, so now we'll say else and now within our else block we will print out a string that just says no match
Language is Python
so now if we run this we can see that it printed out that the language is Python, so our check if the language is equal to Python is evaluating to true, so it's printing the code within that block and since it meets that conditional and never executes the code within our else block.
language = 'Java'
if language == 'Python':
print("Language is Python")
else:
print("No match")
Now if I was instead to change this language and set that equal to Java
No match
and rerun this, and we can see that it didn't meet the conditional for our if statement, so that evaluated to false, so then it dropped down to our else statement and executed that code.
Okay so what if we wanted to check for multiple languages and execute different code for each one that we encountered, so this is where an elif statement comes in. So let's say that we wanted to check if the language was equal to Python, and if it wasn't then we wanted to check if it was equal to Java, and if it was neither of those then we would just print out no match
language = 'Java'
if language == 'Python':
print("Language is Python")
elif language == 'Java':
print("Language is Java")
else:
print("No match")
so we'll add our additional check after our if statement by putting in an elif and again make sure that you're inventing is back to this base level because we're no longer in the if block. Say if the language is equal to Java and put in our colon. So basically what this is saying?, is if the language is equal to Python then execute this code if it's not then run a second conditional and see if it's equal to Java and if it is then run this code and if none of those conditionals are met and print no match
Language is Java
so now if we run this then we can see that it executed the print statement that the language is Java and none of these other statements were executed. Now if you're coming from another language you might be wondering if python has a switch case statement, now if you don't know what a switch case statement is then it's not a big deal basically it's just a way to check multiple values and Python doesn't have a switch case and the reason is because the if elif and else statements are plenty clean enough to do this already.
So if we wanted to check another language then we could just keep adding elif statements
language = 'Java'
if language == 'Python':
print("Language is Python")
elif language == 'Java':
print("Language is Java")
elif language == 'JavaScript':
print("Language is JavaScript")
else:
print("No match")
so if I wanted to add a JavaScript check to the list and I could just come down here if I copy all of this then I could just do another test here for JavaScript and then say if the language is JavaScript and execute this code here. And this basically gives us the same functionality as a switch case from another language okay so now I'm going to remove some code here so that we can take a look at another example.
Now in addition to these comparisons that we have here we also have some boolean operations that we can use
- and
- or
- not
and these are “and”, “or”, and “not” so for example let me create two variables here
user = 'Admin'
logged_in = True
if user == 'Admin' and logged_in:
print('Admin Page')
else:
print('Bad Creds')
and I'll call one of these user and set this equal to a string of admin and then I'll create a another variable here called logged in and I'll set that equal to true, now let's say that we only wanted to execute some code if the user is equal to add and logged in is equal to true now to do this we can use the and keyword, so I could say if user equal equals admin and then we'll use this and keyword and logged in and now we can ride the code if this is true so I'll just print out a string that says admin page and now we can put in an else block and then for the else block I'll just say if neither of these are true then print out the string that just says bad creds for credentials.
And let me bring this down just a little bit here and just to give us a little bit of extra room I'm actually going to delete these comparison comments up here that we have as a reference but I will have a link to these to the github page so that you can download those if you want to have those as a reference.
Okay so now if we run the code that we currently have
Admin Page
and we can see that it printed out our admin page because both of those evaluated to true our user is equal to admin and our login is equal to true but if I changed our logged in variable to false
user = 'False'
logged_in = True
if user == 'Admin' and logged_in:
print('Admin Page')
else:
print('Bad Creds')
and rerun
Bad Creds
this we can see that it executes our bad credentials statement, because both of these didn't evaluate to true so this user equals admin evaluated to true but log in was equal to false so and make sure that both of these have to be true now if we only care if one of these evaluate to true then we can use the or keyword
user = 'False'
logged_in = True
if user == 'Admin' or logged_in:
print('Admin Page')
else:
print('Bad Creds')
so I could change this and to an or
Admin Page
and now if I run this then you can see that it printed out our admin page statement because that evaluated to true because only one or the other needed to be true and our user was equal to admin so it didn't matter if the logged in was false or not, because it only had to be one or the other.
Now this not operation is just used to switch a boolean
user = 'Admin'
logged_in = False
if not logged_in:
print("Please Log In")
else:
print("Welcome")
so it'll change a true to a false and a false to a true. So for example if we were to say if not logged in then we will print a string here that just says please log in and else print welcome. So we can see that currently our logged in value is equal to false now when we say not logged in then it will evaluate to true because this not just switches that false to a true.
Now I know that that can sound a little confusing but basically you can just think of it as saying not false if not false which would evaluate true.
Please Log In
So if we run this then it prints out please login because not logged in evaluated to true so it ran what was in our if statement.
So when I had the conditionals pulled up here as a reference before so now I'm in my snippets here we remember that we had this object identity with this is keyword, and I said that we've looked at the difference between that and the double equals which tests for equality.
Now like I said before that object identity test if two objects have the same ID which basically means if they're the same object in memory, so two objects can actually be equal and not be the same object in memory so for example let me create two different lists here
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
I'll just call one list equal to a and I'll put in the values of one two three another list equal to B and put in the values 1 2 3, and now I will print out a double equals B so this should evaluate to true because these two lists are equal
True
so if we run this then we can see that we got true which is what we would expect because a and b are equal
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)
but instead if we say a is b and then we run this
False
then that returns false now the reason is because these are two different objects in memory and we can print out these locations with this built-in ID function.
a = [1, 2, 3]
b = [1, 2, 3]
print(id(a))
print(id(b))
print(a is b)
so right above printing that a is b, I'm also going to print out the ID of a, and I will also print out the ID of b, so I'll save that and run it
3055382220 3081144204 False
and we can see that these IDs are different.
So really this is comparison is really checking whether these IDs are the same.
a = [1, 2, 3]
b = a
print(id(a))
print(id(b))
print(a is b)
So up here instead of creating a new list if I just said b equal a, and save that and run it
3055382220 3055382220 True
and now we can see that the ID of a, and id of b are the same and then when we print a is b that evaluates to true because now these are the same object in memory. And if I check equality then they're also equal so that's basically the difference there behind the scenes the is comparison
a = [1, 2, 3]
b = a
print(id(a))
print(id(b))
print(id(a) == id(b))
if you say a is b it's really the same as saying ID of a equals equals the ID of b
3056176844 3056176844 True
so if I run that that's equal to true that's basically what the is operator does.
Okay so basically now all the conditionals that we looked at completely depend on what Python evaluates to true or false so let's see what all Python evaluates to true or false and there are a few things that may be unexpected to us. So I have a couple of things pulled up here in my snippets and let me grab these
condition = False
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
so to determine what Python evaluates to true and false it's easier to show everything that evaluates to false and then everything else will by default evaluate to true. And we have a quick if else statement here to test all of these.
So we're going to make a few different conditions here and if that condition evaluates to true we'll print out evaluate its true else evaluated to false. And my comments here are all the things in Python that evaluate to false values so the first one is the most obvious if we set a conditional equal to false then it's going to evaluate to false, and this one would include all the comparison operations that we just saw so they would return true or false
Evaluated to False
so if I run this, then we can see that obviously our conditional evaluated to false here since we set our condition equal to false.
condition = None
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
Now the next value in our list here is none, so none actually evaluates to false as well so if we put that value in as our conditional
Evaluated to False
and run this, and we can see that with our condition equal to none that condition also evaluates to false.
Now this next one here isn't always so obvious so if you have a numeric data type and pass it into a conditional, then zero will die wait to false so if we set this condition equal to zero and run this that we can see that that evaluated to false
condition = 10
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
but if we set this to any other number so if our condition is 10 instead of zero
Evaluated to True
and run that, and we can see that evaluated to true.
So that's something to keep in mind there when working with numbers because you don't want to accidentally pass in a zero that you think would be true but it evaluates to false.
Okay so moving on down the list if we have any empty syncwords and pass it into a conditional then that will evaluate to false. So this can be an empty string an empty list and in the tuple
condition = []
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
so for example if I just set this condition to an empty list
Evaluated to False
and run this, and we can see that that evaluates to false and if you have an empty string that evaluates to false also, and now lastly here in our list empty mapping, so an empty mapping which is basically an empty dictionary this evaluates to false as well
condition = {}
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
so if I pass in an empty dictionary here
Evaluated to False
and run this, and we continue at that empty dictionary also evaluated to false now knowing these types of things can be useful because let's say that you have a function or something that is supposed to return some values now sometimes it's needed to check if those values are actually there.
So you could just pass in these sequences into a conditional to check whether a string is empty or a dictionary is empty and you don't actually have to call any specific method you can just pass in the empty sequence or the empty dictionary and it will evaluate the true or false if that is empty.
Now there are also some user-defined classes that can evaluate to false but these are the majority of the conditions that will be checking. So now that we know everything that evaluates to false and everything else is obviously going to evaluate to true.
condition = 'test'
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
So you know for example just to do another example here if I set this condition equal to a string that just says test now an empty string would evaluate to false so if we ask that in
Evaluated to True
that we can see that that a string with some characters evaluated the true. So that's really important when working with these conditionals is just having an idea of what is going to evaluate the true and what's going to evaluate to false.
Okay so I think that is going to do it for this post I hope now everyone has a clear understanding of how these conditionals work and all the different ways that Python determines what values are true and false.