3  Conditions and Loops

3.1 Conditions

We have seen data type boolean which has got two values True, False. Boleans are results of various operators as given below

  >>> "hel" in "hello" # the in operator checks if first string is part of second string
  True
  >>> "hel" in "world!"
  False
  >>> x = "hello"
  >>> y = "hello"
  >>> x == y  #equality operator
  True
  >>> 1 in [2, 2, 2, 1, 1, 2] #checks if element 1 is in list on right
  True
  >>> 5 not in [1, 2, 3, 4] # checks if element 5 not in list on right side
  True
  >>> x , y = 5, 4
  >>> x > y
  True
  >>> x >= y
  True
  >>> y < x
  True
  >>> y <= x
  True
  >>> x != y # checks if left and right side are not equal
  True

Conditions are one of the basic building blocks of basic programming constructs.::

  if "hel" in "cell":
      print("hell!") # executed if condition of this block is True
  elif "cel" in "hell": # optional
      print("cell!") # executed if condition of this block is True
  elif "del" in "bell":
      print("dell!") # executed if condition of this block is True
  else:                 # if no condition matched, this is too optional
      print("opps!")

if the conditions have only two possiblities and simple statements, then it is also possible to make one liner if, else statement.

  >>> cond = True
  >>> x = 2 if cond else 3
  >>> x
  2
  >>> cond = False
  >>> x = 2 if cond else 3
  >>> x

3.2 For loop

To iterate over a collection you don’t need to keep track of index. Just like in english one would say for every_student in class … to iterate over all students in class, same way one can iterate over items in a collection in python.::

  words = ["one", "two", "three", "four", "five", "six"]

  for word in words:
      print(word, end=",")

  'one','two','three','four','five',

for loops works on strings, lists, tuples, dictionaries etc.::

  for item in {"x":1, "y":2}:
      print(item)
  x
  y
  d = {"x":1, "y":2}
  for key, value in d.items():
      print(key, value)

  x 1
  y 2

3.2.1 Example

Write our own function mysum which finds sum of numbers from a list::

  def mysum(nums):
      s = 0
      for n in nums:
          s = s + n
          # s += n # this is same as above statement
      return s

  mysum(range(1,11))
  55