Python Workshop-Day1
Python Workshop-Day1
21/06/2018
Workshop on “Introduction to
Python”
Department Of
Computer Science
Engineering
SKFGI, Mankundu
1.History
Python was developed by Guido van Rossum in the early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands. C,
C++, ABC, Modula-3, Algol-68, SmallTalk, Unix shell and other programming
and scripting languages influenced the development of Python. Python is
copyrighted. Python source code is now available under the GNU General Public
License (GPL).
2.Features
Simple to Understand− Python offers has few keywords, simple
structure, and a clearly defined syntax. This allows the student to pick up
the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the
eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable
and cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
Databases − Python provides interfaces to all major commercial
databases.
GUI Programming − Python supports GUI applications that can be
created and ported to many system calls, libraries and windows systems,
such as Windows MFC, Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below-
It supports functional and structured programming methods as well as
OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
4.Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module
or other object. An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores and digits (0 to 9).
5.Reserved Words
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only. Following table shows the list of
keywords available in Python-
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
7.Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow
the use of the line continuation character (\) to denote that the line should
continue.
Example:
total = x + \
y+\
z
8.Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines.
Example:
w = 'Hi'
s= "Hello Everyone Present Here"
p= """All the students who are interested in writing programs must attend this
class of Python programming. This will increase your confidence and embed new
technology in yourselves."""
9.Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
Multi line comments is done by triple single quotes.
Example:
a=10
'''This is a python program
for the beginners
'''
#hello student
print(a)
Output:
10
11.Python Variables
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or characters
in these variables.
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
Example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables.
Example:
x,y,z=10,12.98,”Sourav”
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the
variable c.
14.1Numbers
Number data types store numeric values. Number objects are created when you
assign a value to them.
Example:
x = 100
y = 10.67
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and
hexadecimal)
float (floating point real values)
complex (complex numbers)
Output:
Address of a in integer form is: 1787159456
Address of a in hexadecimal form is: 0x6a85e3a0
14.3Strings
Strings in Python are identified as a contiguous set of characters represented in
the quotation marks. Python allows for either pairs of single or double quotes.
Example:
s="Hello Everyone"
print("String s is:")
print(s)
Output:
String s is:
Hello Everyone
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
Example:
s1="India is"
s2="My Country"
print("Repeated String s1 is:")
print(s1*2)
print("Concatenated String is:")
print(s1+s2)
Output:
Repeated String s1 is:
India isIndia is
Concatenated String is:
India isMy Country
14.4 Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some
extent, lists are similar to arrays in C. One difference between them is that all
the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to
end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*)
is the repetition operator.
Example:
1.
list_new=[] #Empty list. list_new is the name of the user defined list
print(list_new)
Output:
[]
2.
list_new=[100,23,45] # List with same types of elements
print(list_new)
Output:
[100, 23, 45]
3.
list_new=[2,5.37,'Python'] # List with different types of elements
print(list_new)
Output:
[2, 5.37, 'Python']
4.
list_new=[200,15.37,'Hello']
print("list_new[0] is =",list_new[0]) # Printing element at index 0 of the list
print("list_new[1] is =",list_new[1]) # Printing element at index 1 of the list
print("list_new[2] is =",list_new[2]) # Printing element at index 2 of the list
Output:
list_new[0] is = 200
list_new[1] is = 15.37
list_new[2] is = Hello
5.
list_new=[200,15.37,'Hello',8000]
print(list_new[0:3]) # Print elements starting from index 0 to 2
print(list_new[1:3]) # Print elements starting from index 1 to 2
print(list_new[1:]) # Print elements starting from index 1 to last index
Output:
[200, 15.37, 'Hello']
[15.37, 'Hello']
[15.37, 'Hello', 8000]
6.
list_new=[200,15.37,'Hello',8000]
print(list_new[-1]) # Print the 1th element from right; there is no concept of
0th element from right
Output:
8000
7.
list_new=[200,15.37,'Hello',8000]
print(list_new[-3]) # Print the 3th element from right
Output:
15.37
Matrices
In python, a matrix can be represented as a list of lists (a list, where each
element is in turn a list).
Example:
1.
mat=[[1,2,3,4],[100,200,300,400],[1000,2000,3000,4000]] # mat is a 2X4
matrix
print("Matrix mat is:")
print(mat)
Output:
Matrix mat is:
[[1, 2, 3, 4], [100, 200, 300, 400], [1000, 2000, 3000, 4000]]
2.
m=[[12,34.5], # matrix assignment in table form
[23,87.9],
[34,87.5]]
print("matrix m is:")
print(m)
Output:
matrix m is:
[[12, 34.5], [23, 87.9], [34, 87.5]]
3.
student=[['Shyamal',1,85.0],['Ashok',2,93.5]] # student matrix formation with
name ,roll and marks
print("Matrix student is:")
print(student)
Output:
Matrix student is:
[['Shyamal', 1, 85.0], ['Ashok', 2, 93.5]]
4.
m=[[1,2,3],
[10,20,30],
[100,200,300]]
print(m[0]) #print the 0th row of the matrix
print(m[2]) #print the 2th row of the matrix
Output:
[1,2,3]
[100,200,300]
5.
m=[[1,2,3],
[10,20,30],
[100,200,300]]
print(m[0][0]) # print matrix element of 0th row and 0th column
print(m[0][2]) # print matrix element of 0th row and 2th column
print(m[2][1]) # print matrix element of 2th row and 1th column
Output:
1
3
200
6.
m1=[[1,2,3],
[10,20,30],
[100,200,300],
[1000,2000,3000]]
print(m1[-1]) #print 1 th row from bottom, there is no concept of 0th row
from bottom
print(m1[-3]) #print 3 th row from bottom
Output:
[1000, 2000, 3000]
[10, 20, 30]
7.
m2=[[1,2,3,4],
[10,20,30,40],
[100,200,300,400],
[1000,2000,3000,4000]]
print(m2[0][-2]) #print element at 0 th row from top and 2th column from right
of the row
print(m2[2][-3]) #print element at 2 th row from top and 3th column from right
of the row
Output:
3
200
8.
m1=[[1,2,3,4],
[10,20,30,40],
[100,200,300,400],
[1000,2000,3000,4000]]
print(m1[-3][-2]) #print element at 3th row from bottom and 2th column from
right of the row
Output:
30
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists
of a number of values separated by commas. Unlike lists, however, tuples are
enclosed within parentheses.
The main differences between lists and tuples are:
Lists are enclosed in third brackets i.e [ ] but tuples are enclosed in
parentheses i.e ( )
List elements and size can be changed but tuples cannot be updated.
Tuples can be thought of as read-only lists.
Example:
1.
tuple1=(100,200)
print("Tuple is:")
print(tuple1)
Output:
Tuple is:
(100, 200)
2.
t1=('Sachin',1,93.5)
t2=('Sourav',2,81.0)
print("Tuples are:")
print(t1)
print(t2)
Output:
Tuples are:
('Sachin', 1, 93.5)
('Sourav', 2, 81.0)
3.
t1=(100,200.9,300,'Narayan')
print("t1[0] is=",t1[0]) #print 0th element of tuple t1
print("t1[1] is=",t1[1]) #print 1th element of tuple t1
print("t1[2] is=",t1[2]) #print 2th element of tuple t1
print("t1[3] is=",t1[3]) #print 3th element of tuple t1
Output:
t1[0] is= 100
t1[1] is= 200.9
t1[2] is= 300
t1[3] is= Narayan
4.
t1=(100,200.9,300,'Narayan')
print("t1[0] is=",t1[0])
t1[1]=452.8 #updating tuple element is not possible
Output:
Error: 'tuple' object does not support item assignment
5.
t1=('Harish','Ramen')
t2=(100,200)
t3=(3.45,7.98)
t4=t1+t2+t3 #Concatenating more than one tuples
print("Resultant tuple is:")
print(t4)
Output:
Resultant tuple is:
('Harish', 'Ramen', 100, 200, 3.45, 7.98)
6.
t1=('Hello')
print(4*t1) #print the content of tuple t1 4 times
Output:
HelloHelloHelloHello
7.
t1=('Hello','World','Everyone')
print("Length of tuple t1 is:",len(t1)) #Print the length of tuple t1
print("Length of 2th element of tuple t2 is:",len(t1[2])) #Print the length of 2th
element of t1
Output:
Length of tuple t1 is: 3
Length of 2th element of tuple t2 is: 8
8.
t1=('Hello','everyone','I','am','here')
print('am' in t1) #Check the membership of 'am' in tuple t1
Output:
True
14.5 Dictionaries
Python's dictionaries are kind of hash table type. They work like associative
arrays or hashes found in Perl and consist of key-value pairs. A dictionary key
can be almost any Python type, but are usually numbers or strings. Values, on
the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces i.e { } and values can be assigned and
accessed using square braces i.e []
Example:
1.
d={} #Empy dictionary
print(d)
Output:
{}
2.
d={'name':'amal','roll':1,'marks':76.5}
print("Keys of dictionary d are:")
print(d.keys())
Output:
Keys of dictionary d are:
dict_keys(['name', 'roll', 'marks'])
3.
d={'name':'amal','roll':1,'marks':76.5}
print("Values of dictionary d are:")
print(d.values())
Output:
Values of dictionary d are:
dict_values(['amal', 1, 76.5])
4.
d={'name':'amal','roll':1,'marks':76.5}
print("name is:",d['name']) #Accessing dictionary value by using the key 'name'
print("roll is:",d['roll']) #Accessing dictionary value by using the key 'roll'
print("marks is:",d['marks']) #Accessing dictionary value by using the key
'marks'
Output:
name is: amal
roll is: 1
marks is: 76.5
5.
player={} #Empty dictionary
player['name']="sachin" #Adding key and values to the dictionary
player['match']=10
print("name is:", player['name'] , "and match played are:" , player['match'])
Output:
name is: sachin and match played are: 10
6.
player={'name':'sachin','match':10}
player['runs']=500 #Adding new key and value to filled up dictionary
print("name is:", player['name'])
print("match played are:" , player['match'])
print("runs scored are:",player['runs'])
Output:
name is: sachin
match played are: 10
runs scored are: 500
7.
player={'name':'sachin','match':10,'runs':500}
player['match']=12 #Updating value related to key 'match'
player['runs']=650 #Updating value related to key 'runs'
print("name is:", player['name'])
print("Updated match played are:" , player['match'])
print("Updated runs scored are:",player['runs'])
Output:
name is: sachin
Updated match played are: 12
Updated runs scored are: 650
15Operator
Output:
Result of floor division is = 7.0
15.1.6. Modulus (%)
This operator divides left hand operand by right hand operand and returns
remainder.
Example:
a=14
b=3
c=a%b
print("Result of modulo operation is =",c)
Output:
Result of modulo operation is = 2
15.1.7. Exponent (**)
This operator performs exponential (power) calculation on operands.
Example:
a=3
b=2
c=a**b
print("Result of exponential operation is =",c)
Output:
Result of exponential operation is = 9
15.2.Comparison Operators
These operators compare the values on either sides of them and decide the
relation among them. They are also called Relational operators.
15.2.1. Equality Checking (==)
If the values of two operands are equal, then the condition becomes true.
Example:
a=3
b=3
if(a==b):
print("same")
else:
print("not same")
Output:
Same
15.2.2. Not equals to Checking (!=)
Example:
a=3
b=5
if(a!=b):
print(" not same")
else:
print("same")
Output:
not same
If the value of left operand is greater than the value of right operand, then
condition becomes true.
Example:
a=32
b=5
if(a>b):
print("greater")
else:
print("smaller")
Output:
greater
15.7.Identity Operators
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below:
is
Evaluates to true if the variables on either side of the operator point to the same
object and false otherwise.
Example:
1.
a=10
b=10
if( a is b ):
print("same object")
else:
print("different object")
Output:
same object
2.
a=10
b=20
if( a is b ):
print("same object")
else:
print("different object")
Output:
different object
is not
Evaluates to false if the variables on either side of the operator point to the same object and true
otherwise.
Example:
1.
a=10
b=20
if( a is not b ):
print("different object")
else:
print("same object")
Output:
different object
2.
a=10
b=10
if( a is not b ):
print("different object")
else:
print("same object")
Output:
same object
Operator Description
17.Conditional Statements
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.
Python programming language 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 language provides following types of decision making
statements:
if statement
The if statement contains a logical expression using which data is compared and
a decision is made based on the result of the comparison.
Example:
1.
a=2 #Non zero value is true
b=0 #Zero value is false
if(a):
print("a")
if(b):
print("b")
Output:
a
2.
print("Enter the character")
c1=input()
a=ord(c1)#conver the chracter into its ASCII value
if(a>=65 and a<=90):
print("Character",c1,"is upper case")
if(a>=97 and a<=122):
print("Character",c1,"is lower case")
Output:
Enter the character
B
Character B is upper case
if-else statement
An else statement can be combined with an if statement. An else statement
contains the block of code that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only
one else statement following if.
Example:
1.
a=2
b=0
if(a):
print("true")
else:
print("false")
if(b):
print("true")
else:
print("false")
Output:
true
false
2.
print("Enter the number")
n=(int)(input())
if(n%2==0): #Checking whether the number is even or not
print("Entered number",n,"is even")
else:
print("Entered number",n,"is odd")
Output:
Enter the number
12
Entered number 12 is even
3.
print("Enter the number")
n=(int)(input())
if(n>0): #Checking whether the number is positive or negative
print("Entered number",n,"is positive")
else:
print("Entered number",n,"is negative")
Output:
Enter the number
-8
Entered number -8 is negative
4.
print("Enter the number")
n=(int)(input())
if(n==1):
print("Entered number",n,"is power of 2")
exit(0)
a=n
b=n-1
c=a&b
if(c==0):
print("Entered number",n,"is power of 2")
else:
print("Entered number",n,"is not power of 2")
Output:
Enter the number
32
Entered number 32 is power of 2
5.
print("Enter two numbers")
n1=(int)(input())
n2=(int)(input())
if(n1>n2):
print(n1,"is greater than",n2)
else:
print(n2,"is greater than",n1)
Output:
Enter two numbers
12
10
12 is greater than 10
Nested if-else
There may be a situation when you want to check for another condition after a
condition resolves to true. In such a situation, you can use the nested if-else
construct.
Example:
1.
print("Enter three numbers")
n1=(int)(input())
n2=(int)(input())
n3=(int)(input())
if(n1>n2):
if(n1>n3):
print(n1,"is greatest")
else:
print(n3,"is greatest")
else:
if(n2>n3):
print(n2,"is greatest")
else:
print(n3,"is greatest")
Output:
Enter three numbers
14
24
12
24 is greatest
2.
print("Enter the year")
y=(int)(input())
if(y%100==0):
if(y%400==0):
print(y,"is a leap year")
else:
print(y,"is not a leap year")
else:
if(y%4==0):
print(y,"is a leap year")
else:
print(y,"is not a leap year")
Output:
Enter the year
1996
1996 is a leap year
3.
import math
print("Enter three coefficients a,b,c of quadratic equation")
a=(int)(input())
b=(int)(input())
c=(int)(input())
d=pow(b,2)-4*a*c
if(d>0):
s=math.sqrt(d)
x1=(-b)/(2*a)+s/(2*a)
x2=(-b)/(2*a)-s/(2*a)
print(" Real roots are:x1=",x1,"and x2=",x2)
if(d==0):
x1=(-b)/(2*a)
print(" Real roots are:x=",x1)
else:
x=(-b)/(2*a)
s=math.sqrt(d*(-1))
y=s/(2*a)
print("Imaginary roots are:x1=",x," + i",y)
print("Imaginary roots are:x2=",x," - i",y)
Output:
Enter three coefficients a,b,c of quadratic equation
2
2
3
Imaginary roots are:x1= -0.5 + i 1.118033988749895
Imaginary roots are:x2= -0.5 - i 1.118033988749895
Swap the value of two variable :
1)A=5
B=6
A,B=B,A
print(A,B)
2) A=5
B=6
A=A+B
B=A-B
A=A-B
print(A,B)
3) A=5
B=6
A=A*B
B=A/B
A=A/B
print(A,B)
print(min)
Number Conversion:
1.dec = int(input("Enter a decimal number: "))
2.print(bin(dec),"in binary.")
3.print(oct(dec),"in octal.")
4.print(hex(dec),"in hexadecimal." )
5.print("The ASCII value of '" + c + "' is",ord(c))
6.print(float(dec),"in float." )
7.print(str(5),"in String" )
8.print(chr(65),"in character " )
9.
10.
11.