done

Chapter 4 Making Decisions: if, elif, else

We need to make decisions. Conditional statements are like saying, “If this, then that.” If you eat broccoli, then you get pudding; otherwise, no dessert! Ah... Life is full of decisions to make. One way or the other. Now we need to learn how to make programs work for us, be able to change the path depending on situations.

4.1 If-statements

If-statements let you change the flow of control in a (Python or Java) program. Almost all nontrivial(what does it mean? Keep going anyway.) programs use one or more if-statements, so they are important to understand.

If-statement enables the program to do different things depending on different situations, such as pay different movie ticket prices depending on your age or print class schedule depending on the weather.

The if statement is used to check a condition: if the condition is true, we run a block of code in the clause (called the if-clause), else we process another block of code (called the else-block or else_clause). The else clause is optional.

(Java, The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true)

In Python, an if (elif,else) statement consists of the following:

  • The if keyword
  • A condition (evaluates to True or False)
  • A colon
  • An indented block of code starting on the next line

The syntax

if (condition is) True:    
    do this                   # if clause
elif (condition is) True:     # optional
    do that                   # elif clause
else:                         # optional
    do something else         # else clause

Remember that the elif and else parts are optional.

Python's indentation rule, one of the most distinctive features of Python is its use of indentation to mark blocks of code. the block of code in the the if-statement example is indented four spaces, which is typical amount of indentation for Python.

A minimal valid if statement is:

Ex. 4.1-1 simple if statement

>>> n=3
>>> if n > 1:
    print n
...# run
3
>>>

Adding an else to an if

Sometimes adding an else statement is completely optional, but if you include the else, you have to put a block of code under it.

Ex. 4.1-2 if and else

>>> n=3
>>> if n > 10:
    print ('n is larger than 10')
    else:
        print ('n is smaller than 10')    
...# run
n is smaller than 10
>>>

If...else can be very useful, let's look at this:

Ex. 4.1-3 password.py

ex. password.py
>>> pass = input('Enter the password here:' )
>>> if pass == 'Sniffy' :    # notice '==' instead of '='
        print 'Logging on ...be patient...'
    else:
        print 'Wrong password, haha!'
...# run
Enter the password here: snifyy     # case sensitive
Wrong password, haha!       
...# run again
Enter the password here: Sniffy
Logging on ...be patient...
>>>

input() function, see Chapter 1.6
When the above program runs, the prompt message 'Enter the password here: ' in the input() function will show on the screen and wait for the user to type in a string value, once we enter something and press kbd:[enter] key, the input() function returns what we entered, as a string, and then store it in the variable pass. Then if-else statements come into the picture and do their work.

In next example, we get a number as a string from input() , and then using int() to convert it into a integer, and then store it in the variable n.

Ex.4.1-4 check_numbers.py

Ex. check_numbers.py
>>> n= int (input ('Enter a number between 0 to 10 ') )
>>> if n >5:
    print ('Greater than 5')
    else:
    print ('Five or less')
>>> 
...# run...
Enter a number between 0 to 10: 4
Five or less
...# run again ...
Enter a number between 0 to 10: 8
Greater than 5
>>>

Use if-statement to test user's input is within required range

Ex. 4.1-5 in_range.py

>>> value = int(input('Enter a number between 1 and 10: '))
>>> if (value > 0) and ( value <=10):
    print ('The number you entered is ', value)
    else:
        print ( 'The value you entered is out of range!')
>>>
...# run...
Enter a number between 1 and 10: 6
The number you entered is 6
...# run again...
Enter a number between 1 and 10: 12
The number you entered is out of range!
>>>

4.2 Testing many things with elif

An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions.

Sometimes, you want to test more than one condition. For example, you might want to print out a different message based on the age of people. In case like this, you can use an elif (else if) statement.

Tell different jokes depending on the listener's age Ex. 4.2-1 jokes.py

>>>age=int(input('Enter your age in number: ') )
>>>if age > 12:
       print ('It will be hard to get you laugh.')
   elif age>5 and age<=12:
       print ('What did o said to 8?'
       print ('Hi, gugs!')
   else:
       print ('You are too young for my jokes.')
 >>>
 Enter your age in number: 11
 What did o said to 8?
 Hi, guys!

Many choices: Ex.4.2-2 fruit_choice.py

print('1. Apple')
print('2. Pear')
print('3. Orange')
print('4. Grape')
print('5. Banana')

choice= int(input('Select you favorite fruit by choosing the corresponding number: ')

if (choice == 1):
    print('Your favorite fruit is Apple.')
elif (choice ==2):
    print('Your favorite fruit is Pear.')
elif (choice ==3):
    print('Your favorite fruit is Orange.')
elif (choice ==4):   
    print('Your favorite fruit is Grape.')   
elif (choice ==5):
    print('Your favorite fruit is Banana.')
else:
    print('You made an invalid choice!')

...#run...
1. Apple
2. Pear
3. Orange
4. Grape
5. Banana
Select your favorite fruit by choosing the corresponding number: 3
Your favorite fruit is Orange.
>>>
...#run again...
1. Apple
2. Pear
3. Orange
4. Grape
5. Banana
Select your favorite fruit by choosing the corresponding number: 8
You made an invalid choice!

People pay different movie ticket price depending on their age.
Ex. 4.2-3 movie_ticket.py

# movie_ticket.py
>>> age =int ( input ( 'Please enter your age: ') )
>>> if age <=12:
        ticket = 8.75
        print ('Children\'s price, %d dollars.' % ticket)
    elif age>12 and age <65:
        ticket = 12.00
        print ('Adult\'s price, %d dollars' % ticket)
    else:
        ticket = 5.00
        print ( 'Senor's price, %d dollars' % ticket)
>>>
...run...
Please enter your age: 26
Adult's ticket, 12.00 dollars.
>>>

Next example shows a program to calculate shipping fee: Shopping total>100, get free shipping; Shopping total between 90 to 100 , print message 'Spend a bit more to get free shipping'; Shopping total less than 90, print 'Spend 100 to get free shipping'.

Ex. 4.2-4 shipping_fee.py

>>> shopping_cart = 88.75
>>> if shopping_cart >= 100:
        print ('You get free shipping.')
    elif shopping_cart >= 90:
        print ('Spend %d dollars more 
               to get free shipping!' % (100-total) )
    else:
        print ('Spend 100 dollars to get free shipping.')
>>>
...# run...
Spend 11.25 dollars more to get free shipping!

results matching ""

    No results matching ""