Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Python Programming DB

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 132
At a glance
Powered by AI
Python is a widely used programming language with features like being easy to learn and read. It supports multiple programming paradigms and has a large standard library.

Python is easy-to-learn, easy-to-read, object-oriented, and has automatic memory management. It can be used for web development, data science, and more.

Popular Python IDEs include IDLE, Jupyter Notebook, Spyder, PyCharm, and Anaconda Navigator.

Introduction to

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”.

iPython is now called Jupyter


Getting Python

 Most up-to-date version is available on the official website of Python


https://www.python.org/

 It is available for a wide variety of platforms.


Getting Python

Various ways to start python:

1. Immediate Mode:

 Enter python command to get following prompt

 >>>

 The python interpreter is ready for input

 Eg. type 4+7 and press enter to get the output

 To exit this mode type exit() or quit() and press enter.


Getting Python
Various ways to start python:

2. Script Mode:

 Used to execute Python program written in a file called a script

 Python scripts have the extension .py

 To execute this file in script mode we simply write python helloWorld.py


at the command prompt
Getting Python
Various ways to start python:

3. Integrated Development Environment (IDE):

 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

 Anaconda is one of the most popular Python data science platform


The Anaconda Navigator
Jupyter
Spyder
PyCharm
Installing Packages
 You can install packages from the Anaconda ter
minal using the command:
 conda install <name of package>

 For example, Seaborn is a package for Statistica


l Data Visualization.
 conda install seaborn

 piserial is a package for communication with seri


al devices.
 conda install piserial
Running Python

 Type following code in any of IDE/python prompt

 >>> print("Hello world!")

 Few more examples

 >>> 5+7
Python Keywords
Python Identifiers
 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)

 Python does not allow punctuation characters such as @, $,


and % within identifiers

 Identifiers are case sensitive


Python Indentation
 In most other programming languages the indentation in code
is for readability only, in Python the indentation is very
important

 Python uses indentation to indicate a block of code

 Following code creates a block under if statement

