Last post with the Booleans I said the code will only run as true if all the qualities are satisfied. I should’ve said conditions. I couldn’t think of the word at the time, but that’s what I meant.
So passwords are a common example of conditionals at work.
if password == "1234":
grant_access()
The grant_access function would only be called if that given password is inputted.
This seems a lot more practical for automating tasks or even setting an approve/deny function like with the password
Here’s a cool one for setting the max health in a video game
def max_health(mode):
if mode == "easy":
return 100
elif mode == "medium":
return 75
else:
return 35
‘elif’ is for ‘else if’ that acts as an alternative in case the preceding ‘if’ is false, meaning the game is not on easy mode. The ‘else’ is for any mode that is not easy or medium. If there was only a hard mode, we would’ve just put ‘hard’, but we used the ‘else’ for the sake of learning more from this example.
Comparisons
In comparisons, we use the greater than and less than signs.
def is_young(age):
if age < 18:
return True
else:
return False
This code runs if the inputted age is under 18.
The same goes for the ‘or equals too’ (<=/>=) signs. You can also use these in place of an OR. And you can use the ‘not equal to’ (!=) in place of a double equals.
Here’s a code with comparisons at work in the case of automating a stock portfolio. We want to buy at 100, hold if between 100-150, and sell when over 150
def decide(price):
if price < 100:
return "buy"
if price >= 100 and price <= 150:
return "hold"
if price > 150:
return "sell"
Don’t forget to put the colon after your ‘if’ statements, and keep the ‘r’ in ‘return’ lowercase.