What are if,else and elif statements in Python?

 What are if,else and elif statements in Python?

 

What are if,else and elif statements in Python?

if statements

  • We can use the concept of branching to have our code alter its execution sequence depending on the values.
  • We can use an if statement to evaluate a comparison.
  • We start with the if key word, followed by our comparison.
  • We end the line with colon:
  • The body of the if statement is then indented to the proper.
  • If the comparison is True, the code inside the if body is executed.
  • If the comparison evaluates to False, then the code block is skipped and will not be run.

Assume we want to know whether the string assigned to the variable object is “computer”. This is the code.

if object == “computer”

  print(“Yes, it’s computer”)

If the string “computer” has been assigned to the variable object, Python displays the message Yes,it’s computer. If the string “computer” hasn’t been assigned to the variable object, nothing happens.

  • It begins with the keyword if.
  • Note that if is all lowercase.
  • If we write If instead of if, it won’t work.We ‘ll get an error message.
  • Note that it’s two equal signs, ==, not one. One equal sign, = , can only be used to assign a value to a variable, as in..  object = “computer”
  • Whenever we’re testing whether one thing is the same as another, the operator has to be ==. Otherwise, we’ll get an error message.
  • The first line ends with a colon. If the string “computer” has been assigned to the variable object we tell Python what to do..
  • We put this on its own line, and we indent the line one tab.
  • We can make any number of things happen when the answer to the if question is “yes”.
  • Each thing that happens gets its own line. And each line is indented.
  • There are other things we can test, including numbers. It works the same way.
  • In Python, indents aren’t just for pretty formatting. They have meaning for Python. They aren’t optional. 
  • In general, any lines of code that take their orders from a line that ends during a colon are indented.

Comparison Operators

  • == , it’s a sort of comparison operator, specifically it’s the equality operator. We use it to compare two things to see if they’re equal.
  • We can use the equality operator to compare a variable with a string, a variable with a number, a variable with a math expression, or a variable with a variable.
  • We can use the equality operator to compare various combinations.
  • When we are comparing strings, the equality operator is case-sensitive, “Flower” does not equal to “flower”.
  • Another comparison operator, !=, is the opposite of ==. It means is not equal to.It can be used to compare numbers, strings, variables, math expressions, and combinations.
  • Four more comparison operators;
  1. > is greater than 
  2. < is less than
  3. >= is greater than or equal to
  4. <= is less than or equal to

else Statements and the Modulo Operator

  • We just covered the if statement, which executes code if an evaluation is true and skips the code if it’s false.
  • But what if we wanted the code to do something different if the evaluation is false?
  • We can do this using the else statement.
  • The else statement follows an if block, and is composed of the keyword else followed by a colon.
  • The body of the else statement is indented to the right, and will be expected if the above if statement doesn’t execute.
  • We also touched on the modulo operator, which is represented by the percent sign:%.
  • This operator performs integer division, but only returns the remainder of this division operation.
  • If we are dividing 5 by 2, the quotient is 2, and the remainder is 1.
  • Two 2s can go into 5, leaving 1 left over. So 5%2 would return 1.
  • Dividing 10 by 5 would give us a quotient of 2 with no remainder, since 5 can go into 10 twice with nothing left over.
  • In this case, 10%2 would return 0, as there is no remainder

Testing sets of conditions

  • Using the if statement, we have learned to test for a condition.
  • If the condition is met, one or more statements execute.
  • But suppose not one but two conditions have to be met in order a test to succeed.
  • Let’s suppose, if a boy weighs more than 200 pounds, he’s just a great big boy. But if he weighs more than 200 pounds and runs 30 yards in under 5 seconds? We’re going to invite him to try out for the team.
  • We can test for a combination of conditions in Python by using the keyword and.
  • if weight > 200 and time < 5:
  • status = ” try to appoint him”
  • The individual need to meet both conditions–over 200 pounds and under 5 seconds– in order to qualify.
  • If he meets only one of the conditions, the test fails, and doesn’t get the invitation. 
  • We can chain any number of conditions together.
  • if weight > 200 and time < 5 and age > 19 and height < 55
  • status = ” try to recruit him”
  • We can also create a test that passes if any condition is met. The keyword is or.
  • if SAT > avg or GPA > 2.5 or parent == “alum”:
  •    message = ” Welcome to Government College ! “
  • Only one of the conditions need to be met in order for the welcome message to be sent out– a high SAT score, a decent grade point average, or a parent who attended the college.
  • Any of them will do. Of course, line 2 executes if more than one condition is met. 
  • We can combine any number of and and or conditions. When we do, we create ambiguities.

 More Complex Branching with elif Statements

  • Building off of the if and else blocks, which enable us to branch our code relying on the evaluation of 1 statement, the elif statement allow us even more comparisons to perform more complex branching.
  • Very similar to the if statements, an elif statement starts with the elif keyword, followed by a comparison to be evaluated.
  • This is followed by a colon, and then the code block on the next line, indented to the right.
  • An elif statement must follow an if statement, and will only be evaluated if the statement was evaluated as false.
  • We can include multiple elif statements to build complex branching in our code to do all kinds of powerful things.

A Note on Syntax and Code Blocks

  • When writing a code, using correct syntax is super important.
  • Even a small typo, like a missing parentheses or  comma, can cause a syntax error and the code won’t
  • After the colon, the function body starts.
  • It’s important to note that in Python the function body is delimited by indentation.
  • This means that all code indented to the right following a function definition is part of the function body.
  • The first line that’s no longer indented is the boundary of the function body.
  • It’s up to us how many spaces we use when indenting—just make sure to be consistent.
  • So if we choose to indent with four spaces, we need to use four spaces everywhere in our code.

Leave a Comment