0% found this document useful (0 votes)
5 views

PSP UNIT 2 (1)

Python is an open-source, high-level programming language created by Guido van Rossum in the early 1990s, known for its ease of learning and versatility. It supports various operating systems and is widely used in web development, system utilities, and game programming. The document covers Python's features, coding style, data types, expressions, statements, and operators.

Uploaded by

danukrishnan003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

PSP UNIT 2 (1)

Python is an open-source, high-level programming language created by Guido van Rossum in the early 1990s, known for its ease of learning and versatility. It supports various operating systems and is widely used in web development, system utilities, and game programming. The document covers Python's features, coding style, data types, expressions, statements, and operators.

Uploaded by

danukrishnan003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 139

UNIT 2

DATA ,EXPRESSIONS,
STATEMENTS
WHAT IS PYTHON?
 Python is an open source, object-oriented,
high-level powerful programming language.

 Developed by Guido van Rossum in the


early 1990s. Named after Monty Python

 Pythonruns on many Unix variants, on the Mac,


and on Windows 2000 and later.
PYTHON PROGRAM
Python programs are composed of modules
Modules contain statements
Statements contain expressions
Expressions create and process objects
Features of Python
open source
Easy-to-learn
VERSIONS OF PYTHON
PYTHON 2.X
PYTHON 3.X
HISTORY
The name Python was selected from “Monty
Python’s Flying Circus” which was a British
sketch comedy series.

Python was created as a successor of a


language called ABC (All Basic Code) and
released publicly in1991.
Major uses of Python
 System utilities (system admin tools, command
line programs).
 Web Development.
 Graphical User Interfaces (Tkinter, gtk, Qt).
 Internet scripting.
 Embedded scripting.
 Database access and programming.
 Game programming.
 Rapid prototyping and development.
 Distributed programming
Python Definition
Python is a high-level programming language
designed to be easy to read and simple to
implement.
 It is open source, which means it is free to use,
even for commercial applications.
Which kind OS supports python?

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

for continuation lines it prompts with the


secondary prompt, by default three dots
(...)
Example to print a text in python
>>>print(“welcome”>

welcome

>>>

For continuous multiline printing using(‘”’”)

>>>print(‘“hi we are going

to learn new version of

Python 3.6.2’”)

hi we are going

to learn new version of

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

A Boolean variable can take only


two values, true or False.
The main use of this type is in
logical expressions.
Example
a= true
b = 30 > 45 # b gets the value
False
Boolean operators
Boolean operations are performed using the
and, or, and not keywords in Python:
True and False # False
False or True # True
(30 > 45) or (27 < 30) # True
not True # False
not (3 > 4) # True
Example for Booleans
>>> 3>4
False
>>> test = (3 > 4)
>>>test
False
>>> type(test)
<type ‘bool’>
Strings:
Strings are amongst the most popular types in
Python and it is an ordered sequence of
characters.
Creating strings is as simple as assigning a value
to a variable.
>>> str =“Akshaya”
Character
Python does not have a distinct character type.
In Python, a character is a string of length
The character “a” is a plain string of length 1:

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

In Python programming, a list is created by


placing all the items (elements) inside a square
bracket [ ], separated by commas.
Examples
#empty list
my_list = []
 # list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, “World”,
3.4]
List Index
The index operator [] is used to access an item
in a list.
Index starts from 0.
So, a list having 5 elements will have index
from 0 to 4.
Nested list are accessed using
nested indexing.
my_list = [‘p’,‘r’,‘o’,‘b’,‘e’]

# Output: p

print(my_list[0])

#Output: o

print(my_list[2])

#Error ! Only integer can be used for


indexing

print (my_list[4.0])
Negative indexing
Python allows negative
indexing for its sequences.

 The index of -1 refers to the


last item, -2 to the second last
item and so on.
Examples

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.

In other words a variable in a program


gives data to the computer to work
on.

Variablescan be declared by any


name or even alphabets like a, aa, abc
etc.
Example

>>>b=200
>>>print (b)
200
re-declare a Variable
#Declare a variable and
initialize it
c= 0;
print c

#re-declaring the variable works


c = “Welcome”
Print c
Concatenate Variables
Itis used to concatenate different
data types like string and number
together.
examples
a=‘‘Guru”
b =99
print a + str(b)
Output:
Guru99
Local & Global Variables
In Python use the same variable for
rest of the program or module and
declare it global variable, while if want
to use the variable in a specific
function or method you use local
variable.
#Declare a variable and initialize it

