Download Module 3

Document related concepts
no text concepts found
Transcript
MODULE 3
(Refer pgms done in lab, tutorial,
assignment.)
Variables, expressions & statements
Branching /conditional statements
Iteration/looping statements
Python Identifiers



A Python identifier is a name used to identify a variable,
function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores
and digits (0 to 9).
Python does not allow punctuation characters such as @, $
and % within identifiers.

Python is a case sensitive programming language.

reserved words may not be used as identifier names.
Good:
Bad:
spam
spam23
23spam
Different:
_speed roll_num
#sign var.12
spam Spam SPAM
keywords:


Keywords are reserved words that have a
predefined meaning
No identifier can have the same name as one of
the Python keywords:
and, as, assert, break, class, continue, def, del,
elif, else, except, finally, for, from, global, if,
import, in, is, lambda, nonlocal, not, or, pass,
raise, return, try, while, with, yield
Variables







Variables are nothing but memory locations to store values.
This means that when you create a variable you reserve some
space in memory..
A variable is a symbolic name for this physical location.
This memory location contains values, like numbers, text or more
complicated types.
A variable is a way of referring to a memory location used by a
computer program.
As the name implies, a variable is something which can change
While the program is running, variables are accessed and
sometimes changed, i.e. a new value will be assigned to the
variable

Declaration of variables is not required in Python.

Python is dynamically typed language.


Not only the value of a variable may change during
program execution but the type as well.
You can assign an integer value to a variable, use it as an
integer for a while and then assign a string to the variable.
Assigning Values to Variables


Python variables do not have to be explicitly declared to
reserve memory space.
The Declaration happens Automatically when you assign a
value to a variable.

The equal sign (=) is used to assign values to variables.

counter = 100

miles = 1000.0 # A floating point

name = "John“ # A string
# An integer assignment
Multiple Assignment




Python allows you to assign a single value to
several variables simultaneously
a=b=c=1
You can also assign multiple objects to multiple
variables
a, b, c = 1, 2, "john"
Standard Data Types



The data stored in memory can be of many types.
For example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric
characters
Python has six standard data types:
• Numbers – int and float
• String – str
• Boolean – bool
• List
• Tuple
Python Numbers



Number data types store numeric values
Python supports four different numerical data
types:
Integer

Normal integers
e.g. 4321

Octal literals (base 8)
A number prefixed by a 0 (zero) will be interpreted as
an octal number
example:
>>> a = 010
>>> print a
8

Hexadecimal literals (base 16)
Hexadecimal literals have to be prefixed either by
"0x" or "0X".
example:
>>> hex_number = 0xAF
>>> print hex_number



Long integers
these numbers are of unlimited size
e.g.42000000000000000000L
Floating-point numbers
for example: 42.11, 3.1415e-10
Complex numbers
Complex numbers are written as <real part> + <imaginary
part>j
examples:
>>> x = 3 + 4j
>>> y = 2 - 3j
>>> z = x + y
>>> print z
(5+1j)
Python Strings




Strings in Python are identified as a contiguous set of
characters in between 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

str = “python”

print str

print len(s) #length of string

print str[0]
# Prints first character of the string (indexing)
print str[2:5]
(slicing)
# Prints characters starting from 3rd to 5th

print str[2:]
# Prints string starting from 3rd character

print str * 2
# Prints string two times (repetition)

print str + "TEST" # Prints concatenated string (concatenation)

# Prints complete string

The last character of a string can be accessed like this:

>>> s[len(s)-1]

‘n‘

Yet, there is an easier way in Python.

The last character can be accessed with -1, the second to
last with -2 and so on:

>>> s[-1]

‘n'

>>> s[-2]

‘o'
type( )

If you are not sure what type a value has, the interpreter can tell
you.

>>> type("Hello, World!")

<type 'str'>

>>> type(17)

<type 'int'>

>>> type(3.2)

<type 'float'>

>>> type("17")

<type 'str'>

>>> type("3.2")
statement

A statement is an instruction that the Python
interpreter can execute

print 1 #print statement

x = 2 #assignment statement

print x
Data Type Conversion


There are several built-in functions to perform conversion
from one data type to another.
These functions return a new object representing the
converted value.

float(x)
Converts x to a floating-point number.

str(x)

chr(x) converts integer x to character.

