Workshop on the basics of Python

  • Python is an interpreted, high level language.
  • Interpreted - No compilation.
  • Extremely powerful and easy to understand.
  • So many features - The Swiss knife of programming.
  • Used by Google, Youtube, NASA, AI companies, etc.
In [64]:
print "Hello, CSE!"
Hello, CSE!
In [62]:
a = 10
b = 5
print a, b

a, b = b, a
print a, b
10 5
5 10

But what about int n??

No need to specify data types. Automatically recognises them

In [65]:
n = 10

s = "Department of CSE"

marks = [
    90, 82, 99, 97
]

marksTuple = (
    90, 82
)

regNos = {
    95: "Siva",
    116: "Vignesh",
    85: "Sagar"
}

print type(n)
print type(s)
print type(marks)
print type(regNos)
<type 'int'>
<type 'str'>
<type 'list'>
<type 'dict'>

int

Use raw_input() for getting inputs.

eg.

In [66]:
testNo1 = raw_input()
testNo2 = raw_input()

print testNo1 + testNo2
1
2
12

Why ??

raw_input takes str arguments by default. Cast it to int when necessary.

In [67]:
testNo1 = int(raw_input())
testNo2 = int(raw_input())

print testNo1 + testNo2

#Subtraction, Multiplication     -> One line comment
"""
Division, Modulo have the same   -> Multiline comment
operators as that of other
languages like C
"""
2
3
5
Out[67]:
'\nDivision, Modulo have the same   -> Multiline comment\noperators as that of other\nlanguages like C\n'
In [69]:
testNo1 ** testNo2
Out[69]:
8

There is also a complex data type.

In [70]:
c1 = 3 + 5j
c2 = 5 - 8j

print type(c1)
print c1 + c2
print c1 - c2
print c1 * c2
print c1 / c2
print c1 ** c2
<type 'complex'>
(8-3j)
(-2+13j)
(55+1j)
(-0.280898876404+0.550561797753j)
(-22828539.0958-11631178.0866j)

Task

Can you figure out how to do 10/3 in floating point?

str

In [71]:
s1 = "Hello"
s2 = "World" #can also be written as 'World'

print s1 + ", " + s2 + "!"
print len(s1)

print s1*3
Hello, World!
5
HelloHelloHello

Task

Write a Python code to take in your name and CGPA as inputs and print "Welcome to Python, nameHere. Your CGPA is CGPAHere"

Welcome to Python, Siva. Your CGPA is 8.

List

Collection of elements. The elements can be of different data types.

In [73]:
l = [1, 2, 3]

To access list elements, use

In [74]:
print l[0]
1

Python strings are like a list of characters. So,

In [75]:
print s1[0] #Will give the first element
H

To add an element,

In [76]:
l.append(4)

print l
[1, 2, 3, 4]

Slicing a list - the cool part

In [77]:
dept = "Department of CSE"

#Usage: list[startingIndex:endingIndex:increment]
print dept[4:8]
print dept[4:8:2]

#Tricks
print dept[5:len(dept)-1] #will print from 5th element to the end
print dept[:8]            #print from the starting element to the 8th element
print dept[::-1]          #print the list in the reverse order


#Finding an element
pos = dept.index("CSE")
print "The word CSE is present at " + str(pos) + "th position"

#Joining the elements of a list
joinExample = [
    '1', '2', '3'        #Be careful to use a list with str elements for join 
]
print ",".join(joinExample)
rtme
rm
tment of CS
Departme
ESC fo tnemtrapeD
The word CSE is present at 14th position
1,2,3

Using lists and str together

Task

In [78]:
sentence = "My name is Siva"
words = sentence.split() #or sentence.split(" ")
print words
['My', 'name', 'is', 'Siva']

Can you produce the following output using the list words?

Siva is name My

Clue: Use join.

Dictionary

In [79]:
dictionary = {
    1: "one",
    2: "two",
    3: "three"
}

print dictionary[1]

print dictionary.values()
print dictionary.keys()
one
['one', 'two', 'three']
[1, 2, 3]

Task

Write a program that would get a number from a user between 20 and 30 and print it in words.

Example,

input  -> 25
output -> twenty five

Clues:

  • Use raw_input() for input. Be careful with the data type.
  • Use a dictionary for storing the corresponding words for numbers.
  • A rough, dirty approach would be like,
words = {
   1: "one"
   4: "four"
}
n = 24 #example
print "twenty " + words[int(str(n)[1])]

The above solution is too dirty. Python is all about code beauty. Try and make it beautiful.

Conditions and looping

Python has no braces. Indentation is used instead.

Also, there is no switch.

In [80]:
if(True):
    print "Hello"
else:
    print "No"
Hello
In [81]:
a = 10

if(a == 1):
    print "one"
