Monday, 27 July 2020

If Statements


    
    Programming often involves examining a set of conditions and deciding which action to take based on those conditions. Python’s if statement allows you to examine the current state of a program and respond appropriately to that state.

In this blog you’ll learn to write conditional tests, which allow you to check any condition of interest. You’ll learn to write simple if statements, and you’ll learn how to create a more complex series of if statements to identify when the exact conditions you want are present. You’ll then apply this concept to lists, so you’ll be able to write a for loop that handles most items in a list one way but handles certain items with specific values in a different way.

A Simple Example

The following short example shows how if tests let you respond to special situations correctly. Imagine you have a list of cars and you want to print out the name of each car. Car names are proper names, so the names of most cars should be printed in title case. However, the value 'bmw' should be printed in all uppercase. The following code loops through a list of car names and looks for the value 'bmw'. Whenever the value is 'bmw', it’s printed in uppercase instead of title case:

cars = ['audi', 'bmw', 'subaru', 'toyota'] 
for car in cars: 
    if car == 'bmw': 
        print(car.upper()) 
    else: 
        print(car.title())

Output
Audi 
BMW 
Subaru 
Toyota

This example combines a number of the concepts you’ll learn about in this chapter. Let’s begin by looking at the kinds of tests you can use to examine the conditions in your program.

Conditional Tests

At the heart of every if statement is an expression that can be evaluated as True or False and is called a conditional test. Python uses the values True and False to decide whether the code in an if statement should be executed. If a conditional test evaluates to True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement.

Comparison Operators in Python · Pylenin

Checking for Equality 

Most conditional tests compare the current value of a variable to a specific value of interest. The simplest conditional test checks whether the value of a variable is equal to the value of interest:

car = 'bmw' 
print(car == 'bmw') gives True
print(car == 'BMW') gives False

Double equal sign (==) is a equality operator. This equality operator returns True if the values on the left and right side of the operator match, and False if they don’t match.

Ignoring Case When Checking for Equality

Testing for equality is case sensitive in Python. For example, two values with different capitalization are not considered equal just as in above example. But we can easily obtain this by first converting value of variable to lower case before comparison.

car = 'BMW'
print(car.lower() == 'bmw') gives True

Checking for Inequality

When you want to determine whether two values are not equal, you can combine an exclamation point and an equal sign (!=). The exclamation point represents not, as it does in many programming languages.

user = "prasanna"
if user != "prasanna":
    print("Unauthorized")

Here, if user is set to anything other than "prasanna" a Unauthorized message is shown.

Numerical Comparisons

Testing numerical values is pretty straightforward. Each mathematical comparison can be used as part of an if statement, which can help you detect the exact conditions of interest. Some of the conditions for numbers can be:

number=17
print( number == 20 , number > 20, number < 20, number != 20 )

Checking Multiple Conditions

You may want to check multiple conditions at the same time. The keywords and and or can help you in these situations. 

Using and to Check Multiple Conditions

To check whether two conditions are both True simultaneously, use the keyword and to combine the two conditional tests; if each test passes, the overall expression evaluates to True. If either test fails or if both tests fail, the expression evaluates to False.

age_0 = 22 
age_1 = 18  
print(age_0 >= 21 and age_1 >= 21) gives False 
print(age_0 >= 21 and age_1 >= 21) gives True

Using or to Check Multiple Conditions 

The keyword or allows you to check multiple conditions as well, but it passes when either or both of the individual tests pass. An or expression fails only when both individual tests fail.

age_0 = 22 
age_1 = 18  
print(age_0 >= 21 or age_1 >= 21) gives True
print(age_0 <= 21 or age_1 >= 21) gives False

Checking Whether a Value Is in a List 

Sometimes it’s important to check whether a list contains a certain value before taking an action. For example, you might want to check whether a new username already exists in a list of current usernames before completing someone’s registration on a website.To find out whether a particular value is already in a list, use the keyword in.

toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in toppings ) gives True
print('pepperoni' in toppings) gives False

Checking Whether a Value Is Not in a List

Other times, it’s important to know if a value does not appear in a list. You can use the keyword not in this situation.