eval(str)

repr(x) Converts object x to an expression string.
Converts object x to a string representation.
Evaluates a string and returns an object.
Python Integer Division is Weird!
Integer division truncates
•
Floating point division
produces floating point
numbers
>>> print 10 / 2
5
>>> print 9 / 2
4
>>> print 99 / 100
0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
Mixing Integer and Floating
•
•
When you perform an operation where
one operand is an integer and the
other operand is a floating point the
result is a floating point
The integer is converted to a floating
point before the operation
>>> print 99 / 100
0
>>> print 99 / 100.0
0.99
>>> print 99.0 / 100
0.99
>>> print 1 + 2 * 3 / 4.0 - 5
-2.5
Type Conversions
•
•
When you put an integer and
floating point in an expression
the
integer
is
implicitly
converted to a float
You can control this with the
built in functions int() and
float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
Expressions



Expression is a combination of values, variables and
operators
Combination of operators and operands
Operators are symbols used to perform mathematical or
logical operations

Values the operator uses are called operands

Evaluation of expression generates a value

Expressions appear on the right side of assignment
statement
Python operators


Python language supports the following types of
operators.
Arithmetic Operators

Comparison (i.e., Relational) Operators

Assignment Operators

Logical Operators

Bitwise Operators

Membership Operators

Identity Operators
Python Arithmetic Operators:
Operator
+
*
/
%
**
//
Description
Addition - Adds values on either side of the operator
Subtraction - Subtracts right hand operand from left
hand operand
Multiplication - Multiplies values on either side of the
operator
Division - Divides left hand operand by right hand
operand
Modulus - Divides left hand operand by right hand
operand and returns remainder
Exponent - Performs exponential (power) calculation
on operators
Floor Division - The division of operands where the
result is the quotient in which the digits after the
decimal point are removed.
Order of Evaluation
•
•
•
When we string operators together - Python must know which one to
do first
This is called “operator precedence”
Which operator “takes precedence” over the others
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
•
Highest precedence rule to lowest precedence rule
•
•
•
•
•
Parenthesis are always respected
Exponentiation (raise to a power)
Multiplication, Division
Addition and Subtraction
Left to right
Parenthesis
Power
Multiplication
Addition
Left to Right




Parentheses have the highest precedence and can be used
to force an expression to evaluate in the order you want.
Since expressions in parentheses are evaluated first, 2 * (31) is 4, and (1+1)**(5-2) is 8. You can also use parentheses
to
make
an
expression
easier
to
read,
as
in (minute * 100) / 60, even though it doesn’t change the
result.
Exponentiation has the next highest precedence,
so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
Multiplication and Division have the same precedence,
which is higher than Addition and Subtraction, which also
have the same precedence. So 2*3-1 yields 5 rather than 4,
and 2/3-1 is -1, not 1 (remember that in integer division,
2/3=0).
Operators with the same precedence are evaluated from
left to right. So in the expression minute*100/60, the
multiplication happens first, yielding 5900/60, which in
turn yields 98. If the operations had been evaluated from
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11
>>>
1 + 2 ** 3 / 4 * 5
1+8/4*5
1+2*5
1 + 10
11
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11
>>>
1 + 2 ** 3 / 4 * 5
Note 8/4 goes before 4*5
because of the left-right rule.
1+8/4*5
1+2*5
1 + 10
11
Python Comparison Operators:
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes (a == b) is not true.
then condition becomes true.
!=
Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(a != b) is true.
<>
Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(a <> b) is true. This is
similar to != operator.
>
Checks if the value of left operand is greater than the value (a > b) is not true.
of right operand, if yes then condition becomes true.
<
Checks if the value of left operand is less than the value of (a < b) is true.
right operand, if yes then condition becomes true.
>=
Checks if the value of left operand is greater than or equal (a >= b) is not true.
to the value of right operand, if yes then condition becomes
true.
<=
Checks if the value of left operand is less than or equal to
the value of right operand, if yes then condition becomes
true.
(a <= b) is true.
Python Assignment Operators:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side
operands to left side operand
+=
Add AND assignment operator, It adds right operand to the left c += a is equivalent to c
operand and assign the result to left operand
=c+a
Subtract AND assignment operator, It subtracts right operand c -= a is equivalent to c
from the left operand and assign the result to left operand
=c-a
-=
c = a + b will assigne
value of a + b into c
*=
Multiply AND assignment operator, It multiplies right operand c *= a is equivalent to c
with the left operand and assign the result to left operand
=c*a
/=
Divide AND assignment operator, It divides left operand with
the right operand and assign the result to left operand
c /= a is equivalent to c
=c/a
%=
Modulus AND assignment operator, It takes modulus using
two operands and assign the result to left operand
Exponent AND assignment operator, Performs exponential
(power) calculation on operators and assign value to the left
operand
Floor Division and assigns a value, Performs floor division on
operators and assign value to the left operand
c %= a is equivalent to
c=c%a
c **= a is equivalent to
c = c ** a
**=
//=
c //= a is equivalent to c
= c // a
Python Logical Operators:
Python Bitwise Operators:
Operator
Description
&
Binary AND Operator copies a bit to the result if it exists in both
operands.
|
Binary OR Operator copies a bit if it exists in either operand.
^
Binary XOR Operator copies the bit if it is set in one operand but
not both.
~
Binary Ones Complement Operator is unary and has the effect of
'flipping' bits.
<<
Binary Left Shift Operator. The left operands value is moved left
by the number of bits specified by the right operand.
>>
Binary Right Shift Operator. The left operands value is moved
right by the number of bits specified by the right operand.
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.
Operator
in
not in
Description
Example
Evaluates to true if it finds a variable in the
specified sequence and false otherwise.
x in y, here in results in a 1 if
x is a member of sequence y.
Evaluates to true if it does not finds a variable
in the specified sequence and false otherwise.
x not in y, here not in results
in a 1 if x is a member of
sequence y.
Identity Operators
Operator Description
is
is not
Evaluates to true if the variables on
either side of the operator point to
the same object and false otherwise.
Example
x is y, here is results
in 1 if id(x) equals
id(y).
Evaluates to false if the variables on x is not y, here is
either side of the operator point to
not results in 1 if
the same object and true otherwise. id(x) is not equal to
id(y).
Python Operators Precedence
Operator
Description
**
Exponentiation (raise to the power)
~, +, *, /, % ,//
complement, 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
= ,%=, /= , //=, -=, +=
,*=, **=
Is, is not
Assignment operators
In, not in
Membership operators
not ,or ,and
Logical operators
Identity operators
Input statement

There are two built-in functions in Python for
getting keyboard input:

n = raw_input("Please enter your name: ")

n = input("Enter a numerical expression: ")
Output statement

Print
Structuring with Indentation



All statements with the same distance to the right belong
to the same block of code, i.e. the statements within a block
line up vertically.
The block ends at a line less indented or the end of the file.
If a block has to be more deeply nested, it is simply
indented further to the right.
Adding Comments

