Python-Ref > Basic usage > Conditional processing > The IF
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

The IF

The basic means of conditional processing is the if keyword.
If is used when some code has to be run only in specific cases.
Expand/Shrink
Zdroj: (if1.py)
  1   items = [1,2,3]
  2   for item in items:   # we loop over the sequence of items
  3       if item == 2:    # for each item we ask if it is equal to 2
  4           print item   # we print it only if the condition is true
stdout:
2
Doba běhu: 67.7 ms
The '==' operator is different from '='. The former is used for comparison of equality, the latter for assignment. Mistaking them often leads to hard to find errors.
The keyword else accompanies if and is used to catch cases that were not matched in the if condition.
Expand/Shrink
Zdroj: (if2.py)
  1   items = [1,2,3]
  2   for item in items:
  3       if item == 2:
  4           print "hit", item   # in case of 2 we have a hit
  5       else:                   # otherwise
  6           print "miss", item  # we have a miss
stdout:
miss 1
hit 2
miss 3
Doba běhu: 20.4 ms
Expand/Shrink
Zdroj: (if2-1.py)
  1   numbers = range(10)
  2   print numbers
  3   
  4   for number in numbers:
  5       if number % 2 == 0:
  6           print "even", number
  7       else:
  8           print "odd", number
  9       print "still in loop..."
 10   print "not in loop anymore."
stdout:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
even 0
still in loop...
odd 1
still in loop...
even 2
still in loop...
odd 3
still in loop...
even 4
still in loop...
odd 5
still in loop...
even 6
still in loop...
odd 7
still in loop...
even 8
still in loop...
odd 9
still in loop...
not in loop anymore.
Doba běhu: 21.3 ms
The keyword elif (short for 'else if') may be used together with if and else to create multi-branch conditions.
Expand/Shrink
Zdroj: (if3.py)
  1   items = range( 20)   # range creates a list of values 0..19
  2   for item in items:
  3       if item == 2:           # in case of 2 we have a hit
  4           print "hit", item
  5       elif item < 5:          # smaller than 5 but not 2 (2 was matched before)
  6           print "small", item
  7       elif item < 10:         # between 5 and 10 (all others were matched before)
  8           print "normal", item
  9       else:
 10           print "large", item # all others
stdout:
small 0
small 1
hit 2
small 3
small 4
normal 5
normal 6
normal 7
normal 8
normal 9
large 10
large 11
large 12
large 13
large 14
large 15
large 16
large 17
large 18
large 19
Doba běhu: 21.8 ms