2. TODAY’S CLASS
• Introduction
• What is Python ?
• Why Python ?
• Features
• Basics of Python
• Syntax
• Import
• Input Functions
• Output Functions
PYTHON PROGRAMMING 2
3. WHAT IS PYTHON ?
PYTHON PROGRAMMING 3
Python is a widely used general-purpose, high-level programming
language.
Python is simple and powerful language
5. WHY PYTHON ?
PYTHON PROGRAMMING 5
Ease of Use and Powerful
Community Driven
Currently it’s in the top five programming languages in the
world according to TIOBE Index
Two times winner of Programming Language of the
Year(2007 and 2010) by TIOBE Index
6. FEATURES
PYTHON PROGRAMMING 6
Simple
Free and Open Source
Powerful
Object Oriented
Dynamic, strongly typed scripting language
Portable
Interpreted
8. CAN DO
Text Handling
System Administration
GUI programming
Web Applications
DatabaseApps
Scientific Applications
Games
NLP
ImageProcessing
IoT and lot more …..
PYTHON PROGRAMMING 8
17. IMPORT
When our program grows bigger, it is a good idea to break it into
different modules.
A module is a file containing Python definitions and statements.
Python modules have a filename and end with the extension .py
Definitions inside a module can be imported to another module
or the interactive interpreter in Python.
. We use the import keyword to do this.
PYTHON PROGRAMMING 17
18. IMPORT
>>> import math
>>> math.pi
3.141592653589793
>>> from math import pi
>>> pi
3.141592653589793
PYTHON PROGRAMMING 18
19. IMPORT
While importing a module, Python looks at several places defined in
sys.path.
It is a list of directory locations.
>>> import sys
>>> sys.path
['',
'C:Python33Libidlelib',
'C:Windowssystem32python33.zip',
'C:Python33DLLs',
'C:Python33lib',
'C:Python33',
'C:Python33libsite-packages']
PYTHON PROGRAMMING 19
20. SUM OF TWO NUMBERS
# Store input numbers
num1 = input('Enter first number: ') # input is built-in function
num2 = input('Enter second number: ') # input returns string
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
PYTHON PROGRAMMING 20
21. FOR PYTHON 2
from __future__ import print_function
Type this in first line to avoid errors if you use python 2.
PYTHON PROGRAMMING 21
22. OUTPUT
>>> print('This sentence is output to the screen')
This sentence is output to the screen
>>> a = 5
>>> print('The value of a is',a)
The value of a is 5
PYTHON PROGRAMMING 22
24. OUTPUT FORMATTING
Sometimes we would like to format our output to make it look
attractive.
This can be done by using the str.format() method.
This method is visible to any string object
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
PYTHON PROGRAMMING 24
25. OUTPUT FORMATTING
>>> print('I love {0} and {1}'.format('bread','butter'))
I love bread and butter
>>> print('I love {1} and {0}'.format('bread','butter'))
I love butter and bread
>>> print('Hello {name},
{greeting}'.format(greeting='Goodmorning',name='John'))
Hello John, Goodmorning
PYTHON PROGRAMMING 25
26. OUTPUT FORMATTING
We can even format strings like the old printf() style used in C
programming language.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
PYTHON PROGRAMMING 26
27. AREA OF TRIANGLE
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
PYTHON PROGRAMMING 27
29. INPUT
Here, we can see that the entered value 10 is a string, not a number.
To convert this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
PYTHON PROGRAMMING 29
30. INPUT EVAL
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
PYTHON PROGRAMMING 30
31. TEMPERATURE CONVERSION
# take input from the user
celsius = float(input('Enter degree Celsius: '))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit'
%(celsius,fahrenheit))
PYTHON PROGRAMMING 31
32. AVERAGE OF THREE NUMBERS
PYTHON PROGRAMMING 32
n1=float(input('1st num'))
n2=float(input('2nd num'))
n3=float(input('3rd num'))
avg=(n1+n2+n3)/3
print "Avarage os 3 numbers
{},{},{},={}n".format(n1,n2,n3,avg)
print ("Avarage os 3 numbers %0.2f %0.2f %0.2f%0.2f"
%(n1,n2,n3,avg))
43. SQUARE ROOT
# Python Program to calculate the square root
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
PYTHON PROGRAMMING 43
44. SQUARE ROOT - COMPLEX
# Find square root of real or complex numbers
# Import the complex math module
import cmath
num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num
,num_sqrt.real,num_sqrt.imag))
PYTHON PROGRAMMING 44
64. DECISION MAKING
Decision making is anticipation of conditions occurring while execution
of the program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE
or FALSE as outcome.
You need to determine which action to take and which statements to
execute if outcome is TRUE or FALSE otherwise.
assumes any non-zero and non-null values as TRUE, and if it is either
zero or null, then it is assumed as FALSE value.
PYTHON PROGRAMMING 64
67. IF
PYTHON PROGRAMMING 67
var1=100
if True:
print ("1 - Got a true“)
print (var1)
var2=0
if var2:
print ("2- Got a true“)
print (var2)
print ("good bye“)
68. IF ELSE : ODD OR EVEN
PYTHON PROGRAMMING 68
num=input("number")
if num%2==0:
print (num,'is Even‘)
else:
print (num,'is Odd‘)
69. IF ELIF
PYTHON PROGRAMMING 69
num=input("Enter a number")
if num>0:
print (num,'is Positive‘)
elif num==0:
print (num,'is Zero‘)
else:
print (num,'is Negative‘)
print ('Have a nice day‘)
70. NESTED IF
PYTHON PROGRAMMING 70
num=input("Enter a number")
if num>0:
print (num,'is Positive')
else:
if num==0:
print (num,'is Zero')
else:
print (num,'is Negative')
print ('Have a nice day')
71. LARGEST OF THREE NUMBERS
PYTHON PROGRAMMING 71
a=input('1st number')
b=input('2nd number')
c=input('3rd number')
if (a>b) and (a>c):
large=a
elif (b>a) and (b>c):
large=b
else:
large=c
print ('The largest number is ',large)
72. QUADRATIC EQUATION
PYTHON PROGRAMMING 72
import cmath
print 'Enter the Coeifficents'
a=input("a")
b=input("b")
c=input("c")
delta=(b**2)-4*a*c
if delta>0:
sq=delta**0.5
x=(-b+sq)/(2.0*a)
y=(-b-sq)/(2.0*a)
print 'roots are n {} n {}'.format(x,y)
#Cont to next slide
73. QUADRATIC EQUATION …
elif delta==0:
x=-b/(2.0*a)
y=x
print 'roots are Equal'
print 'roots aren {} n {}'.format(x,y)
else:
print 'imaginary'
#delta=-delta
sqi=cmath.sqrt(delta)
x=-b/(2.0*a)
#print x
print 'roots are n {0} + {1} j n {0} - {1} j
'.format(x,sqi.imag)
#print sqi.imag
PYTHON PROGRAMMING 73
74. LOOPS
For
While
While else
While Infinite Loop
While with condition at top, middle and bottom
PYTHON PROGRAMMING 74
77. NUMBERS DIV BY 7 and 2
PYTHON PROGRAMMING 77
num=[]
for i in range(100,1000):
if i%7==0:
num.append(i)
print (num)
print ('nnn')
num2=[]
for i in num:
if i%2==0:
num2.append(i)
print (num2)
79. PRIME NUMBER
PYTHON PROGRAMMING 79
num=input('Enter number')
f=0
for i in range(2,(num/2)+1):
if num%i==0:
#print i
f=1
break
if f:
print (num,'is Not a Prime number‘)
else:
print (num,'is Prime number‘)
88. LCM
PYTHON PROGRAMMING 88
n1=input('Enter 1st number ')
n2=input('Enter 2nd number ')
'''
if n1>n2:
lcm=n1
else:
lcm=n2
'''
lcm=max(n1,n2)
while True:
if (lcm%n1==0) and (lcm%n2==0):
break
lcm+=1
print ('LCM of {} and {} is {}'.format(n1,n2,lcm))
89. STUDENT GRADE
PYTHON PROGRAMMING 89
name=raw_input('Enter Student Name: ')
gpa=input('Enter GPA: ')
if gpa>=9:
print ('{} has got {} Grade'.format(name,'S'))
elif gpa>=8 and gpa<9 :
print ('{} has got {} Grade'.format(name,'A'))
elif gpa>=7 and gpa <8 :
print ('{} has got {} Grade'.format(name,'B'))
elif gpa>=6 and gpa<7:
print ('{} has got {} Grade'.format(name,'C'))
elif gpa>=5 and gpa<6:
print ('{} has got {} Grade'.format(name,'D'))
else:
print ('{} is Failed'.format(name))
90. DAYS WITH FUNCTION
PYTHON PROGRAMMING 90
days={
1:'Sun',
2:'Mon',
3:'Tue',
4:'Wed',
5:'Thu',
6:'Fri',
7:'Sat'
}
def day(d):
if days.get(d):
print ('Day is ',days.get(d))
else:
print ('Invalid Key ‘)
d=input('Enter the Day: ')
day(d)
91. SUM OF DIGITS
PYTHON PROGRAMMING 91
n=input('Enter the Number: ')
s=0
while n>0:
# a=n%10
# print a
s+=n%10
n/=10
print ('Sum of digit is ',s)
92. PALINDROME NUMBER
PYTHON PROGRAMMING 92
n=input('Enter the Number: ')
rev=0
n1=n
while n>0:
rev=rev*10+n%10
n/=10
print ('Reverse of Number is ',rev)
if rev==n1:
print ('Palindrome‘)
else:
print ('Not Palindrome‘)
101. DIVIDE AND CONQUER
every problem can be broken down into smaller/more manageablesub-
problems
most computer programs that solve real-world problems are
complex/large
the best way to develop and maintain a large program is to construct it
from smaller pieces or components
PYTHON PROGRAMMING 101
113. PYTHON FUNCTIONS (PARAMS vs
ARGS)
PYTHON PROGRAMMING 113
Function Parameters
Function Arguments
114. PYTHON FUNCTIONS
(ARGUMENTS)
You can call a function by using the following types of formal
arguments:
Required Arguments
Default Arguments
Keyword Arguments
Variable-Length Arguments
PYTHON PROGRAMMING 114
115. REQUIRED ARGUMENTS
PYTHON PROGRAMMING 115
Required/MandatoryArguments passed to a function in correct positionalorder
def sum(x,y):
return x+y
print sum(2, 3)
116. DEFAULT ARGUMENTS
PYTHON PROGRAMMING 116
assumes a default value if a value is not provided in the function call for
that argument.
def sum(x=1,y=1):
return x+y
print sum()
print sum(2, 3)
print sum(x=2)
print sum(x=2, y=3)
print sum(y=3, x=2)
117. KEYWORD ARGUMENTS
PYTHON PROGRAMMING 117
the caller identifies the arguments by the parameter name as keywords,
with/without regard to positional order
def sum(x,y):
return x+y
print sum(y=3, x=2)
118. VARIABLE ARGUMENTS
PYTHON PROGRAMMING 118
can handleno-argument, 1-argument, or many-argumentsfunction calls
def sum(*addends):
total=0
for i in addends:
total+=i
return total
print sum()
print sum(2)
print sum(2,3)
print sum(2,3,4)
119. TRY IT OUT
Program to find the sum of digits
PYTHON PROGRAMMING 119
120. FIBONACCI
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
PYTHON PROGRAMMING 120
122. MATRIX
PYTHON PROGRAMMING 122
# Read the Matrix
def readmat(r,c):
mat=[]
for i in range(r):
temp=[]
for j in range(c):
n=input('Enter the Number: ')
temp.append(n)
mat.append(temp)
return mat
# Calculate the sum
def matsum(r,c,a,b):
res=[]
for i in range(r):
temp=[]
for j in range(c):
sum=a[i][j]+b[i][j]
# print sum
temp.append(sum)
res.append(temp)
# print res
return res
123. MATRIX…
# Print Matrix
def printmat(r,c,a):
print 'The Matrix is n '
for i in range(r):
for j in range(c):
print a[i][j],"t",
print 'n '
print "nn"
# Find Transponse
def transpose(r,c,a):
trans=[]
for i in range(c):
tmp=[]
for j in range(r):
tmp.append(0)
trans.append(tmp)
for i in range(c):
for j in range(r):
trans[i][j]=a[j][i]
return trans
PYTHON PROGRAMMING 123
124. MATRIX…
# Main pgm
r=input('Enter no. of rows: ')
c=input('Enter no. of cols: ')
#print 'Enter 1 st matrix n'
a=readmat(r,c)
print 'Enter 2nd matrix '
b=readmat(r,c)
res=matsum(r,c,a,b)
print 'The First Matrix'
printmat(r,c,a)
print 'The Second Matrix'
printmat(r,c,b)
print 'The Sum of Matrix'
printmat(r,c,res)
print 'The trnsponse Matrix'
t=transpose(r,c,res)
printmat(c,r,t)
PYTHON PROGRAMMING 124
125. NAMESPACES
refers to the current snapshot of loaded
names/variables/identifiers/folders
functions must be loaded into the memory before you
could call them, especially when calling external
functions/libraries
PYTHON PROGRAMMING 125
140. SYNTAX ERRORS
Syntax errors, also known as parsing errors
perhaps the most common kind of complaint you get while you are still
learning Python:
>>> while True print 'Hello world'
File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
PYTHON PROGRAMMING 140
141. EXCEPTIONS
Even if a statementor expression is syntactically correct, it may cause
an error when an attemptis made to execute it.
Errors detected during execution are called exceptions and are not
unconditionally fatal: you will soon learn how to handle them in Python
programs.
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
PYTHON PROGRAMMING 141
146. CLASSES
A class is just like a blueprint of a house.
An object is the actual house built from that blueprint.
You could then create numerous houses/objects from a single blueprint.
PYTHON PROGRAMMING 146