Using
single line comment ----
#
multiline comments ---- ''' comment block '''
eg:
“““
this is a sample pgm
comment section
“““
PYTHON DECISION MAKING
Decision making” is one of the most important concepts
of computer programming.
Programs should be able to make logical (true/false) decisions
based on the condition they are in;
Every program has one or few problem/s to solve; depending
on the nature of the problems, important decisions have to
be made in order to solve those particular problems.
In python programming “conditional statement” is used for
decision making.
Branching/conditional statements
Usually programs follows a sequential form of execution of
statements.
Many times it is required to alter the flow of sequence of
instructions.
python language provides statements that can alter the flow
of a sequence of instructions.
These statements are called as control statements.
One-Way Selection Statements
Simplest form of selection is the if statement
Syntax:
if condition :
indentedStatementBlock
• The colon (:) is significant and required.
• It separates the header of the compound statement from
the body.
• The line after the colon must be indented.
• It is standard in Python to use four spaces for indenting.
• All lines indented the same amount after the colon will be
executed whenever the condition is true.
num = float(input("Enter a number: "))
if num > 0:
print "Positive number"
print "This is always printed"
weight = float(input("How many pounds does
your suitcase weigh? "))
if weight > 50:
print "There is a $25 charge for luggage that
heavy."
print "Thank you for your business."
Two-way selection statement
if… else statement
 An else statement can be combined with an if statement.
 An else statement contains the block of code that executes if the
conditional expression in the if statement resolves to 0 or a false
value.
 The else statement is an optional statement and there could be at
most only one else statement following if
Syntax:
if condition :
indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition
Example:
temperature = float(input('What is the
temperature? '))
if temperature > 30:
print 'Wear shorts.'
else:
print 'Wear long pants.'
Print 'Get some exercise outside.'
num = float(input("Enter a number: "))
if num >0:
print "Positive number"
else:
print "Negative number"
Multi-way if Statements
 The elif statement allows you to check multiple
expressions for truth value and execute a block of code as
soon as one of the conditions evaluates to true.
 Like the else, The elif statement is optional. However,
unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements
following an if.
Syntax:
Example:
num = float(input("Enter a number: "))
if num == 0:
print
“Zero"
elif num > 0:
print “Positive Number"
else:
print "Negative number"
Nested if Statements
 There may be a situation when you want to check for
another condition after a condition resolves to true. In
such a situation, you can use the nested if construct.
 In a nested if construct, you can have an if...elif...else
construct inside another if...elif...else construct.
orange_quality = “fresh”
orange_price = 4.0
if orange_quality == “fresh”:
if orange_price < 5:
print “buy 24.0”
else:
print “buy 12.0”
else:
print “don’t_buy_oranges”
if condition1 = True:
if condition2 = True:
execute code1
elif condition3 = True:
execute code2
else: execute code3
else:
execute code4
Iteration Statements/Looping Statements
 There may be a situation when you need to execute a block of code
several number of times.
 In general, statements are executed sequentially:
 The first statement in a function is executed first, followed by the second
and so on.
 A loop statement allows us to execute a statement or group of statements
multiple times.
Python programming language provides following types of loops to
handle looping requirements
 for loop
Executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
 while loop
Repeats a statement or group of statements while a given condition
is true. It tests the condition before executing the loop body.
 nested loops
You can use one or more loop inside any another while or for
for loop
 The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
 Iterating over a sequence is called traversal.
 Syntax of for Loop
for val in sequence:
body of for
 Here, val is the variable that takes the value of the item
inside the sequence on each iteration.
 Loop continues until we reach the last item in the
sequence. The body of for loop is separated from the rest of
the code using indentation.
for letter in 'Python':
print “Current Letter” : letter
OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print 'Current fruit :', fruit
print "Good bye!“
OUTPUT:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
The range() function
 We
can
generate
using range() function.
a
sequence
of
numbers
 range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not
provided.
 This function does not store all the values in memory, it
would be inefficient. So it remembers the start, stop, step
size and generates the next number on the go.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(2,8)
[2, 3, 4, 5, 6, 7]
>>> range(2,20,3)
[2, 5, 8, 11, 14, 17]
 We can use the range() function in for loops to iterate through a
sequence of numbers.
 It can be combined with the len() function to iterate though a
sequence using indexing
#sample program
genre = ['pop','rock','jazz‘]
for i in range(len(genre)):
print("I like",genre[i])
while loop
 The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true.
 We generally use this loop when we don't know
beforehand, the number of times to iterate.
Syntax of while Loop:
while test_expression:
body of while
 In while loop, test expression is checked first
 The body of the loop is entered only if the test expression evaluates
to True.
 After one iteration, the test expression is checked again. This process
continues until the test expression evaluates to False.
 In Python, the body of the while loop is determined through
indentation.
 Body starts with indentation and the first unindented line marks
the end
n = int(input("Enter limit: "))
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
print "The sum is", sum
OUTPUT:
Enter limit
5
The sum is 15
break and continue Statement
[loop control statements]
 In Python, break and continue statements can alter the
flow of a normal loop.
 Loops iterate over a block of code until test expression is
false, but sometimes we wish to terminate the current
iteration or even the whole loop without checking test
expression.
 The break and continue statements are used in these
cases.
break statement
 The break statement terminates the loop containing it.
 Control of the program flows to the statement immediately
after the body of the loop.
 If it is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
for val in "string":
if val == "i":
break
print val
print "The end“
OUTPUT:
s
t
r
continue statement
 The continue statement is used to skip the rest
of the code inside a loop for the current iteration
only.
 Loop does not terminate but continues on with
the next iteration.
for var in "string":
if var == "i":
continue
print var
print "The end“
OUTPUT:
s
t
r
n
g
Nested for loop
Nested while loop