Introduction to Programming - Lecture 3

Material covered :

1. Conditional statement "if" and Logical Operators
2. For loops

If-else and Logical Operators

"If" is the simplest conditional statement. It simply checks if an evaluation condition is True and if it is then it executes a certain block of code. The checking is usually done by a logical operator such as --> more than( > ), less than( < ), equal to( == ), not equal to ( != or not), etc 

 if <condition>:
     execute statement(s)

Binary Logical Operators :

1. Greater than ( > )
2. Less than ( < )
3. Equal to ( == )

Unary Logical Operators :

1. ! or not

Let us look at some examples : 

In [ ]:
# Greater than ( > )
if 1 > 0:
    print("One is more than zero")
else:
    print("BITS Pilani Goa Campus is better than IIT Kanpur")
    
# Less than ( < )
if 12 < 42:
    print("Yes, 12 is less than 42")
else:
    print("Everyone registered in CTE Python will pass with distinction (90%+ marks)")
    
# Equal to ( == )
if 2 + 2 == 4:
    print("Two plus Two equals Four")
else:
    print("Lite......")
    
# Not equal to ( != )
if 1 != 0:
    print("Sachin")
else:
    print("Kohli")
    
# Inversion operator
if not 2 + 2 == 4:
    print("Lite....")
else:
    print("CTE Python....")

Chained Conditional

if <condition 1> is True:
    execute <statement(s) > 1
elif <condition 2> is True:
    execute <statement(s) > 2
elif <condition 3> is True:
    execute <statement(s) > 3
elif <condition 4> is True:
    execute <statement(s) > 4
.
.
.
else:
    execute <statement(s)> n

Let us see an example :


In [ ]:
if 1 < 0:
    print(1, end='')
elif 2 == 3:
    print(2, end='')
elif not 3 == 4:
    print(3, end='')
print(".....Lite")

The condition need not directly involve a logical operator. For example :


In [ ]:
a = [1, 2, 3]

if isinstance(a, list):
    print(a, "is a list !")
    
if 2 in a:
    print("Yes, 2 is in ", a)
    
if 5 not in a:
    print("No, 5 is not in ", a)

Iterations

Iterative constructs are a key feature of any well developed programming language.
Looping can be done over an iterable which can be a list, set, dictionary, etc.
Let us concern ourselves with lists for now.

Common library functions to use in loops :

range

 Usage : range(start, stop, step)

 This library function returns a list which is an arithmetic progression. The default step value is 1.

Examples


In [3]:
list(range(0, 10))


Out[3]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [4]:
list(range(-4, 10))


Out[4]:
[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [5]:
list(range(0, 10, 3))


Out[5]:
[0, 3, 6, 9]

In [7]:
list(range(0, 5, -6))


Out[7]:
[]

In [8]:
list(range(-10, 10, -5))


Out[8]:
[]

In [9]:
list(range(10, 2, 3))


Out[9]:
[]

In [10]:
list(range(10, 1, -2))


Out[10]:
[10, 8, 6, 4, 2]

enumerate

 Usage : enumerate(<list>, starting_index=1)

 This library function returns an iterable object contains tuples of structure (index, list value at index).
 Extra optional argument provides a different starting index. Default starting index is 0.
 In that case the tuples are of the structure (index, list value at <index - starting_index>)

Examples


In [11]:
list(enumerate(range(0,5)))


Out[11]:
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

In [13]:
list(enumerate(range(0,5), 10))


Out[13]:
[(10, 0), (11, 1), (12, 2), (13, 3), (14, 4)]

For Loop

Structure

for value in iterable:
    execute statement(s)

Only by looking at many examples will this become clear

In [32]:
a = [1, 2, 3, 4, 5]

for value in a:
    print(value, end=' ')


1 2 3 4 5 

In [31]:
b = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
for sublist in b:
    for value in sublist:
        print(value, end=' ')


1 2 3 4 5 6 7 8 9 

Tuples

Tuples are the immutable equivalent of lists.

Declared by : (value_1, value_2, .....)

In [4]:
a = (2, 3, 4)
print(a)


(2, 3, 4)

You cannot change any element of a tuple to a new value since tuples are immutable types. For example :


In [5]:
a[1] = 10
print(a)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-efd97496539c> in <module>()
----> 1 a[1] = 10
      2 print(a)

TypeError: 'tuple' object does not support item assignment

In [38]:
a = ["One", "Two", "Three"]
for i, value in enumerate(a):
    print("Value at index <", i, "> of list<a> is : ", value)


Value at index < 0 > of list<a> is :  One
Value at index < 1 > of list<a> is :  Two
Value at index < 2 > of list<a> is :  Three

In [43]:
for i in range(0, 10):
    for j in range(0, i):
        print("*", end='')
    print("")


*
**
***
****
*****
******
*******
********
*********

In [42]:
for i in range(0, 10):
    for j in range(10, i, -1):
        print(" ", end='')
    for k in range(0, i):
        print("*", end='')
    print("")


          
         *
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********

Short in-class assignment

Write a program to print the following pattern.

**********
****--****
***----***
**------**
*--------*
**------**
***----***
****--****
**********

First line --> 10 stars
Second line --> 4 stars ,2 dashes, 4 stars
Third line --> 3 stars, 4 dashes, 3 stars
.
.
.
Eigth line --> 4 stars ,2 dashes, 4 stars
Ninth line --> 10 stars again.

In [57]:
for i in range(0, 5):
    for j in range(0, 5 - i):
        print("*", end='')
    for k in range(0, 2*i):
        print("-", end='')
    for j in range(0, 5 - i):
        print("*", end='')
    print("")

for i in range(3, -1, -1):
    for j in range(0, 5 - i):
        print("*", end='')
    for k in range(0, 2*i):
        print("-", end='')
    for j in range(0, 5 - i):
        print("*", end='')        
    print("")


**********
****--****
***----***
**------**
*--------*
**------**
***----***
****--****
**********

In [ ]: