Conditionals are generally a way to check something. The classic “if” example is easy to understand. The syntax helps you understand it a bit. A normal if statement would look like this:

if(condition):

do something
Let’s see an example with food because I’m hungry. My code will basically ask if the food is ready by having the user input dictate its state of readiness (that explains the variable name) and then my conditional if checks the data to perform an action, it prints “yay” if the food is ready. But the operator = helps me know if the user input is right. We can evaluate other values by using other operators such as < > to compare values.
readiness = input(“Is the food ready? “)

if(readiness == “yes”):

print(“yay”)
We can also combine two conditionals in an if statement by using the Boolean operation and. I added a new value which is my food temperature so my conditional are always met and my if statement will work.
readiness = input(“Is the food ready? “)

temperature = input(“Is the food hot? “)

if(readiness == “yes”) and (temperature == “yes”):

print(“yay”)
The same can be done with the operation or. What or does is it basically combines two conditionals and the action will be executed if either conditions are met. So in this case it doesn’t matter if our readiness or temperature are not hot or ready if one of them is true our action will be executed.
readiness = input(“Is the food ready? “)

temperature = input(“Is the food hot? “)

if(readiness == “yes”) or (temperature == “yes”):

print(“yay”)
So my values were checked and my program acted accordingly. But what if the value is not what I asked for? There is an operator called else that solves this problem. In this case, else doesn’t have to include a condition because we don’t care about anything else, we just want to have our food right? All I have to do is write else below my if statement without an indentation and tell my else what to do.
readiness = input(“Is the food ready? “)

if(readiness == “yes”):

print(“yay”)

else:

print(“hurry up, I’m hungry”)
There is another conditional that is a mixture of else and if and it must be typed between your if and else. It is called elif. It basically sets up another conditional so it is a lot more like it but it is still like else.
readiness = input(“Is the food ready? “)

if(readiness == “yes”):

print(“yay”)

elif(readiness == “yep”):

print(“yay”)

else:

print(“hurry up, I’m hungry”)

CC BY 4.0 Mastery15 & Mastery16 & Mastery17 by 5nbpppkkyj is licensed under a Creative Commons Attribution 4.0 International License.