f =101;

Print f

#Global vs. local variables in functions

def someFunction():

#global f

f =“God is great”

print f

somefunction()

print f
delete a variable
 In delete variable using the command

del ”variable name”

#Declare a variable and initialize it

b = 102;

print b

del b

print b

NameError: name ‘b’ is not defined


Swap variables

Python swap values in a single line and this


applies to all objects in python.
Syntax :

var1, var2 = var2, var1


 >>> x = 10
 >>> y = 20
 >>> print(x)
 10
 >>> print(y)
 20
 >>> x, y = y, x
 >>> print(x)
 20
 >>> print(y)
EXPRESSIONS
EXPRESSIONS
An expression is a combination of
values, variables, and operators.

If type an expression on the command


line, the interpreter evaluates it and
displays the result
EXAMPLES
 >>> 2+ 2
 4
 >>> line =“God is Great?”
 >>> line
 “God is Great?”
 >>> print line
 God is Great?
STATEMENTS
Statement
A statement is an instruction that the
Python interpreter can execute

Two kinds of statements:


 print
 assignment.
Example

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

4. Logical (or Relational) Operators

5. Bitwise Operators

6. Conditional (or ternary) Operators

7. Membership Operators

8. Identity Operators
Python Arithmetic
Operators:
Operator Description Example

+ Addition operator to add two operands 5+2=7


Subtraction operator to subtracts two
- 5–2=3
operands
Multiplication operator to multiply two
* 5 * 2 = 10
operands
Division operator to Divides left hand
/ 5/2= 2
operand by right hand operand
Modulus - Divides left hand operand by
% right hand operand and returns 5%2=1
remainder
Exponent - Performs exponential (power)
** 5**2 = 25 (ie 52)
calculation on operands
Floor Division - The division of operands
5 // 2 = 2
where the result is the quotient in which
// 5.0 // 2.0 = 2.0
the digits after the decimal point are
removed.
Python Comparison Operators:

Operator Description Example

== Checks if the value of two operands are equal (5 == 2) is false

!= (5 != 2) is true
Checks if the value of two operands are not equal
<> (5 <> 2) is true

Checks if the value of left operand is greater than


> (5 > 2) is true
the value of right operand

Checks if the value of left operand is less than the


< (5 < 2) is false
value of right operand

Checks if the value of left operand is greater than or


>= (5 >= 2) is true
equal to the value of right operand

Checks if the value of left operand is less than or


<= (5 <= 2) is false
equal to the value of right operand
Python Assignment Operators:
Operator Description Example

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 subtracts right operand from the left operand and c -= a is equivalent


-=
assign the result to left operand to c = c - a

It multiplies right operand with the left operand and c *= a is equivalent


*=
assign the 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 exponential (power) calculation on two operands c **= a is equivalent


**=
and assign value to the 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.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and false results in a 1 if x is a
otherwise. member of sequence y.
Python Operators
Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // 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
Python - IF...ELIF...ELSE Statement
 The syntax of the if statement is:
if expression: if expression:
statement(s)
statement(s) else:
Example: 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!"
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1

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"

print "Good bye!"


Single Statement
Suites:
If the suite of an if clause consists only of a single line, it may
go on the same line as the header statement:

if ( expression == 1 ) : print "Value of expression is 1"


5. Python - while Loop
Statements
 The while loop is one of the looping constructs
available in Python. The while loop continues until
the expression becomes false. The expression has to
be a logical expression and must return either a true
or a false value
The syntax of the while loop is:
while expression:
statement(s)
Example:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
The Infinite Loops:
 You must use caution when using while loops because of
the possibility that this condition never resolves to a false
value. This results in a loop that never ends. Such a loop is
called an infinite loop.
 An infinite loop might be useful in client/server
programming where the server needs to run continuously
so that client programs can communicate with it as and
when required.

Following loop will continue till you enter CTRL+C :


while var == 1 : # This constructs an infinite
loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"
Single Statement Suites:
 Similar to the if statement syntax, if your while clause
consists only of a single statement, it may be placed on
the same line as the while header.

 Here is the syntax of a one-line while clause:

while expression : statement


6. Python - for Loop Statements
 The for loop in Python has the ability to iterate over the
items of any sequence, such as a list or a string.
 The syntax of the loop look is:
for iterating_var in sequence:
statements(s)
Example:
for letter in 'Python': # First Example
print 'Current Letter :', letter

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


for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Iterating by Sequence Index:
 An alternative way of iterating through each item is
by index offset into the sequence itself:

 Example:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"


7. Python break,continue and pass
Statements
The break Statement:
 The break statement in Python terminates the current loop and
resumes execution at the next statement, just like the traditional
break found in C.
Example:
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
The continue Statement:
 The continue statement in Python returns the control to the
beginning of the while loop. The continue statement rejects
all the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop.
Example:
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
The else Statement Used with Loops

Python supports to have an else statement associated with a loop


statements.
 If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
 If the else statement is used with a while loop, the else statement
is executed when the condition becomes false.
Example:
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
The pass Statement:
 The pass statement in Python is used when a statement is
required syntactically but you do not want any command
or code to execute.
 The pass statement is a null operation; nothing happens
when it executes. The pass is also useful in places where
your code will eventually go, but has not been written yet
(e.g., in stubs for example):
Example:
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
operator Precedence
Exponent and
Multiplication
Exponent will always run before the
multiplication equation.
#Exponent and Multiplication
#Exponent Runs First

>>> 2** 4+2


18
#If multiplication ran first this
answer would be 16
>>> 2*4 ** 2
32.
Exponent and division
Exponent will always run before a
division equation.
# Exponent and Division

#Exponent runs first


>>> 4/2 ** 6
0.0625
#2** 6 is 64
>>> 4/64
0.0625
Multiplication and division
#Multiplication and Division
#In this case division is ran
first then multiplied by 3
>>> 5/4 *3
3.75
#In this case 3 is multiplied
by 4 then divided by 5
>>> 3*4/5
2.4
Multiplication and Addition
#Multiplication and Addition
>>> 2+4*4
18
Addition and Subtraction
#Addition and Subtraction
>>> 2+3-5+8 -4+2 -9
-3
Associativity of Python
operators
When two operators have the same precedence,
associativity helps to determine which the order
of operations.
# Left-right associativity
# Output: 3
print(5*2// 3)
COMMENTS
COMMENTS
Comments in Python is also quite different
than other languages, but it is pretty easy to get
used to.
Types of comments

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

Multiple lines can be created by


repeating the number sign
several times
A common way to use comments
for multiple lines is to use the (”’)
symbol.
‘’’ This is a multiline
Python comment example.’’’
x =5
MODULES AND
FUNCTIONS
MODULES AND
FUNCTIONS
Modules are quite easy to create.
They are simply Python files, like
your regular scripts.
To create a module, write one or
more functions in a text file, then
save it with a .py extension.
EXAMPLE(finance.py)
create a function for calculating
tax on a product.
def addTax(price, tax):
newPrice = price / 100 * (100 +
tax)
return newPrice
Importing modules
we can use either the import or
the from keyword.
our finance module in the same
folder as our script.
Example: import finance
Built-in Modules
random
math
os
datetime
urllib2
Random
when using Python to create a
website, they can be used in
making your password
database more secure or
powering a random page
feature.
example
import random
print (random. randint(0, 5))
 This will output either 1, 2, 3, 4 or 5.
 Randint accepts exactly two parameters: a lowest and a
highest number.
math
 The math module provides access to mathematical
constants and functions.
 importmath

math.pi #Pi, 3.14...


math.e #Euler’s number, 2.71...
math.degrees(2) #2 radians = 114.59 degreees
math.radians(60) #60 degrees=1.04 radians
date time
An website with comments, or a
blog, then you’ll probably be
displaying their age, or the time
they were created.
import datetime
operating System (os)
os, which provides functions that
allow you to interface with the
underlying operating system.
Python is running on - be that
Windows, Mac or Linux.
urllib2
This module lets you interface
with the web, so it’s obviously
quite relevant to us.
Import urllib2

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

(i)Function with no argument and


no return value.
(ii)Function with argument and
no return value.
(iii)Function with argument and
with return value.
(iv)Function with no argument
and with return value.
(i)Function with no argument and no return value.
Function with arguments and no return
values:
Function with arguments and with return
value:
Function with no arguments and with
return value
FLOW OF EXECUTION
FLOW OF EXECUTION
Execution always begins at the
first statement of the
program.
Statements are executed one
at a time, in order, from top
to bottom.
Example
PARAMETERS AND ARGUMENTS
Some functions take more than
one argument: math.pow takes
two, the base and the
exponent.
Example
ILLUSTRATIVE PROGRAMS
ILLUSTRATIVE PROGRAMS
THANK YOU

You might also like