conditionals.rst
changeset 171 6537f447efc0
equal deleted inserted replaced
170:d12107cbe14b 171:6537f447efc0
       
     1 Hello friends. Welcome to this spoken tutorial on Getting started with
       
     2 strings.
       
     3 
       
     4 {{{ Show the slide containing the title }}}
       
     5 
       
     6 {{{ Show the slide containing the outline }}}
       
     7 
       
     8 In this tutorial, we will learn the basic conditional constructs
       
     9 available in Python. We learn the if/else, if/elif/else and ternary
       
    10 conditional constructs available in Python. 
       
    11 
       
    12 {{{ Shift to terminal and start ipython }}}
       
    13 
       
    14 To begin with let us start ipython, by typing::
       
    15 
       
    16   ipython
       
    17 
       
    18 on the terminal
       
    19 
       
    20 Whenever we have two possible states that can occur depending on a
       
    21 whether a certain condition we can use if/else construct in
       
    22 Python. Say for example we have a variable "a" which stores integers
       
    23 and we are required to find out whether the value of the variable "a"
       
    24 is an even number or an odd number. To test out conditional statements
       
    25 as an example, let us say the value of the variable "a" is 5::
       
    26 
       
    27   a = 5
       
    28 
       
    29 In such a case we can write the if/else block as::
       
    30 
       
    31   if a % 2 == 0:
       
    32       print "Even"
       
    33   else:
       
    34       print "Odd"
       
    35 
       
    36 When the value of the variable "a" is divided by 2 and the remainder
       
    37 is 0 i.e. the result of the operation "a modulo 2" is 0 the condition
       
    38 "a % 2 == 0" evaluates to True, so the code within the if block gets
       
    39 executed. This means that the value of "a" is Even. 
       
    40 
       
    41 If the operation "a modulo 2" is not 0 the condition "a % 2 == 0"
       
    42 evaluates to False and hence the code block within else gets executed
       
    43 which means that the value of "a" is Odd. 
       
    44 
       
    45 Note in such a case only one of the two blocks get executed depending
       
    46 on whether the condition is True or False.
       
    47 
       
    48 There is a very important sytactic element to understand here. All the
       
    49 statements which are inside a certain code block are indented by 4
       
    50 spaces. The statement which starts a new code block after it, i.e. the
       
    51 if statement in this example ends with a colon (:). So the next
       
    52 immediate line will be inside the if block and hence indented by 4
       
    53 spaces. To come out of the code block we have to come back to the
       
    54 previous indentation level as shown in the else line here. Again the
       
    55 line following else will be in a new block so else line ends with a
       
    56 colon and the following block of code is indented by 4.
       
    57 
       
    58 As we use if/else statement when we have a condition which can take
       
    59 one of the two states, we may have conditions which can take more than
       
    60 two states. In such a scenario Python provides if/elif/else
       
    61 statements. Let us take an example. We have a variable "a" which holds
       
    62 integer values. We need to print "positive" if the value of a is
       
    63 positive, "negative" if it is negative and "zero" if the value of the
       
    64 variable "a" is 0. Let us use if/elif/else ladder for it. For the
       
    65 purposes of testing our code let us assume that the value of a is -3::
       
    66 
       
    67   a = -3
       
    68 
       
    69   if a > 0:
       
    70       print "positive"
       
    71   elif a < 0:
       
    72       print "negative"
       
    73   else:
       
    74       print "zero"
       
    75 
       
    76 This if/elif/else ladder is self explanatory. All the syntax and rules
       
    77 as said for if/else statements hold. The only addition here is the
       
    78 elif statement which can have another condition of its own.
       
    79 
       
    80 Here, exactly one block of code is executed and that block of code
       
    81 corresponds to the condition which first evaluates to True. Even if
       
    82 there is a situation where multiple conditions evaluate to True all
       
    83 the subsequent conditions other than the first one which evaluates to
       
    84 True are neglected. Consequently, the else block gets executed if and
       
    85 only if all the conditions evaluate to False.
       
    86 
       
    87 Also, the else block in both if/else statement and if/elif/else is
       
    88 optional. We can have a single if statement or just if/elif statements
       
    89 without having else block at all. Also, there can be any number of
       
    90 elif's within an if/elif/else ladder. For example
       
    91 
       
    92 {{{ Show slide for this }}}
       
    93 
       
    94   if user == 'admin':
       
    95       # Do admin operations
       
    96   elif user == 'moderator':
       
    97       # Do moderator operations
       
    98   elif user == 'client':
       
    99       # Do customer operations
       
   100 
       
   101 {{{ end of slide switch to ipython }}}
       
   102 
       
   103 is completely valid. Note that there are multiple elif blocks and there
       
   104 is no else block.
       
   105 
       
   106 In addition to these conditional statements, Python provides a very
       
   107 convenient ternary conditional operator. Let us take the following
       
   108 example where we read the marks data from a data file which is
       
   109 obtained as a string as we read a file. The marks can be in the range
       
   110 of 0 to 100 or 'AA' if the student is absent. In such a case to obtain
       
   111 the marks as an integer we can use the ternary conditional
       
   112 operator. Let us say the string score is stored in score_str
       
   113 variable::
       
   114 
       
   115   score_str = 'AA'
       
   116 
       
   117 Now let us use the ternary conditional operator::
       
   118 
       
   119   score = int(score_str) if score_str != 'AA' else 0
       
   120 
       
   121 This is just the if/else statement block which written in a more
       
   122 convenient form and is very helpful when we have only one statement
       
   123 for each block. This conditional statement effectively means as we
       
   124 would have exactly specified in the English language which will be
       
   125 like score is integer of score_str is score_str is not 'AA' otherwise
       
   126 it is 0. This means that we make the scores of the students who were
       
   127 absent for the exam 0.
       
   128 
       
   129 Moving on, there are certain situations where we will have to no
       
   130 operations or statements within the block of code. For example, we
       
   131 have a code where we are waiting for the keyboard input. If the user
       
   132 enters "s" as the input we would perform some operation nothing
       
   133 otherwise. In such cases "pass" statement comes very handy::
       
   134 
       
   135   a = raw_input("Enter 'c' to calculate and exit, 'd' to display the existing
       
   136   results exit and 'x' to exit and any other key to continue: ")
       
   137 
       
   138   if a == 'c':
       
   139      # Calculate the marks and exit
       
   140   elif a == 'd':
       
   141      # Display the results and exit
       
   142   elif a == 'x':
       
   143      # Exit the program
       
   144   else:
       
   145      pass
       
   146 
       
   147 In this case "pass" statement acts as a place holder for the block of
       
   148 code. It is equivalent to a null operation. It literally does
       
   149 nothing. So "pass" statement can be used as a null operation
       
   150 statement, or it can used as a place holder when the actual code
       
   151 implementation for a particular block of code is not known yet but has
       
   152 to be filled up later.
       
   153 
       
   154 {{{ Show summary slide }}}
       
   155 
       
   156 This brings us to the end of the tutorial session on conditional
       
   157 statements in Python. In this tutorial session we learnt
       
   158 
       
   159   * What are conditional statements
       
   160   * if/else statement
       
   161   * if/elif/else statement
       
   162   * Ternary conditional statement - C if X else Y
       
   163   * and the "pass" statement
       
   164 
       
   165 {{{ Show the "sponsored by FOSSEE" slide }}}
       
   166 
       
   167 This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India
       
   168 
       
   169 Hope you have enjoyed and found it useful.
       
   170 Thankyou
       
   171  
       
   172 .. Author              : Madhu
       
   173    Internal Reviewer 1 :         [potential reviewer: Puneeth]
       
   174    Internal Reviewer 2 :         [potential reviewer: Anoop]
       
   175    External Reviewer   :
       
   176