Functions

two main reasons for functions: modularity and multi-purpose
In [5]:
def square(x):  # x is referred to as a parameter
    return x * x
In [6]:
square(5)  # 5 is referred to as an argument or input
Out[6]:
25
In [7]:
square(10)
Out[7]:
100
In [11]:
def printHello(name):
    print("Hello, "+name)
    return "I just printed something"
In [12]:
printHello("Raj")
Hello, Raj
Out[12]:
'I just printed something'
In [13]:
printHello("Bello")
Hello, Bello
Out[13]:
'I just printed something'
In [14]:
def sum(x,y):
    return x+y
In [15]:
sum(10,20)
Out[15]:
30
In [16]:
sum(100,200)
Out[16]:
300

While loop

In [19]:
xs = [10,5,20,30,6,90]
index = 0
found = False
while not found and index < len(xs):
    if xs[index] == 5:
        found = True
    else:
        index = index + 1
if found:
    print("I found the 5")
else:
    print("I did not find the 5")
I found the 5
In [26]:
xs = (1,"raj",3)
In [27]:
xs[0]
Out[27]:
1
In [28]:
xs[1]
Out[28]:
'raj'
In [29]:
xs[2]
Out[29]:
3
In [20]:
## Bulls and Cows
In [ ]:
3612
In [31]:
# This function takes as input a 4-digit number and 
# returns a tuple of its 4 digits.
def extractDigits(num):
    d4 = num%10
    d3 = (num//10)%10
    d2 = (num//100)%10
    d1 = (num//1000)%10
    return (d1,d2,d3,d4)
In [32]:
extractDigits(3612)
Out[32]:
(3, 6, 1, 2)
In [34]:
extractDigits(3490)
Out[34]:
(3, 4, 9, 0)
In [35]:
from random import *
In [43]:
randint(1000,9999)
Out[43]:
3301

Objects and Classes

In [45]:
s1 = "This is a sentence"
t1 = s1.upper()  # upper is a method
print(t1)
THIS IS A SENTENCE
In [46]:
class Student:

    # CONSTRUCTOR method MANDATORY
    def __init__(self,name): # need to assign a value to every attribute
        self._name = name
        self._courses = []

    def add_course(self,cno,credits,grade):
        self._courses.append((cno,credits,grade))
  
    def gpa(self):
        grade_points = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}
        points = 0
        total_credits = 0
        for (cn,cr,g) in self._courses:
            points = points + cr*grade_points[g]
            total_credits = total_credits + cr
        if (total_credits > 0):
            return round(points/total_credits,2)
        else:
            return None
In [47]:
s1 = Student("Raj")
In [49]:
s1._name
Out[49]:
'Raj'
In [50]:
s1._courses
Out[50]:
[]
In [51]:
s1.add_course('101',3,'A')
s1.add_course('102',3,'A')
s1.add_course('201',3,'B')
s1.add_course('202',3,'C')
In [52]:
s1._name
Out[52]:
'Raj'
In [53]:
s1._courses
Out[53]:
[('101', 3, 'A'), ('102', 3, 'A'), ('201', 3, 'B'), ('202', 3, 'C')]
In [54]:
s1.gpa()
Out[54]:
3.25
In [ ]: