Sunteți pe pagina 1din 90

Python

Workshop
Shaastra, IIT Madras

Common Programming Languages


Java
C
C++
C#
Python
JavaScript
PHP
Ruby
SQL
Matlab

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.

Printing Hello World in Java


import java.util.*
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

Printing Hello World in C++


#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}

Printing Hello World in Python

print Hello World!

Swap two variables


In C/C++/Java:
temp = a;
a = b;
b = temp;

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.

Python used around the globe


Google - It uses Python for many tasks including the backends of
web apps such as Google Groups, Gmail, and Google maps, as well
as for some of its search-engine internals.
NASA - It is using Python to implement a CAD/CAE repository and
model management, integration, and transformation system which
will be the core infrastructure for its next-generation collaborative
engineering environment.
Walt Disney - It uses it for graphics.
Youtube - It uses Python to produce maintainable features in record
times, with a minimum of developers.

Python Programs Overview


Programs are composed of modules
Modules contain statements
Statements contain expressions
Expressions create and process objects

Comments in Python programs


There are two styles of comments in python:
# this is single line comment
" " " this is a multiline comment
which spawns many lines
"""

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.

Variable names in Python


Have the following restrictions:
Must start with a letter or underscore (_)
Case sensitive
Must consist of only letters, numbers or underscore
Must not be a reserved word

Variable names Conventions


Have the following conventions:
All uppercase letters are used for constants
Variable names are meaningful thus, often multi-word
o Convention 1: alignment_sequence
o Convention 2: AlignmentSequence

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

(digits after decimal are removed)

x=125
x=1
x=10
x=1

Comparison & Bitwise Operators


== - checks if the two operands are equal.
!= or <> - checks if the two operands are not equal.
> - checks if left operands value is greater than right operands.
< - checks if right operands value is greater than left operands.
& - bitwise AND
| - bitwise OR
^ - bitwise XOR
~ - bitwise ones compliment operator (unary operator).

Short-hand operations
x+=a => x=x+a
x-=a => x=x-a
x*=a => x=x*a
x/=a => x=x/a

Start programming in Python


Two modes for python programming
a.From terminal
.Start a new terminal
.Type python. You can start your programming in python
here (>>>)
b. As programs
.Source file suffixed with .py.
.To run, python filename.py

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

Complex numbers in Python


>>> a = 2 + 3j
>>> b = 1j
>>> print a+b
(2 + 4j)
>>> print a*b
(-3 + 2j)
>>> print a/b
(3 - 2j)

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

math library in python


Using the math functions:
>>> import math
>>> math.factorial (5)
120
>>> math.log (1024, 2)
10.0
>>> math.sqrt (16.0)
4.0

math library in python


Trigonometric Functions in the math library:
>>> import math
>>> math.cos (math.pi / 4.0)
0.7071067811865476
>>> math.tan (math.radians(45))
0.9999999999999999
>>> math.acos (0)
1.5707963267948966

Strings Introduction
>>> shaastra
shaastra
>>> python workshop
python workshop
>>> shaastra[2]
a

= to assign value to variable


>>> width = 20
>>> height = 5 * 9
>>> width * height
900
>>> word = Shaastra
>>> word
Shaastra

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]

Accessing List elements


>>> squares = [1, 4, 9, 16, 25]
>>> print squares[0] # indexing returns the item
1
>>> print squares[-2]
16
>>> print squares[1:4]
[4,9,16]
list[a:b] returns alist from list[a] to list [b-1]

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'

#input() for input of all the basic data structures

Console Input contd..


>>> a
helloworld
>>> a=input(Enter a number: )
Enter a number: 4+7
>>> a
11
>>> a = input(Enter a list: )
Enter a list: [0, 1, 2, 3] + [4, 5, 6]
>>> a
[0, 1, 2, 3, 4, 5, 6]

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

string library in python


>>> import string
>>> string.atof(437.4876)
437.4876
>>> string.atoi(365)
365
>>> str = Shaastra 2015 IIT Madras
>>> str.split ( )
[Shaastra, 2015, IIT, Madras]

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:

# if the expression is true

...

# else if the event is false

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

Control Flow - for statement


>>> words = [ Shaastra, IIT Madras ]
>>> for w in words:
# for each element in the list words
...
print w
Shaastra
IIT Madras
>>> for w in words:
...
if len(w) > 6:
...
words.insert (1, 2015)
...
break
>>> words
[ Shaastra, 2015, IIT Madras ]

for statement contd..


>>> arr = [ a, b, c, d, e ]
>>> for i in range (len (a)):
...
print (i, arr[i])
...
0a
1b
2c
3d
4e

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

break & continue statements


>>> for n in range (2, 10):
...
for x in range (2, n):
...
if n % x == 0:
...
print n, is a composite number.
...
break
...
else:
...
continue

Program to check if a number is prime


prime = 1
n=input()
for i in range(2,n/2+1):
if n%i==0:
prime=0
break
if prime==0:
print Not Prime
else:
print Prime

Searching a number in a list


n=input(Enter the number of numbers: )
l=[ ]
for i in range(n):
l.append(input(Enter a number: ))
p=input(Enter the number that has to be found: )
for i in range(len(l)):
if l[i]==p:
print i

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

Functions contd.. (return statement)


>>> def fib (n):
...
a, b = 0, 1
...
result = [ ]
...
while a < n:
...
result.append (a)
...
a, b = b, a+b
...
return result
>>> f = fib (2000)
>>> print f
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]

Function to check if a number is prime


def checkforprime(n):
for i in range(2,n/2+1):
if n%i==0:
return False
return True
n=input()
if checkforprime(n)==False:
print Not Prime
else:
print Prime

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.

List Comprehension Example


Easy example to create a list of first 10
numbers:
>>> x = [i for i in range(10)]
>>> print x
. . . [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

List Comprehension Example


Example to create a list of squares.
1) You can use loops.
>>> squares = [ ]
>>> for i in range(10):
squares.append (i*i)
2) Or you can use list comprehension:
>>> squares = [ i*i for i in range(10) ]

List Comprehension contd..


Like, in mathematics the sets are written as:
S = {x3 : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2)
M = {x | x in S and x even}

List Comprehension contd..


In list comprehension, the above sets can be written as:
>>> S = [x**3 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]
>>> print S, V, M
. . . [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
. . . [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
. . . [0, 4, 16, 36, 64]

List Comprehension in Functions


>>> def double(x):
...
return x*2
>>> a = [ double(x) for x in range(10) if x%2==0 ]
>>> print a
. . . [0, 4, 8, 12, 16]

List comprehension with more than 1 loops


>>> l=[1,2,3]
>>> p=['Python','Perl','java']
>>> print [(i,j) for i in l for j in p]
[(1, 'Python'), (1, 'Perl'), (1, 'java'), (2, 'Python'), (2, 'Perl'), (2, 'java'), (3,
'Python'), (3, 'Perl'), (3, 'java')]
>>> print [(i,j) for i in l for j in p if j[0]=='P']
[(1, 'Python'), (1, 'Perl'), (2, 'Python'), (2, 'Perl'), (3, 'Python'), (3, 'Perl')]

Print all primes less than n


>>> primes = [h for h in range(2, 100) if h not in [j for i in range(2,
10) for j in range(i*2, 100, i)]]
>>> print primes
. . . [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97]

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 5 using while loop


i=1
while i<7:
l=[]
j=1
while j<i+1:
l.append(str(j))
j+=1
st = ' '.join(l)
print st
i+=1

Ques 5 using for loop


for i in range(1,7):
l=[]
for j in range(1,i+1):
l.append(str(j))
st = ' '.join(l)
print st

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

S-ar putea să vă placă și