Introduction To Python Programming DB
Introduction To Python Programming DB
Introduction To Python Programming DB
Python Program
ming
Contents
Introduction
Environmental setup
Basic Syntax
Data Types
Operators
Decision Making
Loops
Numbers
Strings
File I/O
numPy
What is Python?
Python is a widely used high-level, general-purpose, interpret
ed, dynamic programming language
Available under the GNU General Public License (GPL)
Python supports multiple programming paradigms, including
object-oriented, imperative and functional programming or proce
dural styles.
It features a dynamic type system and automatic memory mana
gement and has a large and comprehensive standard library.
Huge community pypi (Python Package Index) containing 92K +
packages
Python Features
Easy-to-learn
Python for Science and Engineering
Python by itself is not that useful for S&E
Many add-ons and extensions have been created to allow python to work for S&E’s,
web development, big data processing, and other software stacks”.
1. Immediate Mode:
>>>
2. Script Mode:
IDE is a piece of software that provides useful features like code hintin
g, syntax highlighting and checking, file explorers etc. to the programm
er for application development
IDLE is the IDE installed along with the Python programming language
and is available from the official website. Others are
Jupyter notebook
Spyder
PyCharm
PyScripter
PythonWin
>>> 5+7
Python Keywords
Python Identifiers
Identifier is a name used to identify a variable, function, class,
module or other object
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Comments and help
Python Comments:
Comments start with a #, and Python will render the rest of the line as a
comment
#This is a comment.
print("Hello, World!")
Docstrings
"""This is a
multiline docstring."""
print(“a={:f}".format(123.4567898)) #a=123.456790
Numbers
String
List
Tuple
Dictionary
Standard Data Types
Numbers
int
All integers in Python3 are represented as long
integers. Hence there is no separate number type as
long.
float
Complex
A complex number consists of an ordered pair of real
floating-point numbers denoted by x + yj, where x and
y are the real numbers and j is the imaginary unit.
Standard Data Types
Numbers
Examples
Strings
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.
Subsets of strings can be taken using the slice operator ([ ]
and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator.
Trying to access elements beyond the length of the string
results in an error.
Standard Data Types
Strings
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting at index 2 to 4
# first index is inclusive while end is exclusive
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
print (str[-1])
print (str[-3:-1])
print (str[-12:])
print(id(b)) print(id(a))
140675605442000 6406872
b.append(3) a = a + 1
print(b) print(id(a))
print(id(b))
140675605442000 # SAME
Standard Data Types
Strings
Python strings cannot be changed — they are
immutable.
The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.
Tuples
A tuple is another sequence data type that is similar to the list.
The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.
The set objects may also created by applying the set function to
lists strings and tuples.
A dictionary key can be almost any Python type, but are usually
numbers or strings.
['Vishal',75,80,75,85,100],
['Priyank',80,80,80,90,95]]
print(a[0][1]) # 80
print(a[1][2]) # 80
Basic Operators
Types of Operator
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Basic Operators
Arithmetic Operators
Assume variable a holds 10 and variable b holds 21, then
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 31
- Subtraction Subtracts right hand operand from left hand a – b = -11
operand.
* Multiplication Multiplies values on either side of the operator a * b = 210
> If the value of left operand is greater than the (a > b) is not true.
value of right operand, then condition becomes
true.
< If the value of left operand is less than the value (a < b) is true.
of right operand, then condition becomes true.
>= If the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, then
condition becomes true.
<= If the value of left operand is less than or equal (a <= b) is true.
to the value of right operand, then condition
becomes true.
Basic Operators
Assignment Operators
Assume variable a holds 10 and variable b holds 20, then
Operator Description Example
= Assigns values from right side operands to left side c = a + b assigns value of
operand a + b into c
+= It adds right operand to the left operand and assign c += a is equivalent to c =
the result to left operand c+a
-= It subtracts right operand from the left operand and c -= a is equivalent to c =
assign the result to left operand c-a
*= It multiplies right operand with the left operand and c *= a is equivalent to c =
assign the result to left operand c*a
/= It divides left operand with the right operand and c /= a is equivalent to c =
assign the result to left operand c/a
%= It takes modulus using two operands and assign the c %= a is equivalent to c
result to left operand =c%a
**= Performs exponential (power) calculation on c **= a is equivalent to c
operators and assign value to the left operand = c ** a
& Operator copies a bit to the result if it (a & b) (means 0000 1100)
exists in both operands
| It copies a bit if it exists in either (a | b) = 61 (means 0011 1101)
operand.
^ It copies the bit if it is set in one (a ^ b) = 49 (means 0011 0001)
operand but not both.
~ It is unary and has the effect of (~a ) = -61 (means 1100 0011 in
'flipping' bits. 2's complement form due to a
signed binary number.
<< The left operands value is moved left a << = 2 (means 1111 0000)
by the number of bits specified by the
right operand.
>> The left operands value is moved right a >> = 2 (means 0000 1111)
by the number of bits specified by the
right operand.
Basic Operators
Logical Operators
Assume a = True (Case Sensitive) and b = False (Case
Sensitive), then
not in Evaluates to true if it does not finds a variable in x not in y, here “not in” results in a
the specified sequence and false otherwise. 1 if x is not a member of sequence
y.
Eg.
list1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
Basic Operators
Identity Operators
Identity operators compare the memory locations of two
objects.
There are two Identity operators explained below:
Operator Description Example
is Evaluates to true if the variables on either x is y, here ”is” results in 1
side of the operator point to the same object if id(x) equals id(y).
and false otherwise.
is not Evaluates to false if the variables on either x is not y, here ”is
side of the operator point to the same object not” results in 1 if id(x) is
and true otherwise. not equal to id(y).
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
Output:
1 - Got a true expression value
100
Good bye!
Decision Making
if else
if expression:
statement(s)
else:
statement(s)
amount=int(input(“Enter amount: “))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Decision Making
Nested if
num=int(input("enter number"))
if num%2==0:
if num%3==0:
print("Divisible by 3 and 2")
else:
print("divisible by 2 not divisible by 3")
else:
if num%3==0:
print("divisible by 3 not divisible by 2")
else:
print("not Divisible by 2 not divisible by 3")
Loops
While Loop
while expression:
statement(s)
count = 0
while count < 9:
print ('The count is:', count)
count = count + 1
print("Good bye!")
Loops
While Loop
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Loops
for loop
Output:
0
1
2
3
4
Loops
for Loop
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Loops
for Loop
Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
for Loop
Iterating by Sequence Index
Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
Break Statement
for letter in 'Python':
if letter == 'h':
break
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Breaked Letter : h
Loops
Continue Statement
for letter in 'Python':
if letter == 'h':
continue
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Loops
Using else Statement with Loops
Python supports to have an else statement associated
Output:
the list contains an even number
Loops
Using else Statement with Loops
num=0
while num < 10:
num=num+1
if num%2==0:
print('In side the loop', num)
break
else:
print ('Outside the loop in else')
Output:
In side the loop 2
Numbers - Revisited
import math
num=-6.1
print(math.ceil(num))
Numbers - Revisited
Numbers
Mathematical Functions
Function Returns ( description )
max(x1, x2,...) The largest of its arguments: the value closest to positive
infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative
infinity
pow(x, y) The value of x**y.
round(x ,n) x rounded to n digits from the decimal point.
math.sqrt(x) The square root of x for x > 0
Numbers - Revisited
Numbers
Random Number Functions
Function Description
random.choice(seq) A random item from a list, tuple, or string.
random.random() A random float r, such that 0 is less than or equal to r
and r is less than 1
random.seed([x]) Sets the integer starting value used in generating
random numbers. Call this function before calling any
other random module function. Returns None.
random.shuffle(lst) Randomizes the items of a list in place. Returns None.
random.uniform(x, y) A random float r, such that r is less than or equal to x
and r is less than y
random.randint(x, y) Return random integer in range [x, y], including both
end points
random.sample(population, k) Chooses k unique random elements from a population
sequence or set.
Numbers - Revisited
Random Number Functions
import random
myList = [2, 109, False, 10, "Vijay", 482, "Vishal"]
print(random.randint(0, 100))
print(random.random() * 100)
print(random.choice(myList))
print(random.randrange(0, 101, 5))
print(random.uniform(0, 100))
print(myList)
random.shuffle(myList)
print(myList)
Output
39
45.26060117036571
Vijay
40
84.56477617706464
[2, 109, False, 10, 'Vijay', 482, 'Vishal']
[482, 2, 'Vishal', 'Vijay', 109, 10, False]
Strings - Revisited
Strings (Assume str to be a string variable)
Sr. Methods with Description
No.
1 str.capitalize()
Capitalizes first letter of string.
2 str.isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and
false otherwise.
3 str.isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
4 str.isdigit()
Returns true if string has at least 1 character and contains only digits and false otherwise.
5 str.islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
6 str.isspace()
Returns true if string contains only whitespace characters and false otherwise.
Strings - Revisited
Strings
Sr. Methods with Description
No.
7 str.isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
8 len(str)
Returns the length of the string
9 str.lower()
Converts all uppercase letters in string to lowercase.
10 max(str)
Returns the max alphabetical character from the string str.
11 min(str)
Returns the min alphabetical character from the string str.
12 str.upper()
Converts lowercase letters in string to uppercase.
Lists - Revisited
Delete List Elements
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
Output:
1 len(list)
Gives the total length of the list.
2 max(list)
Returns item from the list with max value.
3 min(list)
Returns item from the list with min value.
4 list.copy()
Returns a copy of the list
Lists - Revisited
List Methods
SN Methods with Description
1 list.append(obj)
Appends object obj to list. Returns None.
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.index(obj)
Returns the lowest index in list that obj appears
4 list.insert(index, obj)
Inserts object obj into list at offset index
5 list.pop()
Removes and returns last object or obj from list
6 list.remove(obj)
Removes first instance of obj from list
7 list.reverse()
Reverses objects of list in place
8 list.sort()
Sorts objects of list in place
Python Functions
Defining a Function
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
print (str)
return
Python Functions
Pass by reference vs value
Output:
Values inside the function before change: [2, 109, False, 10, 'Vijay', 482, 'Vishal']
Values inside the function after change: [2, 109, 50, 10, 'Vijay', 482, 'Vishal']
Python Functions
Pass by reference vs value
#Function definition is here
def changeme( mylist ):
'''This changes a passed list into this function'''
mylist = [1,2,3,4] #Assign new reference in mylist
print ("Values inside the function: ", mylist)
return
Output:
Output:
Output:
Inside the function local total : 30
Outside the function global total : 30
Output:
Python is Great
100
Miscellaneous
del var_name
del var1, var2
type(5)
type(5.6)
type(5+2j)
type(“hello”)
type([‘h’,’e’])
type((‘h’,’e’))
Multiple Assignments
a=b=c=1
a, b, c = 1, 2, "john"
Python Input / Output
Printing to screen using print statement
print ("Python is great”)
Reading keyboard input
raw_input() - discontinued in version 3
The raw_input([prompt]) function reads one line from standard input
and returns it as a string
str = raw_input("Enter your input: ")
print("Received input is : ", str)
input()
The input([prompt]) function is equivalent to raw_input, except that it
assumes the input is a valid Python expression and returns the
evaluated result to you.
str = input("Enter your input: ");
print "Received input is : ", str
Output:
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
File Input / Output
Open File
file_name − The file_name argument is a string value that contains the name
access_mode − The access_mode determines the mode in which the file has
to be opened, i.e., read, write, append, etc. This is optional parameter and the
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode
rb Opens a file for reading only in binary format
r+ Opens a file for both reading and writing
rb+ Opens a file for both reading and writing in binary format
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing
ab+ Opens a file for both appending and reading in binary format
File Input / Output
Once a file is opened with open function, many atrributes of the file
can be accessed with file_object
Attribute Description
Output
Read String is : Python is
File Position
tell() Method
The tell() method tells you the current position within
the file
The seek(offset[, from]) method changes the current
file position. The offset argument indicates the
number of bytes to be moved. The from argument
specifies the reference position from where the
bytes are to be moved.
from: 0 - means beginning of file
from: 1 - current position as reference point
from: 2 - end of the file as reference point
File Position
# Open a file
fo = open("test.txt", "r+")
str = fo.read(10);
print("Read String is : ", str)
Output
Read String is : Python is
Current file position : 10
Again read String is : Python is
Python Modules
Module allows to logically organize the Python code
Eg. Create a hello.py file with following contents
def say_hello( par ):
print "Hello : ", par
return
import statement
Output
# Import module hello
import hello
Install
C:\\Python34\scripts>pip3.4 list
C:\\Python34\scripts>pip3.4 install numpy
Already installed with Anaconda. If not, use conda install numpy
import numpy as np
Numpy
NumPy has an N-dimensional array type called ndarray
Every item in an ndarray takes the same size of block in the memory.
Each element in ndarray is an object of data-type object (called dtyp
e).
To create an ndarray
numpy.array(object, dtype = None, copy = True, order = None, subok = Fals
e, ndmin = 0)
Numpy
To create an array
import numpy as np
a = np.array([1,2,3])
print a
Output
[1 2 3]
To create multi-dimensional array
a = np.array([[1,2,3],[4,5,6]])
print a
Output
[[1 2 3]
[4 5 6]]
dt = np.dtype([('name','S20'),('no',np.int16)])
a = np.array([('VU',4),('ViyU',20),('PU',3)],dtype = dt)
print (a)
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print(a)
print(a[])
Numpy
np.array
Two dimensional array
Numpy
np.array
Two dimensional array: reshape() & copy()
Strange - Shape is a settable property and it is a tuple and you can concatenate the dimension.
Numpy
np.array
Two dimensional array: reshape(), transpose() &
flatten()
Numpy
np.array
Two dimensional array: concatenate()
Numpy
np.array
Two dimensional array: concatenate()
Numpy
np.array
Other ways to create array
Numpy
np.array
Array mathematics
Numpy
np.array
Array mathematics
Numpy
np.array
Array mathematics - Broadcasting
Numpy
np.array
Array mathematics - Broadcasting
Numpy
np.array
Array mathematics
Numpy
np.array
Array mathematics
Numpy
np.array
Array iteration
Numpy
np.array
Basic array operations
np.mean(a)
np.var(a)
np.std(a)
np.min(a)
np.max(a)
np.argmin(a)
np.argmax(a)
np.sort(a)
Numpy
np.array
Basic array operations
a=np.array([[1,2],[3,4]])
np.mean(a) #2.5
np.mean(a,axis=0) #array([ 2., 3.]) #column wise
np.mean(a,axis=1) #array([ 1.5, 3.5]) #row wise
b=np.array([[11,5,14],[2,5,1]])
np.sort(b) # array([[ 5, 11, 14],
• [ 1, 2, 5]])
np.sort(b,axis=1) # array([[ 5, 11, 14],
• [ 1, 2, 5]])
np.sort(b,axis=0) # array([[ 2, 5, 1],
• [ 11, 5, 14]])
3-D Array
a=np.array([ [[11,5,14],[2,5,1]], [[11,5,14],[2,5,1]] ])
Numpy
np.array
Comparison Operators & Value Testing
Numpy
np.array
Comparison Operators & Value Testing
Numpy
np.array
Where Function
Numpy
np.array
Checking for NaN and Inf
Numpy
np.array
Array Item Selection & Manipulation
Numpy
np.array
Vector and Matrix Mathematics
Numpy
np.array
Vector and Matrix Mathematics
Numpy
np.array
Statistics
Numpy
np.array
Random Numbers
Numpy
np.array
Random Numbers
Python References
〉 Enthought.com Location of Enthought Canopy and Enthought Python Distribution
〉 Docs.python.org <- A great resource for general Python
〉 Docs.enthought.com <- Release notes, installation instructions for Enthought
〉 Pyvideo.org <- a repository of links to videos on Python from all the python conferenc
es
〉 Training.enthought.com <- get a Enthought account from Bob get free TRAINING!
〉 scipy-lectures.org <- Tutorials on the scientific Python ecosystem
〉 awesome-python.com <- A curated list of awesome Python frameworks, libraries, soft
ware and resources
〉 talkpython.fm <- talk python to me podcast
〉 pythonbytes.fm <- very short and to the point weekly updates about python