0% found this document useful (0 votes)
13 views190 pages

Python(MASAI) Module 2

The document provides an overview of Python programming concepts, focusing on data types, variables, operators, and memory allocation. It explains literals, variable assignments, and the use of operators in Python, including arithmetic, relational, logical, and bitwise operations. Additionally, it covers string operations and the rules for naming variables in Python.

Uploaded by

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

Python(MASAI) Module 2

The document provides an overview of Python programming concepts, focusing on data types, variables, operators, and memory allocation. It explains literals, variable assignments, and the use of operators in Python, including arithmetic, relational, logical, and bitwise operations. Additionally, it covers string operations and the rules for naming variables in Python.

Uploaded by

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

Data and Variables

String and Functions


Python for Data Science & Artificial Intelligence

Instructor: Dr. Sneha Singh, SCEE


Term : June 2025
Data and Algorithms
Command Line Sessions

● 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

Name Type Description

Integers int Whole numbers; 3, 5, 69, -2

Floating point float Numbers with decimal point; 2.3, 5.0, 100.01

Character str A single character string my_char = 'a' # my_string = "hello"

Strings str Ordered sequences of characters; “hello”, “Good Morning”

List list Ordered sequence of objects; [100, “hello”, 5.0]

Dictionaries dict Unordered key:value pairs; {“Country”:”India”, “Name”:”Sneha”}

Tuples tup Ordered immutable sequence of objects; (100, “hello”, 5.0)

Sets set Unordered collection of unique objects; {“a”, “b”}

Booleans bool Logical values indicating; TRUE, FALSE


Data and Algorithms
Python Vocab

Program: file of code that may contain one or more functions

Variable: names that you can assign values to and reuse later on

Operators: Mathematical symbols, like +, -, *, /, and **

