Python(MASAI) Module 2
Python(MASAI) Module 2
● The character # as a comment, i.e., it simply ignores this text as it is intended for humans and not
the computer.
● Three dots (...) in the command-line environment appears when Python is expecting more input.
● In the IDLE convention, the prompt following a comment is still >>>, showing an interactive session
Command Line Sessions: File Editor
Bugs
Data and Types: Literals
A literal is code that exactly represents a value, can be:
● Numeric
○ Integer (int)
○ Float (float)
○ Complex (complex)
○ Boolean (bool)
● Non-Numeric
○ Textual/Char (str/char)
○ List (list)
○ Tuples (tup)
○ Dictionary (dic)
Image by Mudassar Iqbal and Elias from Pixabay
Data and Types: Literals
Floating point float Numbers with decimal point; 2.3, 5.0, 100.01
Variable: names that you can assign values to and reuse later on
● Name of a variable X
1028 1
● For programmer’s ease 1032
52311 My_number
1036
.
- 534 myNumber
Variable type
.
.
● Defines kind of data .
.
.
● 4 bytes (32 bits) for an
integer x≠0, s.t. |x| < 1073741824
Variables: Memory Allocation
Static Dynamic
Variables and
method labels
Value objects
Ref_Count
Expression
Response
Overwriting
Variable b does not “remember” that its value came from variable a.
“Hello”
Computer Memory
Memory Segment Update
Variable Assignment: Example
Variables: Memory Allocation
● Name of a variable X
1028 1
● For programmer’s ease
Command Line
Variable type
Variable type
Variable type
s e - 1023
Memory location is given n = (-1) * 2 * (1+f)
● Name of a variable s=1
● For programmer’s ease
Variable type e = 1*210 + 0*29 + …
Tips:
- Descriptive: my_number for a number, myString for a string etc.
- Consistent: myNumber or my_number
- Traditions: avoid starting with _, start with lowercase
- keep them short
Identifiers: Assignments
In addition to assigning names to values (or objects), there are other entities, such as functions
and classes, for which programmers must provide a name, called identifiers.
Keywords
Reserved words that have special meaning and cannot be used as an identifier.
import keyword;
print(keyword.kwlist).
Keywords
*If an identifier had previously been used, the old association is forgotten when a new value is assigned to it.
Keyword Recovery: Recover the built-in function by deleting, using the del() function,
Questions
● What types of values can a variable hold in Python? Give examples for
different types.
● How did the stored program concept change the way computers were
used and programmed compared to earlier machines?
● _3 = 3 ?
Operators in Python
Operations and Operators
The operator / always represents float division while // is always used for floor division.
Operators Associativity
Preference
( ), [ ], { } left to right
** right to left
+, - left to right
or left to right
Arithmetic Operations: Questions?
1.
2.
3.
Are they Equivalent ?
Formatting Code
Relational Operators
Relational operators always return a boolean result that indicates whether some relationship holds
between their operands
Relational Operators: Identity and Inclusion
Compares the memory locations of two objects
Validate the membership of the query object within the given sequence such as string, list or tuples
Logical Operators
1’s Complement
➔ Signed representation
➔ Swap 0 with 1 and 1 with 0, and then append 1 on left as sign bit
➔ ~5 -> 101 -> swap -> 010 -> append sign bit -> 1010
1 0 1 0 1 1 0 1 0
➔ Binary to Integer:
-8 4 2 1 -16 8 4 2 1
➔ Signed representation
➔ Swap 0 with 1 and 1 with 0, and then append 1 on left as sign, then add 1
➔ ~5 -> 101 -> swap -> 010 -> append 1 -> 1010 -> then add 1 -> 1011
➔ Binary to Integer:
➔ Subtract 1, Remove 1 from left, and then swap 0 with 1 and 1 with 0,
➔ ~[(~5 + 1) - 1] = 5
Bitwise Operations
True << 1
Left Shift <<
True << 3
Bitwise Operations
True << 1 2
Left Shift <<
True << 3 8
Bitwise Operations
True << 1 2
Left Shift <<
True << 3 8
OR | 2|5 7
Bitwise Operations
OR | 2|5 7
XOR ^ 2^7 5
Bitwise Operations
OR | 2|5 7
XOR ^ 2^7 5
NOT ~ ~5 ?
Bitwise Operations
OR | 2|5 7
XOR ^ 2^7 5
NOT ~ ~5 -6
Bitwise Operations
OR | 2|5 7
XOR ^ 2^7 5
NOT ~ ~5 -6
0000010
1
1111101
0
Bitwise Operations
OR | 2|5 7
XOR ^ 2^7 5
NOT ~ ~5 -6
OR | 2|5 7
XOR ^ 2^7 5
NOT ~ ~5 -6
5 >> 1 2
Right >>
Shift 5 >> 2 1
Questions
● What will the bitwise operation XOR return when applied to ‘12’ and ‘25’,
● What will the bitwise OR and AND operations return when applied to ‘12’ and
‘25’ ?
● What is the result of right-shifting & left-shifting the number 'x' by 2 positions
? Answer in terms of x, 2^n.
● What is the relationship between the bitwise NOT operation and the two's
complement of a number in Python ?
String Operations
0 1 2 3 4 5 6 Forward Counting
Data = “Lucknow” L u c k n o w
-7 -6 -5 -4 -3 -2 -1 Backward Counting
a = "Hello, World!"
print(a[1]) ?
Special
Characters
String Operations: Formatted String
● A formatted string literal (or f-string) is a string literal that is prefixed with "f" or
"F". A replacement field is an expression in curly braces ({ }) inside an f-string.
Syntax : input(prompt)
Function: Analogy
“Do Something”
● Arguments
○ Parentheses
○ Separated by commas
● Output
● Printing multiple arguments in same line and auto
conversions
● Return the object
● def is a key word used to “define” a block of executable code Code within the
def block is not available to the interpreter until called.
● def creates a function object and assigns the object to the name of the
function.
● def can appear as a separate code block in the same python file, or inside a
loop or condition or even within another function (enclosed).
● lambda creates a function object as well, but it has no name. Instead it
simply returns the result of the function.
Defining A Function: Start
Function
definition
begins with
“def.”
Defining A Function: Start
Function
definition Function name and its arguments
begins with
“def.”
Defining A Function: Start
The indentation
matters…………..
Defining A Function: Start
The indentation
matters…………..
Colon
The indentation
matters…………..
● When a function is called the flow of the main program stops and sends the
“control” to the function.
● No code in the main program will be executed as long as the function has the
control.
● Function “returns” the control to the main program using the return statement.
● Every function has an implicit return statement.
● We can use the return statement to send a value or object back to the main
function.
● Since return can send back any object you can send multiple values by
packing them into a tuple.
Calling A Function
Output:
Calling A Function
Output:
Calling A Function
Output:
Function Without Return
All functions in Python have a return value, even if no return line inside the
code
If no return statement is present, execution continues until the end of the body, at
which point execution returns to the point in the program where the function was
called.
Function: Examples
Function Call Output
float("3.14") 3.14
int("41") 41
str(12.312) '12.312'
Function: Examples
Function: Print() vs Return()
Function: Call Stack Frame
Stack
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Function: Call Stack Frame
Stack Heap
Line 9 prints the contents of the out variable (here, 6). After it
runs, the main function is complete and the program is
finished
String Methods
String Methods
text[0]
text[len(text) - 1]
# len() is a function used to retrieve the length of a string in the
parentheses
➔ What happens if we try an index outside of the string?
text[len(text)]
String Methods
➔ Return a string
String
Str = “HELLO”
Method
Str.lower( )
Result
hello
String Methods: Called without string
String Methods: Transforming Strings
str. lower ( ) Returns a copy of str with all letters converted to lowercase.
str. upper ( ) Returns a copy of str with all letters converted to uppercase.
str. capitalize ( ) Capitalize the first character in str and converts the rest to lowercase.
str. title ( ) Returns a copy of str with first character of each word capitalized.
str. swapcase ( ) Returns a copy of str with the case of its alphabetic characters
swapped.
str. replace (old, new ) Returns a copy of str with all instances of old replaced by new.
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.lower( ) 'anyone can learn python, python is so easy. best way to learn python
is using it for different tasks.'
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.lower( ) 'anyone can learn python, python is so easy. best way to learn python
is using it for different tasks.'
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.lower( ) 'anyone can learn python, python is so easy. best way to learn python
is using it for different tasks.'
statement.capitalize( ) 'Anyone can learn python, python is so easy. best way to learn python
is using it for different tasks.'
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.title( ) 'Anyone Can Learn Python, Python Is So Easy. Best Way To Learn
Python Is Using It For Different Tasks.'
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.title( ) 'Anyone Can Learn Python, Python Is So Easy. Best Way To Learn
Python Is Using It For Different Tasks.'
statement.strip( ) 'Anyone can learn python, python is so easy. Best way to learn python
is using it for different tasks.'
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is using it
for different tasks."
statement1= " Anyone can learn python, python is so easy. Best way to learn python is using
it for different tasks. "
statement.title( ) 'Anyone Can Learn Python, Python Is So Easy. Best Way To Learn
Python Is Using It For Different Tasks.'
statement1.strip( ) 'Anyone can learn python, python is so easy. Best way to learn python
is using it for different tasks.'
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is using it
for different tasks."
statement1= " Anyone can learn python, python is so easy. Best way to learn python is using
it for different tasks. "
statement.title( ) 'Anyone Can Learn Python, Python Is So Easy. Best Way To Learn
Python Is Using It For Different Tasks.'
statement1.strip( ) 'Anyone can learn python, python is so easy. Best way to learn python
is using it for different tasks.'
statement1.rstrip( ) ' \tAnyone can learn python, python is so easy. Best way to learn
python is using it for different tasks.'
String Methods: Transforming Strings
statement = "Anyone can learn python, python is so easy. Best way to learn python is using it
for different tasks."
statement1= " Anyone can learn python, python is so easy. Best way to learn python is using
it for different tasks. "
statement1.strip( ) 'Anyone can learn python, python is so easy. Best way to learn
python is using it for different tasks.'
statement1.rstrip( ) ' \tAnyone can learn python, python is so easy. Best way to
learn python is using it for different tasks.'
statement.replace('python', 'coding', 2 ) 'Anyone can learn coding, coding is so easy. Best way to learn
python is using it for different tasks.'
String Methods: Slicing
String Methods: Slicing
'tnereffid rof ti gnisu si nohtyp nrael ot yaw tseB .ysae os si nohtyp ,nohtyp nrael nac enoynA'
String Methods: Slicing
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
# Gives Error
str. fnd ( pattern ) Returns the first index of pattern in str or -1 if it does not appear.
str. find ( pattern , k) Same as above but start searching the pattern with index k.
str. rfind( pattern ) Returns the last index of pattern in str or -1 if it does not appear.
str. rfind( pattern, k ) Same as above but start searches backward the pattern from index k.
str. startswith ( prefix ) Returns TRUE if the str starts with the prefix.
str. endswith ( suffix ) Returns TRUE if the str ends with the suffix.
str. index ( pattern ) Returns the first index of pattern in str or ValueError if it does not appear.
str. __repr__ ( ) Returns a detailed string representation of object in str ; for debugging
String Methods: Finding Patterns and Index
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.find(‘python’ ) 17
String Methods: Finding Patterns and Index
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.find(‘python’ ) 17
statement.index(‘python’ ) 17
String Methods: Finding Patterns and Index
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
statement.find(‘python’ ) 17
statement.index(‘python’ ) 17
statement.count(‘python’ ) 3
String Methods: split() & join()
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
Scope: The region in the program code where variables and names are accessible.
● Namespace is the complete list of names, including all objects, functions, etc.
that exist in a given context.
Scope concept follows the LEGB (Local, Enclosing, Global and built-in) rule.
● The scope of an object is the namespace within which the object is available.
Scope concept follows the LEGB (Local, Enclosing, Global and built-in) rule.
● The scope of an object is the namespace within which the object is available.
● Local first: Look for this name first in the local namespace and use local
version if available. If not, go to higher namespace.
Scope: LEGB Rule
● Global third: Look for the name in the objects defined at global scale (e.g.,
main program).
Scope: LEGB Rule
● Built-in last: Finally, look for the variable among Python’s built-in names.
LEGB Rule: Local Scope
LEGB Rule: Local Scope
LEGB Rule: Local Scope
LEGB Rule: Local Scope
Output
LEGB Rule: Enclosing or Non-Local Scope
LEGB Rule: Enclosing or Non-Local Scope
LEGB Rule: Enclosing or Non-Local Scope
LEGB Rule: Enclosing or Non-Local Scope
LEGB Rule: Enclosing or Non-Local Scope
Output
LEGB Rule: Global Scope
Output
LEGB Rule: Built-In Scope
LEGB Rule: Built-In Scope
LEGB Rule: Built-In Scope
LEGB Rule: Built-In Scope
LEGB Rule: Built-In Scope
LEGB Rule: Built-In Scope
● The objects sent to a function are called its arguments. Arguments are
sometimes also called parameters.
● Passing an object as a argument to a function passes a reference to
that object.
● Argument names in the def line of the function become new, local
names.
● Arguments are passed in two ways:
○ ‘Immutables’ are passed by value eg., String, Integer, Tuple
○ ‘Mutables’ are passed by reference eg., Lists
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Output
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
Function: Arguments
op
add
x 2
y 3
Function: Arguments
op
add a 2
x 2 b 3
y 3
Function: Arguments
op
add a 2
x 2 b 3
y 3
returns 5
Function: Arguments
op
add
x 2
y 3
returns 5
Function: Arguments
5
Function As Arguments: Questions
Function As Arguments: Questions