Above is the if / elif / else in action, but there is a lot of vocab to know about along the way, along with some new operators and how they work!
To jump right into some Terminology for these Conditionals!
Being that programs are “Logically Malleable” this allows them to use what are called “Conditional” statements within the lines of code to point to a decision, if A then do this, if B then do that.
Two of these are <Expression> and <Statement> in programming, which can be written in different ways, such as this example of code, this will be demonstrated in Visual Studio Code below in action but an overview looks like this:
if <expression> than <statement>
if <expression> than <statement>
elif <expression> than <statement>
An “Expression” doesn’t have a set rule on what it means, but can be assumed it evaluates to “eval” so it becomes a singular true / false / integer / some kind of singular value, like the “if” statement could be boiled down to a Boolean statement (true or false).
“Statements” are full complete sentences within the programming language, which may or may not contain expressions, how it may not, and can still stand on its own. Expressions come in with these “Conditionals” like “if” to add interaction to a Statement, so then “if” yes then execute this statement, and “if” no execute that Statement.
Also Statements and actually be part of larger Statements, as demonstrated below:
“When taking care of plant life, if a plant does / does not have any water then it will grow strong / dry up very quickly, so it is important to make sure to water them regularly.”
This is an example of a single statement with expressions inside of it, sitting within a longer overall statement that does not contain expressions to complete its contents.
Now to look at the programming side with some new “Operators” to work with
There will be four new Operators introduced here for coding (Boolean Operators):
- == Equals
- != Does not Equal
- > Greater than
- < Less than
These return a True / False depending whats on either side of the statement:
This of course is not limited to Integers, but this is how it can be logically thought of in operation for all four of the Boolean operators, as shown here on the Interface line:
As seen below these can be used in flexible ways, here I am just playing with math:
These are all examples of little Boolean (True / False) Expressions.
One thing to note is these Boolean Expressions will not accept a single = as shown:
Given = is an assignment operator, Python has this as a sort of fail safe built into the code, so we as developers cannot accidentally assign one integer the value of another.
Now to incorporate this into a program that uses if / than / else (ifelse)
I got caught up on one part of writing this code, integers must have a : after them or they error out, that took me way longer than necessary to realize!
I followed Bens example here for time sake on this post to write a script asking for name and age to see if someone is allowed to get into a 21+ club, shown here:
The first portion circled is the input which gathers the name / age input by the user, to be used in the Boolean if operator of >, and added a line that makes age = int(rawAge) to be used at a later time for error handling purposes on line 3.
The second portion is a pretty straight forward I think to even someone who doesn’t code at all, if your Greater Than 20 your in, if not you need to go back home and study Python!
One important note with Indentation and Blank Spaces when Programming
Beyond using blank (white) lines between chunks of code to look nice, Python requires the “Indentation” seen with the print statements after their if / else operator to create what are called “Statement Blocks” in the code, which is unique to Python as other code requires maybe curly brackets or some other character to indicate a Statement Blocks.
This is a nice thing about Py is it knows coders use indentation to make code readable anyways (at different levels in the script), and Pythong DOES NOT REQUIRE Indentation to be any certain length! You could use a single space, a tab (4 spaces?), you can indent expressions and statements however much you want so long as it is uniform.
This makes Python cleaner,
Now to throw a curve ball in there, what if the answer to the age is 20?
20 is not Greater Than 20, so this will tell whoever the name is to take a hike:
Which given the context of needing to be 21+ is a perfect result and the script is still doing its job, but what if you only need to be 20 for some reason to get into this club?
Then you can add an = to the Operator >= which will mean Mr 20 Year Old is allowed in:
So we added the = to > so its now Greater than or Equals to 20, edited the print lines to say 20 instead of 21, and our script is now working for 20 years to sneak their way in!
This can go on using the different Operators, such as if this is a 20 year old only club, throw an == in place of the >=, or if its for anyone NOT 20 add an != Operator. I am currently trying to add in non-Integer conversation like the color of the sky but failing.
Which I got figured out in this final section here 🙂
Last is a a look at “elif” expressions in a Statement
The “elif” or “elseif” I found out the long way of messing with code until I saw the log jam, which was that I had created it after the first if / else expressions – “Elif” will not work if “else” expressions are in front of it (that I am aware of).
Example of non-working “elif” with my non-Integer Sky question in there(!) :
So I pulled all of that non-sense out for another morning because I am getting study fried at this point, I will raise that fight for another day – Though I did get it working properly:
As can be seen I ran it 3 times: Once as myself and old enough to drink, once as an 18 year old and old enough to enter but not drink, and a Toddler that is told to go home and study up on his Python coding 🙂
I also did test “What if it doesn’t = exactly 18 years old? And here is the result:
So I forgot about the Syntax there of the print functions of the club being 20+, how the = repeated the same message from 18-20 year olds than 21+ it gave the OK to get drunk!
And Toddlers, of course, need to go home and learn their Python.
One last thing to hit before closing this article out
Python scripts execute line by line, so you can actually insert lines that will “catch” the script from moving any further (maybe you have a fake ID that says your 21!), however I am way too tired to illustrate that however every time the script hits an object it executes the commands below it (the print functions in this case) then stopped executing.
So there are ways if you wanted to put a catch-all in your script for some reason, you could create an if or elif above the lines you don’t want executed to stop the script before it executes them, so its similar I want to say like Route-Maps in this way that they execute from the top down / stop searching once it hits a match / executes the clause.
I am way wrapping this post up here on the subject of operators and if/elif/else!
It is 9:15am and I’ve been studying since about 5am, this stuff really takes me hours like first learning to subnet or what I used to called “Supernet” (Summary Routes) in my R/S infancy so its a long grind but I am pushing through it!
Until next time amigos! 🙂