Comments: notes ignored by the computer (#)

Indentation: the whitespace (spaces) at the beginning of a code line

Keywords: “and”, “print”, and “if”

Function: built-in, and “user-defined”. Reusable piece of program


Python Vocab: Example

Command Console Variable Explorer


Variables: Memory Allocation

Memory location is given ADDRESS DATA VARIABLE

● 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

Methods and References are created in the stack


memory. Whereas Objects are created in heap
memory.
Variable Assignment: Example
Assignment

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

Memory location is given ADDRESS DATA VARIABLE

● Name of a variable X
1028 1
● For programmer’s ease

Command Line
Variable type

● Defines kind of data

● 4 bytes (32 bits) for an


integer x≠0, s.t. |x| < 1073741824

● 8 bytes (64 bits) for float


Variables: Memory Allocation
ADDRESS DATA VARIABLE

Memory location is given


1028 - 1073741823 X
● Name of a variable

● For programmer’s ease


Used to determine the size of an
object in bytes

Variable type

● Defines kind of data

● 4 bytes (32 bits) for an


integer x≠0, s.t. |x| < 1073741824

● 8 bytes (64 bits) for float


Variables: Memory Allocation
ADDRESS DATA VARIABLE
Memory location is given
1028 - 1073741823 X
● Name of a variable

● For programmer’s ease


Command Line

Variable type

● Defines kind of data

● 4 bytes (32 bits) for an


integer x≠0, s.t. |x| < 1073741824

● 8 bytes (64 bits) for float


Variables: Bit Allocation
IEEE 754 standard
1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 . . .

sign exponent fraction


(1 bit) (11 bits) (52 bits)

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 + …

● Defines kind of data f = 1*2-1 + 1*2-2 + 0*2-3 + …


● 4 bytes (32 bits) for an
integer x≠0, s.t. |x| < 1073741824
n = (-1)1 * 21024-1023 * (1+ 0.5 + 0.25)
● 8 bytes (64 bits) for float = - 3.5
Variables: Assignments

Rules for variable names in python:


- Can only contain letters, numbers, and underscores.
- Can not start with a number

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.

The 33 keywords in Python 3.

import keyword;
print(keyword.kwlist).
Keywords

So, can we have a variable named print ?

*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

● How do we define a variable in Python, and why do we use one ?

● 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?

● Can 0s be variable name?

● Will following statement give error in python, why?

● _3 = 3 ?
Operators in Python
Operations and Operators

Operators can be defined as symbols that are used to perform operations on


operands; can be unary or binary operators.

These operators are classified into four categories:

● Arithmetic (+, -, *, / , // ,%, **)


● Relational (== , !, =, < , >, <=, >=, is, in)
● Logical (and, not, or)
● Bitwise (&, |, ~, ^, <<, >>)

Operators uses a header-like notation called a “prototype”, includes the symbol/name of


the operator, the type(s) of its operand(s), and the type of result it returns; < (int, int) -> bool
Arithmetic Operations
Arithmetic Operations: Examples
Additional Arithmetic Operations: Exponents
Additional Arithmetic Operations: Floor Division

The operator / always represents float division while // is always used for floor division.

The quotient is a whole number.


Arithmetic Operations: Precedence/Associativity

Operators Associativity
Preference

( ), [ ], { } left to right

func( ), array[ ] left to right

** right to left

/, //, %, * left to right

+, - left to right

<, <=, >, >=, !=, == left to right

not left to right

and left to right

or left to right
Arithmetic Operations: Questions?

1.

Augmented Assignment (for interactive environment): x = x + 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

➔ -8*1 + 4*0 + 2*1 + 1*0 = -6


➔ Reverse of 1’s complement:
➔ Remove 1 from left, and then swap 0 with 1 and 1 with 0,
➔ ~~5 = 5
2’s Complement

➔ 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:

➔ Reverse of 2’s complement:

➔ Subtract 1, Remove 1 from left, and then swap 0 with 1 and 1 with 0,

➔ ~[(~5 + 1) - 1] = 5
Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False
Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False False
Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & True False

OR | True | False True


Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False False

OR | True | False True

XOR ^ True ^ False True


Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False False

OR | True | False True

XOR ^ True ^ False True

NOT ~ ~ True False


Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False False

OR | True | False True

XOR ^ True ^ False True

NOT ~ ~ True False

True << 1
Left Shift <<
True << 3
Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False False

OR | True | False True

XOR ^ True ^ False True

NOT ~ ~ True False

True << 1 2
Left Shift <<
True << 3 8
Bitwise Operations

Operation Python Operator Example Evaluates To


AND & True & False False

OR | True | False True

XOR ^ True ^ False True

NOT ~ ~ True False

True << 1 2
Left Shift <<
True << 3 8

Right Shift >> True >> 1 0


Bitwise Operations
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7

XOR ^ 2^7 5
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7

XOR ^ 2^7 5

NOT ~ ~5 ?
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7

XOR ^ 2^7 5

NOT ~ ~5 -6
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7

XOR ^ 2^7 5

NOT ~ ~5 -6

0000010
1
1111101
0
Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7

XOR ^ 2^7 5

NOT ~ ~5 -6

Left Shift << 2<< 1 4


Bitwise Operations

Operation Python Example Evaluates To


Operator
AND & 2&3 2

OR | 2|5 7

XOR ^ 2^7 5

NOT ~ ~5 -6

Left Shift << 2<< 1 4

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 would be 1’s Complement range in 4-bits ?

● 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

● String: Sequence or List of characters

● Starting from index value 0 to N-1, for a string of length N.

● Enclosed inside the quotes; single, double, triple.

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

● Concatenation consists of combining two strings end to end with no


intervening characters

● Concatenation is built into Python in the form of the + operator.

"la" + "te" = "late"

● Python redefines the * operator for strings to indicate Repetition.


● The expression s * n indicates n copies of the string s concatenated together.

"la" * 3 = "la" + "la" + "la"


String Operations: Example
String Operations: F 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.

What is the output of the following code?


animal = "dog"
says = "bark"

print(f"My {animal} says {says} {says} {says}")

Output: My dog bark bark bark bark


Functions
Functions
Functions

● The print ( ) function displays output to the user.


● Output is the information or result produced by a program.

Syntax : print(value(s), sep= ' ', end = '\n', file=file, flush=flush)


Functions

Whatever you enter as input, the


input function converts it into a
string.
Prompt

● The input ( ) function is what a user enters into a program.


● A prompt is a short message that indicates the program is waiting for input.

Syntax : input(prompt)
Function: Analogy

A function is a block of code which only runs when it is called.


Function: Analogy

A function is a block of code which only runs when it is called.

You can pass data, known


as parameters/arguments,
into a function.
Function: Analogy

A function is a block of code which only runs when it is called.

You can pass data, known A function can return


as parameters/arguments, data as a result
into a function.
Function: Analogy

A function is a block of code which only runs when it is called.

“Do Something”

You can pass data, known A function can return


as parameters/arguments, data as a result
into a function.
Function: Analogy

● Arguments
○ Parentheses
○ Separated by commas
● Output
● Printing multiple arguments in same line and auto
conversions
● Return the object

A function is not executed when it is defined.


Defining A Function: Start
Defining A Function: Start

● 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

Function Function name and its arguments


definition
begins with
“def.”

The indentation
matters…………..
Defining A Function: Start

Function Function name and its arguments


definition
begins with
“def.”

The indentation
matters…………..

‘return’ indicates the value to be sent


back to the caller
Defining A Function: Start

Function Function name and its arguments


definition
begins with
“def.”

Colon
The indentation
matters…………..

‘return’ indicates the value to be sent


back to the caller
Control flow: Call & Return

● 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

The syntax for a function call is:

● Parameters in Python are Call by Assignment


● Old values for the variables that are parameter names are hidden, and these
variables are simply made to refer to the new values
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

● Functions without a return, return the special value None


● None is a special constant in the language
● None is used like NULL, void, or nil in other languages
● None is also logically equivalent to False
● The interpreter’s REPL doesn’t print None

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

n = 4, 2; Define the argument values of f first

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

Output: 1023.4[1, ’a’, [2, 3]]Hi!


String Methods: Indexing
text = “abc123”
➔ How do we get the first character in a string?

text[0]

➔ How do we get the last character in a string?

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

➔ Are similar to functions as they have parenthesis in the end

➔ Return a string

➔ Must be called along with a string

➔ May or may not involve arguments

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. strip ( ) Removes whitespace characters from both ends of str.


.lstrip ( ) OR .rstrip ( )

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

Method Call Output

statement.upper( ) '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."

Method Call Output

statement.upper( ) '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."

Method Call Output

statement.upper( ) '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.swapcase( ) '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."

Method Call Output

statement.upper( ) '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.swapcase( ) '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."

Method Call Output

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

Method Call Output

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

Method Call Output

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

Method Call Output

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

Method Call Output

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

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

● Obtaining a whole substring from a string by specifying a slice.


● Slices are exactly like ranges – they can have a start, an end, and a step.
● Slices are represented as numbers inside of square brackets, separated by
colons. Slice —> Str [start : stop : step]
Default Settings:
Start: s[0]
Stop: s[len(s)] ; # include len(s)-1 character but exclude len(s) character
Step: 1
s[: :] or s[:] = Evaluates to s[0:len(s):1]; "abcdefgh"
s = "abcdefgh" s[: : -1] = Evaluates to s[len(s)-1: :-1]; "hgfedcba"
s[3:6:2] = Evaluates to "df"
String Methods: Slicing
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
String Methods: Slicing
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."
String Methods: Slicing
statement = "Anyone can learn python, python is so easy. Best way to learn python is
using it for different tasks."

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

****Strings are Immutable.****


String Methods: Immutable Strings

● Strings are “immutable” – cannot be modified


● You can create new objects that are versions of the original one
● Variable name can only be bound to one object

# Gives Error

# Allowed; s is bound to new object


Exercise: Slicing

Suppose that you have initialized ALPHABET as


ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
so that the index numbers (in both directions) run like this:

What are the values of the following slice expressions?


1. ALPHABET[7:9] 5. ALPHABET[1:-1]
2. ALPHABET[-3:-1] 6. ALPHABET[0:5:2]
3. ALPHABET[:3] 7. ALPHABET[::-1]
4. ALPHABET[-1:] 8. ALPHABET[5:2:-1]
5. ALPHABET[14:-12] 9. ALPHABET[14:2:-3]
String Methods: Finding Patterns and Index
*Search is case-sensitive

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

Method Call Output

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

Method Call Output

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

Method Call Output

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

Method Call Output

statement.split( ) [‘Anyone’, ‘can’, ‘learn’, ‘python’, ‘,’, ‘ python’, ‘is’,


If no argument is given, the splitting is done at every ‘so’, ‘easy’, ‘.’, ‘Best’, ‘way’, ‘to’, ‘learn’, ‘python’, ‘is’,
whitespace occurrence ‘using’, ‘it’, ‘for’, ‘different’, ‘tasks.’]
“ ”.join([“smashed”, “together”]) ‘smashed together’

“-”.join([“one”, “by”, “one”]) ‘one-by-one’


String Methods: Format Specifiers
String Methods: Membership
String Methods: Membership
String Methods: Membership
String Methods: Membership
String Methods: Membership
String Methods: Membership
String Methods: Membership
Function: Scope
Scope: Role of Functions
Function: Namespace

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.

● Whenever we use a name, such as a variable or a function name, Python


searches through different scope levels (or namespaces) to determine whether
the name exists or not.
○ Built-in Namespace: functions or exceptions that have already built
○ Global Namespace: Available through main program
○ Local Namespace: Within the function
Scope: Accessibility

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.

● Access depends on where the name is defined


Scope: LEGB Rule

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.

● Access depends on where the name is defined


Scope: LEGB Rule

● 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

● Enclosing second: If the current function is enclosed within another function


(nested functions), look for the name in that outer function. 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

Local scope of outer ( ) is the enclosing scope of inner ( )


LEGB Rule: Enclosing or Non-Local Scope

Local scope of outer ( ) is the enclosing scope of inner ( )


LEGB Rule: Global Scope
LEGB Rule: Global Scope
LEGB Rule: Global Scope
LEGB Rule: Global Scope
LEGB Rule: Global 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

Remember: do not redefine built-in names!


Function: Arguments
Function: Argument Passing

● 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

You might also like