Python
Python
Workshop
Shaastra, IIT Madras
Python vs Java
Python programs are generally slower than Java programs.
But take less time to write.
(Python programs are typically 3-5 times shorter than equivalent Java
programs.)
For these reasons, Python is much better suited as a "glue" language,
while Java is better characterized as a low-level implementation
language.
The combination of Python and Java works good for many
applications.
Python vs C++
C++ programs are faster than Python programs.
But take more time to write.
(C++ programs are even more longer than Java programs, i.e.,
Python programs are 5-10 times shorter than C++ programs.)
Fact: What Python programmer can finish in 2 months, two C++
programmers cant complete in a year.
Python is used to combine the components written in C++, hence
acting as a glue language.
In Python:
a, b = b, a
Why Python?
Easy to learn.
User friendly language.
Easy syntax.
Requires less programming efforts.
Interpreted language (no need to compile code).
The commands are logically derived from spoken
English.
Keywords in Python
Keywords in Python are reserved words that cannot be used as
ordinary identifiers/variables. They must be spelled exactly as
they are written.
Following is the list of keywords in Python:
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
'while', 'with', 'yield']
Variables in Python
Variables are not declared, just assigned
values.
Variables are automatically created the first
time you assign a value.
Are reference to objects.
Numbers
Normal Integers represent whole numbers
Ex: 3, -7, 123, 76
Long Integers unlimited size
Ex: 9999999999999999999999L
Floating-point represent numbers with decimal places
Ex: 1.2, 3.14159,3.14e-10
Octal and hexadecimal numbers
Ex: O177, 0x9ff, Oxff
Operators Basics
Example, y=5; z=3
+add
- subtract
* multiply
/ divide
% modulus/remainder
x=y+z
x=y-z
x=y*z
x=y/z
x=y%z
x=8
x=2
x=15
x=1
x=2
Operators Basics
** raise to power
>> right shift
<< left shift
// Floor division
x=y**z
x=y>>2
x=y<<1
x=y//z
x=125
x=1
x=10
x=1
Short-hand operations
x+=a => x=x+a
x-=a => x=x-a
x*=a => x=x*a
x/=a => x=x/a
Python as calculator
>>> 2 + 2
4
>>> 8 / 5.0
1.6
>>> 8 / 3 #int / int = int
2
>>> 5**2 #a**b = a raised to power b
25
Python as calculator
>>> 3 * 3.75 / 1.5
7.5
>>> 5 * 3 + 2
17
>>> 50 - 9 * 3
23
>>> 2 + 4**3
66
in operator
Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
x in y, here in results in a 1 if x is a member of sequence y.
Example:
a = 10
list = [11, 30, 10, 22, 15]
if (a in list):
print a is in the list
else
print a is not in the list
is operator
Evaluates to true if the variables on either side of the operator point to the same
object and false otherwise.
x is y, here is results in 1 if id(x) equals id(y).
Example:
a = 10
b = 10
if (a is b):
print a is equal to b
else
print a is not equal to b
Strings Introduction
>>> shaastra
shaastra
>>> python workshop
python workshop
>>> shaastra[2]
a
Print command
>>> width = 20
>>> print width
20
>>> word = Shaastra
print appends a new line automatically. To avoid that add ,.
>>> print word, width
Shaastra 20
>>> print %s is the techfest of IIT Madras. %(word)
Shaastra is the techfest of IIT Madras.
Lists Introduction
Most versatile datatype available in Python.
Ordered collection of data.
All items in the list need not have same
datatype.
List introduction
>>> list1 = [1,2,3,4]
>>> print list1
[1,2,3,4]
>>> squares = [1,4,9,16]
>>> print squares
[1,4,9,16]
Editing a list
>>> squares = [1, 4, 9, 16, 25]
>>> squares + [36, 48, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 48, 64, 81, 100]
>>> squares[6] = 49
>>> print squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> squares.append(121)
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100,121]
range function
range ([start,] stop [,step])
>>> range(4)
[0,1,2,3]
>>> range(1,4)
[1,2,3]
>>> range(1,10,2)
[1,3,5,7,9]
List of characters
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> len(letters)
7
>>> letters*2
['a', 'b', 'C', 'D', 'E', 'f', 'g','a', 'b', 'C', 'D', 'E', 'f', 'g']
List of strings
>>> a = [Shaastra, 2015, IIT, Madras]
>>> a[0]
Shaastra
>>> a[2][2]
T
>>> a[3][1]
a
Console Input
>>> a=input(Enter a number: )
Enter a number: 2
>>> a
2
>>> a=raw_input(Enter a string: )
Enter a string: abc
>>> a
'abc'
>>> a = input ("Enter any expression: ")
Enter any expression: 'hello' + 'world'
More on lists
>>> l=[1,2,3]
>>> l.extend([4,5])
>>> l
[1, 2, 3, 4, 5]
>>> l.remove(4)
>>> l
[1, 2, 3, 5]
More on lists
>>> l = [ 1, 2, 1, 1, 0, 5, 1, 3, 5, 1 ]
>>> print l.count (1), l.count (5)
52
>>> l.sort ()
>>> print l
0111112355
>>> l.reverse ()
>>> print l
5532111110
Strings
>>> p = Shaa
>>> p[2]
a
>>> p = p + stra
>>> p
Shaastra
>>> p[2:5] + p[0]
aasS
Strings cont.
>>> p*5
ShaastraShaastraShaastraShaastraShaastra
>>> len(p)
8
>>> string = , .join([Apple,Mango,Banana])
>>> print string
Apple, Mango, Banana
>>> print p.upper()
SHAASTRA
# try lower() function too
Dictionary
map keys to values like lists, but indices can be of any type.
Also, keys are in no particular order.
Example:
mydict={b:3, a:4, 75:2.85}
mydict[b] -> 3
mydict[75] -> 2.85
mydict[a] -> 4
Dictionary
>>> mobileno={"M": 938477566,"U" : 938377264}
>>> mobileno[M]
938477566
>>> print mobileno.keys()
[M,U]
>>> del mobileno[M]
>>> mobileno
{"U" : 938377264}
Editing in dictionary
>>> mobileno[S]=9542813947
>>> print mobileno
{"U" : 938377264,S : 9542813947}
>>> mobileno[U]=8123884336
>>> print mobileno
{"U" : 8123884336,S : 9542813947}
Dictionary contd..
>>> mydict = {r:1, g:2, y:3.5, 8.5:8, 9:nine}
>>> mydict.values()
[3.5, 8, 1, 2, 'nine']
>>> mydict.has_key(r)
True
>>> mydict.update({a:75})
{8.5: 8, 'a': 75, 'r': 1, 'g': 2, 'y': 3.5, 9: 'nine'}
if/else statement
>>> x = input (Enter a integer: )
Enter a integer: 13
>>> if x < 0:
...
print (Negative)
. . . elif x == 0:
...
print (Zero)
. . . else:
...
Positive
print (Positive)
#elif - else-if
Nested if
>>> x = 17
>>> if x < 10:
...
print 'a'
. . . elif x > 10:
...
if x<20:
...
print 'b'
. . . else:
...
print 'c'
b
While statement
To print odd numbers less than a
>>> i=1
>>> while i<10:
#execute while the statement is true
...
print i
...
i+=2
# it means i=i+2
1
3
5
7
9
Defining Functions
>>> def fib (n):
...
a, b = 0, 1
...
while a < n:
...
print a
...
a, b = b, a+b
...
>>>
. . . fib (2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
List Comprehension
Concise way to create lists.
Construct lists in easy way as we do in mathematics.
Syntax: *result* = [ *expression* *iteration* *filter* ]
expression is based on variable used for each element.
iteration contains the for loops.
filter contains the if statements.
result is the final list.
Ques 1
Write a program that initially has a list A
containing N strings and produces a dictionary
the
strings of the list A as keys and the
corresponding lengths of the strings as values
Eg: A = ['hello', 'how', 'are']
Program output: {'hello': 5, 'how': 3, 'are': 3}
Ques 1 sol
A=['hello','how','are'] #list of strings
d={}
#empty dictionary
for i in A:
d[i]=len(i)
#defining the keys and assigning values to the keys
Ques 2
Write a program that takes 3 numbers as input
from the user; and prints the maximum of the
three.
Ques 2 sol
n1=input("Enter 1st number:") #taking input of numbers
n2=input("Enter 2nd number:")
n3=input("Enter 3rd number:")
x=[n1,n2,n3]
#storing the numbers in the list
max=n1
#initializing max by assisgning it the value of 1st
number
for i in x:
if i>max:
#comparing all other numbers with initialized value of max
max=i
#if other number is large then modifying max
print max
#printing max
Ques 3
Write a program that prints the sum of all even
numbers in a list
Ques 3 sol
list=[12,32,7,65,31,87,53,34,2,0]
#given list
sum=0
#initializing sum=0
for i in list:
#for all i's in the list
if (i%2)==0:
#checking if i is even or not
sum+=i
#calculating sum
print sum
#printing sum
Ques 4
Write a program that prints the reverse of a
string
Ques 4 sol
st=raw_input("Enter a string :") #taking input of a string
a=len(st)-1
b=len(st)
l1=[]
for i in st:
l1.append(i)
l1.reverse()
st2=''.join(l1)
print st2
Ques 5
Write two programs to print the following pattern using
while loop and for loop
1
12
123
1234
12345
123456
Ques 6
To print the letter frequency for each letter in
the string.
Ques 6 sol
st=raw_input(Enter a string)
d={}
for i in st:
if i in d.keys():
d[i]+=1
else:
d[i]=1
print d
Ques 7
Define a procedure histogram() that takes a list of integers and
prints a histogram to the screen. For example,histogram([4, 9, 7])
should print the following:
****
*********
*******
Ques 7 sol
def histogram (t):
for i in range (len (t)):
print '*' * t[i]
x = [4, 9, 7]
histogram (x)
Ques 8
A pangram is a sentence that contains all the letters of the
English alphabet at least once, for example: The quick
brown fox jumps over the lazy dog. Your task here is to
write a function to check a sentence to see if it is a
pangram or not.
Ques 8 sol
chars='abcdefghijklmnopqrstuvwxyz'
string = raw_input("Enter the string : ")
a=1
for i in chars:
if i not in string:
a=0
break
if a==1:
print "Yes"
else:
print "No"
Ques 9
Program to check if a string is a palindrome or
not.
Ques 9 sol
string = raw_input("Enter a string : ")
l=len(string)
a=1
for i in range(l):
if string[i]!=string[l-i-1]:
a=0
break
if a==0:
print "NO"
else:
print "Yes"
Ques 10
You are given a list of strings and a integer n.
You have to print the list with all the strings in
the given list of strings with length greater than
n.
Ques 10 sol
L=input("Enter a list of strings : ")
n=input("Enter a number : ")
L2=[ ]
for i in L:
if len(i)>n:
L2.append(i)
print L2