banned_users = ['andrew', 'james', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")

Boolean Expressions

As you learn more about programming, you’ll hear the term Boolean expression at some point. A Boolean expression is just another name for a conditional test. A Boolean value is either True or False, just like the value of a conditional expression after it has been evaluated.

winner = True 
can_edit = False

if Statements

When you understand conditional tests, you can start writing if statements. Several different kinds of if statements exist, and your choice of which to use depends on the number of conditions you need to test.

Simple if Statements

The simplest kind of if statement has one test and one action:
age = 19 
if age >= 18: 
    print("You are old enough to vote!") 

If the value of age is less than 18, this program would produce no output.

if-else Statements

Often, you’ll want to take one action when a conditional test passes and a different action in all other cases. Python’s if-else syntax makes this possible. An if-else block is similar to a simple if statement, but the else statement allows you to define an action or set of actions that are executed when the conditional test fails.

age = 17 
if age >= 18: 
    print("You are old enough to vote!") 
else: 
    print("Sorry, you are too young to vote.") 
    print("Please register to vote as soon as you turn 18!")

The if-elif-else Chain

Often, you’ll need to test more than two possible situations, and to evaluate these you can use Python’s if-elif-else syntax. Python executes only one block in an if-elif-else chain.

score_a = 5
score_b = 8
if score_a>score_b:
    print("Team A wins")
elif score_b>score_a:
    print("Team B wins")
else:
    print("Draw")

Using Multiple elif Blocks

You can use as many elif blocks in your code as you like. For example, let's look at a grading system code.

marks = 70
if marks<32:
    print("Fail")
elif marks<50:
    print("Grade D")
elif marks<60:
    print("Grade C")
elif marks<80:
    print("Grade B")
elif marks<100:
    print("Grade A")

Note: Keep in mind that Python does not require an else block at the end of an if-elif chain. i.e. we can easily omit the else block.

Testing Multiple Conditions

The if-elif-else chain is powerful, but it’s only appropriate to use when you just need one test to pass. As soon as Python finds one test that passes, it skips the rest of the tests. This behavior is beneficial, because it’s efficient and allows you to test for one specific condition.
However, sometimes it’s important to check all of the conditions of interest. In this case, you should use a series of simple if statements with no elif or else blocks. This technique makes sense when more than one condition could be True, and you want to act on every condition that is True.

requested_toppings = ['mushrooms', 'extra cheese'] 
if 'mushrooms' in requested_toppings: 
    print("Adding mushrooms.") 
if 'pepperoni' in requested_toppings: 
    print("Adding pepperoni.") 
if 'extra cheese' in requested_toppings: 
    print("Adding extra cheese.") 

 print("\nFinished making your pizza!")

Using if Statements with Lists

You can do some interesting work when you combine lists and if statements. You can watch for special values that need to be treated differently than other values in the list. You can manage changing conditions efficiently, such as the availability of certain items in a restaurant throughout a shift. You can also begin to prove that your code works as you expect it to in all possible situations.

Checking for Special Items

The code for the above toppings code can be written very efficiently by making a list of toppings the customer has requested and using a loop to announce each topping as it’s added to the pizza:

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] 
for requested_topping in requested_toppings: 
    print("Adding " + requested_topping + ".")

print("\nFinished making your pizza!")

Let's take it further, what if the pizzeria runs out of green peppers? An if statement inside the for loop can handle this situation appropriately: 

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] 
for requested_topping in requested_toppings: 
    if requested_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding " + requested_topping + ".")

print("\nFinished making your pizza!")

Checking That a List Is Not Empty

We’ve made a simple assumption about every list we’ve worked with so far; we’ve assumed that each list has at least one item in it. Soon we’ll let users provide the information that’s stored in a list, so we won’t be able to assume that a list has any items in it each time a loop is run. In this situation, it’s useful to check whether a list is empty before running a for loop.

requested_toppings = []
if requested_toppings:
    print("There are items inside. You can run for loop.")
else:
    print("List is empty.")

Using Multiple Lists

Let’s watch out for unusual topping requests before we build a pizza. The following example defines two lists. The first is a list of available toppings at the pizzeria, and the second is the list of toppings that the user has requested. This time, each item in requested_toppings is checked against the list of available toppings before it’s added to the pizza:

available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']  requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] 

for requested_topping in requested_toppings: 
    if requested_topping in available_toppings:  
        print("Adding " + requested_topping + ".") 
    else: 
        print("Sorry, we don't have " + requested_topping + ".")

print("\nFinished making your pizza!")

Output
Adding mushrooms. 
Sorry, we don't have french fries.
Adding extra cheese. 
Finished making your pizza!

Conclusion

In this blog you learned how to write conditional tests, which always evaluate to True or False. You learned to write simple if statements, if-else chains, and if-elif-else chains. You began using these structures to identify particular conditions you needed to test and to know when those conditions have been met in your programs. You learned to handle certain items in a list differently than all other items while continuing to utilize the efficiency of a for loop.

In next blog you’ll learn about Python’s dictionaries. A dictionary is similar to a list, but it allows you to connect pieces of information. You’ll learn to build dictionaries, loop through them, and use them in combination with lists and if statements. Learning about dictionaries will enable you to model an even wider variety of real-world situations.

Post a Comment

Let's make it better!
Comment your thoughts...

Whatsapp Button works on Mobile Device only

Start typing and press Enter to search