elif(a == 2):
    print "two"
else:
    print "oops"
oops
In [82]:
i = 10
while(i > 0):
    print i
    i -=1
10
9
8
7
6
5
4
3
2
1
In [83]:
#usage: range(start, end, increment)
for x in range(10):
    print x
0
1
2
3
4
5
6
7
8
9
In [84]:
a = ["one", "two", "three"]
for x in a:
    print x
one
two
three
In [1]:
#what's the difference?
for x in xrange(10):
    print x
0
1
2
3
4
5
6
7
8
9

List comprehension

In [85]:
nos = [x for x in range(20)]
nos
Out[85]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [86]:
even = [x for x in range(20) if x%2 == 0]
even
Out[86]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [87]:
strange_odd = [x+1 for x in range(20) if x%2 == 0]
strange_odd
Out[87]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Functions

In [88]:
def area(side):
    return side*side

def foo(side, length=2):
    return (side*length)

print area(10)

trial2 = foo(2)
print trial2
100
4
In [89]:
#note the %i and %f

def tax(bill):
    """Adds 8% tax to a restaurant bill."""
    bill *= 1.08
    print "With tax: %f" % bill
    return bill

def tip(bill):
    """Adds 15% tip to a restaurant bill."""
    bill *= 1.15
    print "With tip: %i" % bill
    return bill
    
meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)
With tax: 108.000000
With tip: 124

Lambdas

Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda".

They do not have return statements.

Python supports functional programming. Lambdas play a role here.

Especially useful when you want to pass a function as a variable.

In [90]:
def foo(x):
    return x**x

f = foo(4)
print f

g = lambda l: l**l
print g(4)
256
256
In [91]:
def increment (n): return lambda x: x + n

sample = increment(2)
print sample(5)

print increment(2)(5)
7
7
In [46]:
nos = [1, 2, 3, 4, 5, 6]
print filter(lambda x: x%2 == 0, nos)
[2, 4, 6]
In [50]:
squares=[x**2 for x in range(1,11)]
print filter(lambda x: (x>=30)and(x<=70),squares)
[36, 49, 64]

Task

Can you write a list-comprehension only equivalent of the above lambda?

Classes

In [92]:
#all class methods will have a self parameter. this is different from c++


class Fruit(object):
    """A class that makes various tasty fruits."""
    def __init__(self, name, color, flavor, poisonous):
        self.name = name
        self.color = color
        self.flavor = flavor
        self.poisonous = poisonous

    def description(self):
        print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)
        
    def is_edible(self):
        if not self.poisonous:
            print "Yep! I'm edible."
        else:
            print "Don't eat me! I am super poisonous."

lemon = Fruit("lemon", "yellow", "sour", False)

lemon.description()
lemon.is_edible()
I'm a yellow lemon and I taste sour.
Yep! I'm edible.
In [93]:
class Triangle(object):
    number_of_sides=3
    
    def __init__(self,angle1,angle2,angle3):
        self.angle1=angle1
        self.angle2=angle2
        self.__angle3=angle3
        
    def check_angles(self):
        sum=self.angle1+self.angle2+self.__angle3
        if sum==180:
            return True
        else:
            return False
        
class Equilateral(Triangle):
    angle = 60
    
    def __init__(self):
        self.angle1 = self.angle
        self.angle2 = self.angle
        self.angle3 = self.angle
        
my_triangle=Triangle(45,60,60)
my_triangle=Equilateral()

print my_triangle.angle

print my_triangle.number_of_sides
print my_triangle.check_angles()

my_triangle=Triangle(45,60,75)
print my_triangle.check_angles()

print my_triangle.angle2
#Use double-underscore for private variable in the class definition
print my_triangle.__angle3

1
60
3
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-93-e7dcceb6e42e> in <module>()
     28 
     29 print my_triangle.number_of_sides
---> 30 print my_triangle.check_angles()
     31 
     32 my_triangle=Triangle(45,60,75)

<ipython-input-93-e7dcceb6e42e> in check_angles(self)
      8 
      9     def check_angles(self):
---> 10         sum=self.angle1+self.angle2+self.__angle3
     11         if sum==180:
     12             return True

AttributeError: 'Equilateral' object has no attribute '_Triangle__angle3'

Miscellaneous

In [94]:
print 5 >> 4  # Right Shift
print 5 << 1  # Left Shift
print 8 & 5   # Bitwise AND
print 9 | 4   # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88     # Bitwise NOT
0
10
0
13
38
-89
In [95]:
for i in range(2,6):
    print bin(i)
    print bin(i)[2:]
0b10
10
0b11
11
0b100
100
0b101
101
In [58]:
print int("111",2)
print int("0b111",2)
7
7

Tasks..Let the games begin.

In [ ]: