PSP UNIT 2 (1)
PSP UNIT 2 (1)
DATA ,EXPRESSIONS,
STATEMENTS
WHAT IS PYTHON?
Python is an open source, object-oriented,
high-level powerful programming language.
Mac
Windows
Unix systems
Applications that supported by
python
2D and 3D imaging programs
Python API supports
GIMP,
Inkscape,
Blender,
Autodesk Maya
Python is considered as scripting
language creating Web applications
and dynamic Web content.
Python coding Style
Use 4 spaces per indentation and no tabs.
Do not mix tabs and spaces.
Tabs create confusion and it is recommended
to use only spaces.
Maximum line length : 79 characters which help
users with a small display.
Use blank lines to separate top-level function
and class definitions and single blank line to
separate methods definitions inside a class and
larger blocks of code inside functions.
When possible, put inline comments (should
be complete sentences).
Use spaces around expressions and statements
PYTHON INTERPRETER
AND INTERACTIVE
MODE
INTERPRETER
An interpreter is a program that reads and
execute code.
This includes source code, pre-compiled code
and scripts.
Python is considered on because python
programs are executed by an interpreter.
PROCESS OF
INTERPRETER
Interactive Mode
Interactive mode is a command line shell
which gives immediate feedback for each
statement, while running previously fed
statements in active memory.
In this mode the prompts for the next
command with the primary prompt, usually
three greater-than signs (>>>)
welcome
>>>
Python 3.6.2’”)
hi we are going
Python 3.6.2
>>>
Example for printing integer value
and also the variable storing value
>>>print 2
>>>x = 3
>>>print x
2
3
>>>
VALUES AND
TYPES
VALUE
A value is one of the fundamental things like
word or a number that a program manipulates.
TYPES
Integer
float
Boolean
String
list
Integers and float:
Example for Integers
>>> 1 + 1
2
>>> a = 4
>>> type(a)
<type ‘int’>
Example for Floats
>>> c = 2.1
>>> type(c)
< type ‘float’>
Boolean
Boolean is a data type named
after George Boole (1815-1864).
>>> x= ‘a’
• The integer equivalent of the letter “A”:
>>> x = “A”
>>> ord(x)
65
operators on strings
The concatenate strings with
the “+” operator and create
multiple concatenated copies of
a string with the “*” operator.
Example:
>>> ‘horse’ + ‘and’ + ‘dog’
‘horse and dog’
>>> ‘#’ * 4
####
Examples
Given these strings:
>>> s1 = ‘abcd’
>>> s2 = ‘efgh’
• The plus (+) operator applied to a
string can be used to
concatenate strings:
>>> s3 = s1 + s2
>>> s3
‘abcdefgh’
Escape characters
An escape character lets you use characters
that are otherwise impossible to put into a
string.
An escape character consists of a backslash (\)
followed by the character you want to add
to the string.
examples
>>> print(“Hello there!\nHow
are you?\nI\’m doing fine.”)
Hello there!
How are you?
I’m doing fine.
Raw Strings
A raw string completely ignores
all escape characters and prints
any backslash that appears in the
string.
r can be used before the
beginning quotation mark of a
string to make it a raw string.
>>> print(r’‘ That is
David\’s bird.’)
That is David\’s bird.
Multiline Strings With triple
Quotes
A multiline string in Python begins
and ends with either three single
quotes or three double quotes.
Python’s indentation rules for blocks
do not apply to lines inside a
multiline string.
print(‘‘Dear Joseph, Steve’s cat
has been arrested for
catnapping, cat burglary, and
extortion. Sincerely, James’’)
unicode strings
Unicode strings give us a
consistent way to process
character data from a variety of
character encodings.
Solutions:
Can represent unicode string with either the “u”
prefix or with a call to the unicode type:
def exercise1():
a = u ‘abcd’
print a
b=unicode(‘efgh’)
print b
Lists:
List is one of the most frequently used and
very versatile data type used in Python.
# Output: p
print(my_list[0])
#Output: o
print(my_list[2])
print (my_list[4.0])
Negative indexing
Python allows negative
indexing for its sequences.
my_list = [‘p’,‘r’,‘o’,‘b’,‘e’]
# Output: e
print(my_list[-1])
# Output:p
print(my_list[-5])
VARIABLES
Variables
Avariable is nothing but a reserved
memory location to store values.
>>>b=200
>>>print (b)
200
re-declare a Variable
#Declare a variable and
initialize it
c= 0;
print c
f =101;
Print f
def someFunction():
#global f
f =“God is great”
print f
somefunction()
print f
delete a variable
In delete variable using the command
b = 102;
print b
del b
print b
print 1
x=2
print x
produces the output:
1
2
The assignment statement
produces no output.
TUPLE ASSIGNMENT
TUPLE ASSIGNMENT
Python has a very powerful tuple
assignment feature that allows a tuple
of variables on the left of an
assignment to be assigned values
from a tuple on the right of the
assignment.
Example
(name, surname, birth_year, movie,
movie_year, profession, birth_place) = julia
Swapping example
temp = a
a=b
b = temp
Tuple assignment solves this problem
neatly:
(a, b) = (b, a)
PRECEDENCE OF OPERATORS
4. Python - Basic
Operators
Python language Operator Types.
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
5. Bitwise Operators
7. Membership Operators
8. Identity Operators
Python Arithmetic
Operators:
Operator Description Example
!= (5 != 2) is true
Checks if the value of two operands are not equal
<> (5 <> 2) is true
Assigns values from right side operands to left side c = a + b will assigne
=
operand value of a + b into c
It adds right operand to the left operand and assign the c += a is equivalent
+=
result to left operand to c = c + a
It divides left operand with the right operand and assign c /= a is equivalent
/=
the result to left operand to c = c / a
It takes modulus using two operands and assign the result c %= a is equivalent
%=
to left operand to c = c % a
Performs floor division on two operands and assign value c //= a is equivalent
//=
to the left operand to c = c // a
Python Bitwise
Operators:
Operat
Description Example
or
& Binary AND Operator copies a bit to the (a & b) will give 12
result if it exists in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it exists (a | b) will give 61 which
in either operand. is 0011 1101
^ Binary XOR Operator copies the bit if it is (a ^ b) will give 49
set in one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary (~a ) will give -60 which
and has the effect of 'flipping' bits. is 1100 0011
<< Binary Left Shift Operator. The left operands a << 2 will give 240
value is moved left by the number of bits which is 1111 0000
specified by the right operand.
>> Binary Right Shift Operator. The left a >> 2 will give 15
operands value is moved right by the which is 0000 1111
number of bits specified by the right
operand.
Python Logical
Operators:
Operat
Description Example
or
and Called Logical AND operator. If both the (a and b) is true.
operands are true then then condition
becomes true.
or Called Logical OR Operator. If any of the two (a or b) is true.
operands are non zero then then condition
becomes true.
not Called Logical NOT Operator. Use to reverses not(a and b) is false.
the logical state of its operand. If a condition
is true then Logical NOT operator will make
false.
Python Membership
Operators:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.
Operato
Description Example
r
in Evaluates to true if it finds a variable in the x in y, here in results in a
specified sequence and false otherwise. 1 if x is a member of
sequence y.
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
The Nested if...elif...else Construct
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
Example:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
single line
multiple line
A hash sign (#) that is not
inside a string literal is the
beginning of a comment.
All characters after the #, up
to the end of the physical line,
are part of the comment and the
Python interpreter ignores them.
Single line comment
# This is a comment
print(‘Hello’)
For each line you want to
comment, put the number sign (#)
in front.
# print(‘This is not run’)
print(‘Hello’)
Multiline comment
Urllib2.urlopen(“http://net.infopytho
n.com”)
FUNCTIONS
Functions
A function is a named container
for a block of code.
Types of function
user defined
predefined
#our two costs to add up
cost1 = 15
cost2 = 20
def sumCart():
totalCost =cost1 + cost2
print totalCost
sumCart()
Arguments
An argument is a way of passing
data into a function when we
don’t know which variable or
variables that data is going to be
in.
Arguments are defined inside the
parentheses, and each argument
is given a name, with a comma
separating each
Argument defaults
There is one way around this: you
can define a default value for any
argument, which is used in the
cases when you don’t supply a
value.
returning values
When the function returns a
value, that
value will now be stored in the
variable we specified.
Functions - Built-In
str()
len()
int()
range()
Function with and without arguments with
examples