if 5 > 2:
print("Five is greater than two!")

 While this code generates error

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."""

 Help in Python: help(topic)


 If no argument is given, the interactive help system starts on the
interpreter console. If the argument is a string, then the string is looked
up as the name of a module, function, class, method, keyword, or
documentation topic, and a help page is printed on the console.
Printing in Python
 Syntax: print(value, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)
 print("Hello World") #Hello World
 a=5
 b=2
 print(a) #5
 print(a, b) #52
 print(a) #5
 print(b) #2
 print('V','S','U', sep=”, \t”, end=”X”) #V,S, UX
Printing in Python
 print("a={0}".format(a)) #a=5

 print("a={0} and b={1}".format(a, b)) #a=5 and b=2

 print("a={1} and b={0}".format(a, b)) #a=2 and b=5

 print(“a={} and b={}”.format(a, b)) #a=5 and b=2 #auto field


numbering

 print("bin={0:b}, oct={0:o}, hex={0:x}".format(12)) #bin=1100, oct=14,


hex=c

 print("bin={0:b}, oct={1:o}, hex={1:x}".format(12,10)) #bin=1100,


oct=12, hex=a

 print("bin={:b}, oct={:o}, hex={:X}".format(12,10,10)) #bin=1100,


oct=12, hex=A
Printing – Padding & Alignment

 print("a={0:d} and b={1:d}".format(a, b)) #a=5 and b=2

 print("a={0:3d} and b={1:5d}".format(a, b)) #a= 5 and b= 2

 print("a={0:>3d} and b={1:>5d}".format(a, b)) #a= 5 and b= 2

 print("a={0:<3d} and b={1:<5d}".format(a, b)) #a=5 and b=2

 print("a={:<{}d} and b={:<{}d}".format(a,3,b,5)) #???

 print("a={0:03d} and b={1:05d}".format(a, b)) #a=005 and b=00002

 print("a={0:^3d} and b={1:^5d}".format(a, b)) #a= 5 and b= 2

 print(“a={:f}".format(123.4567898)) #a=123.456790

 print("a={:8.3f}".format(123.4567898)) #a= 123.457


Number Formatting Types
Standard Data Types
 Python has five standard data types −

 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.

 Integers in Python 3 are of unlimited size.

 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

int float complex


10 0.0 3.14j

100 15.20 45.j

-786 -21.9 9.322e1-36j

0o70 32.3e18 .876j

-0o470 -90. -.6545+0J

-0x260 -32.54e100 3e1+26J

0x69 70.2E-12 4.53e1-7j


Standard Data Types

 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

 This will produce the following result −


 Hello World!
 H
 llo
 llo World!
 Hello World!Hello World!
 Hello World!TEST
Standard Data Types
 Strings
 str = 'Hello World!'

 print (str[-1])
 print (str[-3:-1])
 print (str[-12:])

 This will produce the following result −


 !
 ld
 Hello World!
Mutable and Immutable in Python
 Python represents all its data as objects that has
 an identity (id)
 a value (mutable or immutable)

 Some of these objects like lists and dictionaries are mutable,


meaning you can change their content without changing their
identity (Mutable)
 Other objects like integers, floats, strings and tuples are objects
that can not be changed (Immutable). If you change the value, they
also change their id.
 Some objects are mutable, meaning they can be altered. Others
are immutable; they cannot be changed but rather return new
objects when attempting to update
 Primitive data types are normally immutable while container and
user-defined data types are mutable
 Immutable objects are fundamentally expensive to "change",
because doing so involves creating a copy. Changing mutable
objects is cheap
Mutable and Immutable in Python
b = [] a = 4

print(id(b)) print(id(a))

140675605442000 6406872

b.append(3) a = a + 1

print(b) print(id(a))

[3] 6406899 # DIFFERENT

print(id(b))

140675605442000 # SAME
Standard Data Types
 Strings
 Python strings cannot be changed — they are
immutable.

 Therefore, assigning to an indexed position in the


string results in an error
 I.e. str[0] = ‘J’ results in an error. However, str=“welcome”
works.
Standard Data Types
 List
 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 from -1 at the end.

 The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.

 Unlike strings, which are immutable, lists are a mutable type,


i.e. it is possible to change their content.

 Trying to access/assign elements beyond the length of the list


results in an error.
Standard Data Types
 List (see the juypter notebook)
 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
 tinylist = [123, 'john']

 print (list) # Prints complete list


 print (list[0]) # Prints first element of the list
 print (list[1:3]) # Prints elements from 2nd till 3rd
 print (list[2:]) # Prints elements from 3rd element
 print (tinylist * 2) # Prints list two times
 print (list + tinylist) # Prints concatenated lists

 This produce the following result −


 ['abcd', 786, 2.23, 'john', 70.2]
 abcd
 [786, 2.23]
 [2.23, 'john', 70.2]
 [123, 'john', 123, 'john']
 ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Standard Data Types
 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
 tinylist = [123, 'john']

 print (list) # Prints complete list


 print (list[0]) # Prints first element of the list
 print (list[1:3]) # Prints elements from 2nd till 3rd
 print (list[2:]) # Prints elements from 3rd element
 print (tinylist * 2) # Prints list two times
 print (list + tinylist) # Prints concatenated lists

 This produce the following result −


 ['abcd', 786, 2.23, 'john', 70.2]
 abcd
 [786, 2.23]
 [2.23, 'john', 70.2]
 [123, 'john', 123, 'john']
 ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Standard Data Types

 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 brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.

 Tuples can be thought of as read-only lists/immutable lists.


Standard Data Types
 Tuples
 tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
 tinytuple = (123, 'john')

 print (tuple) # Prints complete tuple


 print (tuple[0]) # Prints first element of the tuple
 print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
 print (tuple[2:]) # Prints elements starting from 3rd element
 print (tinytuple * 2) # Prints tuple two times
 print (tuple + tinytuple) # Prints concatenated tuple

 This produce the following result −


 ('abcd', 786, 2.23, 'john', 70.2)
 abcd
 (786, 2.23)
 (2.23, 'john', 70.2)
 (123, 'john', 123, 'john')
 ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Standard Data Types
 Tuples and List
 tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

 tuple[2] = 1000 # Invalid syntax with tuple

 list[2] = 1000 # Valid syntax with list


Standard Data Types
 Sets
 A set in Mathematics refers to an unordered collection of objects
without any duplicate.

 An object of type set may be created by enclosing the elements


of the sets with in curly brackets.

 The major difference is that sets, unlike lists or tuples, cannot


have multiple occurrences of the same element and store
unordered values.

 The set objects may also created by applying the set function to
lists strings and tuples.

 Unlike lists we can’t access the elements of a set through


indexing and slicing

 We cant apply + and * operators on sets


 Open the jupyter notebook
Standard Data Types
 Dictionary
 Dictionaries 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 ({ }) and values can


be assigned and accessed using square braces ([]).

 Dictionaries have no concept of order among elements.

 It is incorrect to say that the elements are "out of order"; they


are simply unordered.

 Dictionaries are mutable.


Standard Data Types
 Dictionary
 dict = {}
 dict['one'] = "This is one"
 dict[2] = "This is two"
 tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

 print (dict['one']) # Prints value for 'one' key


 print (dict[2]) # Prints value for 2 key
 print (tinydict) # Prints complete dictionary
 print (tinydict.keys()) # Prints all the keys
 print (tinydict.values()) # Prints all the values
 This produce the following result −
 This is one
 This is two
 {'dept': 'sales', 'code': 6734, 'name': 'john'}
 ['dept', 'code', 'name']
 ['sales', 6734, 'john']
Input Statement
 a=input(“Enter a:”)
 a=int(input(“Enter a:”))
 a=eval(input("Enter three values:"))
 a, b, c=eval(input(“Enter a, b, c:”))
Matrices
 Matrix is a two-dimensional data structure
 All matrices can be considered as nested list
 a=[[1,2,3],[4,5,6]]
 a[0], a[1], a[0][0], a[0][2], a[1][2]
 Eg.
a = [['Vijay',80,75,85,90,95],

['Vishal',75,80,75,85,100],

['Priyank',80,80,80,90,95]]

print(a[0]) # ['Vijay', 80, 75, 85, 90, 95]

print(a[0][1]) # 80

print(a[1][2]) # 80
Basic Operators
 Types of Operator
 Arithmetic Operators

 Comparison (Relational) 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

/ Division Divides left hand operand by right hand operand b / a = 2.1

% Modulus Divides left hand operand by right hand operand b%a=1


and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the
operators power 21
// Floor Division - The division of operands where 9//2 = 4 and
the result is the quotient in which the digits after 9.0//2.0 = 4.0
the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative
infinity):
Basic Operators
 Comparison Operators
 Assume variable a holds 10 and variable b holds 20, then
Operator Description Example
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.

!= If values of two operands are not equal, then (a!= b) is true.


condition becomes true.

> 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

//= It performs floor division on operators and assign c //= a is equivalent to c =


value to the left operand c // a
Basic Operators
 Bitwise Operators
 Assume a = 60 = 0b00111100 and b = 13 = 0b00001101,
then
Operator Description Example

& 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

Operator Description Example


and If both the operands are true (a and b) is False.
then condition becomes true.
or If any of the two operands are (a or b) is True.
non-zero then condition
becomes true.
not Used to reverse the logical Not(a and b) is True.
state of its operand.
Basic Operators
 Membership Operators
 Python’s membership operators test for membership in a
sequence, such as strings, lists, or tuples.
 There are two membership operators as explained below
Operator Description Example
in Evaluates to true if it finds a variable in the x in y, here “in” results in a 1 if x is
specified sequence and false otherwise. a member of sequence y.

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).

# Python program to illustrate the use


# of 'is' identity operator
x = 5
if (type(x) is int):
print ("true")
else:
print ("false")
Basic Operators
 Python Operator Precedence
 Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Decision Making
 Simple if
 if expression:
statement(s)
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)

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)

print ("Net payable:",amount-discount)


Decision Making
 if else
Output:
Enter amount: 600
Discount 30.0
Net payable: 570.0

Enter amount: 1200


Discount 120.0
Net payable: 1080.0
Decision Making
 elif Statement
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Decision Making
 elif Statement
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)

print ("Net payable:",amount-discount)


Decision Making
 elif Statement
Enter amount: 600
Discount 30.0
Net payable: 570.0

Enter amount: 3000


Discount 300.0
Net payable: 2700.0

Enter amount: 6000


Discount 900.0
Net payable: 5100.0
Decision Making
 Nested if

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

for iterating_var in sequence:


statements(s)

for var in list(range(5)):


print (var)

Output:
0
1
2
3
4
Loops
 for Loop

for letter in 'Python': # traversal of a string sequence


print ('Current Letter :', letter)

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Loops
 for Loop

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: #traversal of List
sequence
print ('Current fruit :', fruit)

print ("Good bye!")

Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
 for Loop
 Iterating by Sequence Index

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print('Current fruit :', fruits[index])

print ("Good bye!")

Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
 Break Statement
for letter in 'Python':

if letter == 'h':

break

print ('Current Letter :', letter)

print ('Breaked Letter :', letter)

Output:

Current Letter : P

Current Letter : y

Current Letter : t

Breaked Letter : h
Loops
 Continue Statement
for letter in 'Python':

if letter == 'h':

continue

print ('Current Letter :', letter)

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

with a loop statement


 If the else statement is used with a for loop, the else block

is executed only if for loops terminates normally (and not

by encountering break statement)


 If the else statement is used with a while loop, the else

statement is executed when the condition becomes false.


Loops
 Using else Statement with Loops
numbers = [11, 33, 55, 39, 55, 76, 37, 21, 23, 41, 13]
for num in numbers:
if num%2==0:
print('the list contains an even number')
break
else:
print('the list does not contain even number')

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

 Number Type Conversion


 Type int(x) to convert x to a plain integer.

 Type float(x) to convert x to a floating-point number.

 Type complex(x) to convert x to a complex number with real part x

and imaginary part zero.

 Type complex(x, y) to convert x and y to a complex number with

real part x and imaginary part y. x and y are numeric expressions.


Numbers - Revisited
 Numbers
 Mathematical Functions
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x
and zero.
math.ceil(x) The ceiling of x: the smallest integer not less than x
math.floor(x) The floor of x: the largest integer not greater than x
math.exp(x) The exponential of x: ex
math.log(x) The natural logarithm of x, for x> 0
math.log10(x) The base-10 logarithm of x for x> 0 .
Need to import math

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]

print ("After deleting value at index 2 : ", list)

Output:

['physics', 'chemistry', 1997, 2000]

After deleting value at index 2 : ['physics', 'chemistry',


2000]
Lists - Revisited
 Basic List Operations

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1,2,3] : 123 Iteration
print (x,end=' ')
Lists - Revisited
 Built in List Functions and Methods (assume list to
be name of the variable)
Sr. Function with Description

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]

def printme( str ):

 "This prints a passed string into this function"

 print (str)

 return
Python Functions
 Pass by reference vs value

 All parameters (arguments) in the Python language are


passed by reference.

 It means if you change what a parameter refers to within a


function, the change also reflects back in the calling
function.
Python Functions
 Pass by reference vs value
myList = [2, 109, False, 10, "Vijay", 482, "Vishal"]
print(myList)

# Function definition is here


def changeme( mylist ):
"This changes the passed list into this function"
print("Values inside the function before change: ", mylist)
mylist[2]=50
print("Values inside the function after change: ", mylist)
return
changeme(myList)

Output:

[2, 109, False, 10, 'Vijay', 482, 'Vishal']

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

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist)
print ("Values outside the function: ", mylist)

Output:

Values inside the function: [1, 2, 3, 4]

Values outside the function: [10, 20, 30]


Python Functions
 Global vs. Local Variables
 Variables that are defined inside a function body have a
local scope, and those defined outside have a global
scope.

 This means that local variables can be accessed only


inside the function in which they are declared, whereas
global variables can be accessed throughout the program
body by all functions.
Python Functions
 Global vs. Local Variables
total = 0 # This is a global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return

# Now you can call sum function


sum(10, 20)
print ("Outside the function global total : ", total )

Output:

Inside the function local total : 30

Outside the function global total : 0


Python Functions
 Global vs. Local Variables
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
global total
total = arg1 + arg2;
print ("Inside the function local total : ", total)
return

# Now you can call sum function


sum( 10, 20 )
print ("Outside the function global total : ", total )

Output:
Inside the function local total : 30
Outside the function global total : 30

Note: You can also return multiple values, e.g. return x, y


Python Functions
 Multiple return values
# This function returns a tuple
def fun():
str = "Python is Great"
x = 100
return str, x; # Return tuple, we could also
# write (str, x)

#Call the function now


str, x = fun() # Assign returned tuple
print(str)
print(x)

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_obj = open(file_name [, access_mode][, buffering])

file_name − The file_name argument is a string value that contains the name

of the file that you want to access

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

default file access mode is read (r).

buffering − If the buffering value is set to 0, no buffering takes place. If the

buffering value is 1, line buffering is performed while accessing a file.


File Input / Output
Mode Description

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

wb Opens a file for writing only in binary format


w+ Opens a file for both writing and reading
wb+ Opens a file for both writing and reading in binary format
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing

ab Opens a file for appending in binary format


a+ Opens a file for both appending and reading

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

file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened.


file.name Returns name of the file
file.softspace Returns false if space explicitly required with print, true otherwise
# Open a file
fo = open("test.txt", "wb")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
print("Softspace flag : ", fo.softspace)
Output
Name of the file: test.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
 Close the file using file_object.close() method
File Reading / Writing
 The file_object provides access methods to access the file
 write() Method
 The write() method writes any string to an open file
#Open a file
fo = open("test.txt", "w")
fo.write("Python is a great. \nYeah its great!!\n");
#Close opened file
fo.close()
File Reading / Writing
 read() Method
 The read() method reads a string from an open file
# Open a file
fo = open("test.txt", "r+")
str = fo.read(10);
print("Read String is : ", str)
# Close opend file
fo.close()

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)

# Check current position


position = fo.tell();
print("Current file position : ", position)

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10);
print("Again read String is : ", str)
# Close opend file
fo.close()

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

 A module is loaded only once, regardless of the number of times it is


imported

Output
# Import module hello
import hello

# Call defined function from module as follows


hello.say_hello("Vijay")
NumPy
Numpy
 Numpy (Numeric/Numerical Python)
 Numpy is an open-source add-on module that provides
common mathematical and numerical routines as pre-
compiled fast functions

 It provides basic routines for manipulating large arrays and


matrices of numeric data.

 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]]

 To create array with minimum dimension


a = np.array([1, 2, 3, 4, 5], ndmin = 2)
print a
Output
[[1 2 3 4 5]]
Numpy
 To create an array with dtype parameter
a = np.array([1, 2, 3], dtype = complex)
print a
Output
[ 1.+0.j, 2.+0.j, 3.+0.j]

a = np.array([[1, 2, 3], [4, 5, 6]], float)


print a
Output
[[1. 2. 3.]
[4. 5. 6.]]
Numpy - datatypes (dtypes)
 NumPy supports a much greater variety of numerical types than Python d
oes.
 bool_, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float16, float3
2, float64, complex64, complex128 etc...
 A dtype object is constructed using the following syntax :

numpy.dtype(object, align, copy)

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

You might also like