Basic Programming Constructs

Let us recollect some of the basic programming constructs of Python.

  • We can perform all standard arithmetic operations using standard operators.

    • + for addition

    • - for subtraction

    • * for multiplication

    • / for division

    • % for modulus

  • Comparison Operations (==, !=, <, >, <=, >=, etc)

    • All the comparison operators return a True or False (Boolean value)

  • Conditionals (if)

    • We typically use comparison operators as part of conditionals.

  • Loops (for)

    • We can iterate through collection using for i in l where l is a standard collection such as list or set.

    • Python provides special function called as range which will return a collection of integers between the given range. It excludes the upper bound value.

  • In Python, scope is defined by indentation.

Tasks

Let us perform few tasks to quickly recap basic programming constructs of Python.

  • Get all the odd numbers between 1 and 15.

range?
Init signature: range(self, /, *args, **kwargs)
Docstring:     
range(stop) -> range object
range(start, stop[, step]) -> range object

Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
Type:           type
Subclasses:     
list(range(1, 16))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
list(range(1, 16, 2))
[1, 3, 5, 7, 9, 11, 13, 15]
  • Print all those numbers which are divisible by 3 from the above list.

for i in list(range(1, 16, 2)):
    if i % 3 == 0: 
        print(i)
    else:
        print('Not divisible by 3')
Not divisible by 3
3
Not divisible by 3
Not divisible by 3
9
Not divisible by 3
Not divisible by 3
15