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

Introduction2Python 2

The document serves as an introduction to Python programming, detailing its structure, interpreter, and key features such as dynamic typing and ease of use. It covers fundamental programming concepts, including naming conventions, data types, control flow, and examples of Python code. Additionally, it contrasts Python with compiled languages, highlighting the advantages and limitations of interpreted languages.

Uploaded by

ramaseshan.nlp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Introduction2Python 2

The document serves as an introduction to Python programming, detailing its structure, interpreter, and key features such as dynamic typing and ease of use. It covers fundamental programming concepts, including naming conventions, data types, control flow, and examples of Python code. Additionally, it contrasts Python with compiled languages, highlighting the advantages and limitations of interpreted languages.

Uploaded by

ramaseshan.nlp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Advanced Programming

Introduction to Python

Ramaseshan Ramachandran

ADPG 1 / 80
String
1 Program Structure
List
2 Naming Conventions
Tuples
3 Python Dictionary
4 Basics generators
5 Python Objects 6 References

ADPG 2 / 80
INTRODUCTION TO PYTHON INTERPRETER

I Python is an interpreted language, where the code is executed line-by-line.


I The interpreter consists of:
I Tokenizer (Lexer): Splits source code into tokens
I Parser: Constructs an Abstract Syntax Tree (AST)
I Bytecode Compiler: Converts the AST into bytecode.
I Python Virtual Machine (PVM): Executes bytecode at runtime
I Modes
I Interactive Mode: Executes commands interactively.
I Script Mode: Executes pre-written scripts.

ADPG 3 / 80
INTERPRETED AND COMPILED LANGUAGES
Aspect Python (Interpreted) Compiled Languages

Execution Process Line-by-line translation Pre-compiled into ma-


chine code
Performance Slower (runtime inter- Faster (optimized ma-
pretation) chine code)
Output Bytecode (.pyc) Executables (.exe, .bin)
Error Handling Runtime errors Compile-time errors
Platform Dependency Platform-independent Platform-dependent
(PVM required) (hardware-specific)
Flexibility Supports runtime Static typing (strict type
changes (dynamic typ- declarations)
ing)
Examples Python, Ruby, JavaScript C, C++, Rust, Go
ADPG 4 / 80
ADVANTAGES OF PYTHON INTERPRETER

I Ease of Use: No compilation step required


I Portability: Byte code runs on any platform with a Python interpreter
I Dynamic Features: Allows runtime type-checking and dynamic execution

ADPG 5 / 80
LIMITATIONS OF PYTHON INTERPRETER

I Speed: Slower due to line-by-line execution


I Error Detection: Errors detected only during runtime
I Resource Intensity: Requires more memory and processing power

I Python interpreter prioritizes development speed and flexibility


I Compiled languages prioritize execution efficiency and performance

ADPG 6 / 80
COMMON STRUCTURES

I Preprocessor directives (optional): Instructions for the compiler or


interpreter, often used for header files or conditional compilation
I Declarations: Definitions of variables, functions, and other elements,
specifying their names and data types.
I Functions:Reusable blocks of code that perform specific tasks, often with
parameters and a return value.
I Main function:The entry point of the program, where execution begins.
I Statements: Instructions that perform actions, such as assignments,
calculations, input/output, and control flow.
I Control structures: Statements that control the flow of execution, such as
conditional statements (if/else) and loops (for/while)
I Comments: Non-executable text explaining code functionality

Program Structure ADPG 7 / 80


SAMPLE CODE IN PYTHON

def main ():


# Declarations
x = 10 #not the best way to name a variable
y = 5

# Statements
sum = x + y
print ("The sum is:", sum)

# Call the main function to start execution


# Entry point
if __name__ == " __main__ ":
main ()
Program Structure ADPG 8 / 80
SAMPLE CODE IN C
# include <stdio.h>

// Entry point
int main () {
// Declarations
int x = 10;
int y = 5;

// Statements
int sum = x + y;
printf ("The sum is: %d\n", sum );

return 0;
}
Program Structure ADPG 9 / 80
SAMPLE CODE IN SWIFT

// Entry point
func main () {
// Declarations
var x = 10
var y = 5

// Statements
let sum = x + y
print("The sum is: \( sum)")
}

main ()

Program Structure ADPG 10 / 80


SAMPLE CODE IN RUST

// Entry point
fn main () {
// Declarations
let x = 10;
let y = 5;

// Statements
let sum = x + y;
println !("The sum is: {}", sum );
}

Program Structure ADPG 11 / 80


NAMING CONVENTIONS
Set of rules for choosing names for variables, functions, classes, and other elements in code
Naming Explanation Examples
Conventions
Camel Case First word in lowercase, subsequent firstName, lastName, middleName,
words start with uppercase totalBalance
Pascal Case All words start with uppercase. Of- FirstName, LastName, MiddleName,
ten used for class names, enums, and TotalBalance
sometimes functions.
Snake Case Words separated by underscores. first_name, last_name, middle_name,
Common in Python, C++, and other total_balance
languages
Kebab Case Words separated by hyphens. Used in first-name, last-name, middle-name,
file paths, URLs, and sometimes code total-balance
elements
Hungarian Prefixes encode data type. Less com- strName, intAge, btnSubmit
Notation mon in modern practice due to poten-
tial for confusion
Naming Conventions ADPG 12 / 80
NAMING CONVENTIONS - OFFICIAL GUIDES

Python Official Python Style Guide

Naming Conventions ADPG 13 / 80


PROGRAM STRUCTURE IN PYTHON

Entry point Starting point of the program’s execution


Declarations Statements that define variables, constants, functions, or
other program elements
Statements Instructions that perform actions or calculations
Control Elements that control the flow of execution, such as con-
Structure ditional statements (if/else) and loops (for/while)
Comments Non-executable text explaining functionality of the code
(for self and co-developer’s understanding)

Naming Conventions ADPG 14 / 80


FUNDAMENTAL (PRIMARY) SCALAR OBJECTS

Scalar Objects Explanation Examples


Integer type Signed and unsigned values no_students = 29
Float Represents decimal values pi = 3.142
String Holds sequence of characters name =’Whats in a name’
Boolean Logical type (True or False) is_awake = False
None Type Absence of a value ipl_tickets = None

Python ADPG 15 / 80
OPERATIONS ON THE SCALAR TYPES

Operations Operators
Arithmetic operations + − /%
Equality Checks == and ! = operators
Ordering <, >, <=, and >= operators (except for None Type)
Type Checking type() function
Type Conversion int(), float(), and str()

Python ADPG 16 / 80
INPUT AND OUTPUT STATEMENTS

if __name__ == '__main__ ':


first_name = input ('Enter First Name: ')
last_name = input ('Enter Last Name: ')
print (first_name ,' ', last_name )

print ('First name is ' + first_name + 'and ' + \


'Last name is ', last_name )

# What happens in this code segment ?


# Error free?
x = input ('Enter x value as int: ')
y = input ('Enter y value as int: ')
print (x+y)

Python ADPG 17 / 80
INDENTATION

I Code blocks in Python are Statements ending with colon(:)


indented I Function blocks
I Many languages use braces {} for
I Control flow statements
blocks, but Python relies only on
I with statement
indentation for code blocks
I Enhances code readability I Dictionary definition
I Recommended spaces for I for, while loops
indentation is 4 (four). Remain I Array slicing
consistent in the indentation 1
I Do not mix spaces and tabs -
configure tab as 4 spaces instead
of
tab

1 ManyPython
IDEs ADPG of spaces can be configured)
convert tabs into spaces (the number 18 / 80
INDENTATION EXAMPLE

def indent_code () -> str:


# Indented code within the function
print ('This is inside the function ')

for i in range (5):


# Indented code within the loop
print (i)

return 'done '

Python ADPG 19 / 80
IDENTIFIERS IN PYTHON

An identifier is the name used to


identify variables, functions,
classes, or other objects in Python.

Basics ADPG 20 / 80
RULES FOR CREATING IDENTIFIERS

I Must start with a letter (a-z, A-Z) or an underscore _


I Can contain letters, digits (0-9), and underscores (_).
I Cannot be a reserved keyword or built-in constant (e.g., True, None).
I Case-sensitive (e.g., myVar and myvar are different).
Examples
I Valid: my_variable, _temp, sum1
I Invalid: a − b, 1variable, $x, class (reserved keyword)

Basics ADPG 21 / 80
A SIMPLE BNF FOR PYTHON IDENTIFIER

<identifier > ::= <letter > <identifier_tail > | "_"


<identifier_tail >
<identifier_tail > ::= <letter_or_digit > <identifier_tail > | 
<letter_or_digit > ::= <letter > | <digit >
<letter > ::= "a" | "b" | "c" | "d" | "e" | "f" | "g" |
"h" | "i" | "j" | "k" | "l" | "m" | "n" |
"o" | "p" | "q" | "r" | "s" | "t" | "u" |
"v" | "w" | "x" | "y" | "z" |
"A" | "B" | "C" | "D" | "E" | "F" | "G" |
"H" | "I" | "J" | "K" | "L" | "M" | "N" |
"O" | "P" | "Q" | "R" | "S" | "T" | "U" |
"V" | "W" | "X" | "Y" | "Z"
<digit > ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" |
"7" | "8" | "9"

Basics ADPG 22 / 80
INTERPRETER
Definition
An interpreter directly executes programming code without prior
compilation
Key Features
I Executes code line-by-line or statement-by-statement
I Does not produce a standalone executable file
Advantages
I Easier to debug: Errors are reported immediately
I Supports interactive development: Allows real-time testing in Read-Eval-Print
Loop (REPL) environments.
Disadvantages
I Slower execution speed compared to compiled programs
I Requires the interpreter to be installed on the target system
Examples of Interpreted Languages
Python, JavaScript, Ruby, PHP
Python Objects ADPG 23 / 80
···

Python Objects ADPG 24 / 80


PYTHON OBJECTS I

Definition:
In Python, everything is an object - all data and code structures are instances
of classes
I Objects can represent:
I Data structures (e.g., integers, strings, lists, dictionaries).
I Functions, modules, and even classes themselves.
Key Features of Objects:
I Each object has:
I A type, which defines its class (e.g., int, str)
I A value, which is the data it holds
I A unique identity (retrieved using id())
I Objects can have methods and attributes

Python Objects ADPG 25 / 80


PYTHON OBJECTS II

Examples:
# Example objects in Python
x = 10 # int object
y = "Hello " # str object
z = [1, 2, 3] # list object

# Accessing attributes and methods


print(type(x)) # <class 'int '>
print(len(y)) # 5
print(z. append (4)) # Adds 4 to the list

Python Objects ADPG 26 / 80


DATA TYPES IN PYTHON

Category Data Types

Numeric Types int, float, complex


Sequence Types str, list, tuple
Mapping Type dict
Set Types set, frozenset
Boolean Type bool (True, False)
None Type None

Python Objects ADPG 27 / 80


EXPRESSIONS IN PYTHON I

Definition
An expression in Python is a combination of values, variables, operators,
and function calls that the Python interpreter evaluates to produce a value.
Key Features
I Expressions always return a value.
I Can consist of literals (e.g., 42, "Hello"), variables, or more complex
constructs.
I Commonly used in assignments, function arguments, and control structures.

Python Objects ADPG 28 / 80


EXPRESSIONS IN PYTHON II
I Types of Expressions
I Arithmetic: Combines numbers and operators (e.g., +, -).
I Logical: Evaluates to True or False.
I Function Call: Returns the result of a function.
Examples
>>> x = 42 + 8 # Arithmetic expression
>>> x
50
>>>
# Logical expression
>>> x > 40 and x < 50
False
>>>

Python Objects ADPG 29 / 80


EXPRESSIONS IN PYTHON III

# Function call as an expression


>>> len(" Python ") + 5
11
>>>

Python Objects ADPG 30 / 80


STATEMENTS
Statements are the smallest executable units of code. They perform actions, such as assigning
values, making decisions, or iterating over data.
I Python supports multiple types of statements, including:
I Assignment statements
I Conditional statements
I Looping statements
I Function definitions
Note: In the interpreter, Python executes an expression and prints its result if there is one.
In a script, a sequence of statements is executed, and expressions usually don’t output
values unless printed.

In the interpreter mode When run as script


>>> x = 40 x = 40
>>> x x
40 print(x)
>>> print(x) 40
40
>>>

Python Objects ADPG 31 / 80


EXAMPLES OF PYTHON STATEMENTS

Assignment Statement
x = 10
name = "Ram"
# Conditional Statement
if x > 5:
print ("x is greater than 5")
# Looping Statement
for i in range (5):
print (i)
# Function Definition
def print_name (name ):
print (f"Hello , {name }!")

Python Objects ADPG 32 / 80


CONTROL FLOW IN PYTHON I

Definition
Control flow determines the order in which statements are executed in a
program.
Control Flow Statements
I Conditional Statements:
I if, elif, else to execute code based on conditions.
Loops
I for loop: Iterates over sequences or ranges.
I while loop: Repeats as long as a condition is true.

Python Objects ADPG 33 / 80


CONTROL FLOW IN PYTHON II

I Loop Control
I break: Exits the loop.
I continue: Skips the current iteration.
I pass: Placeholder for empty blocks.

Python Objects ADPG 34 / 80


CONTROL FLOW IN PYTHON III

Exception Handling:
I try, except, finally to manage runtime errors.
I Example
if __name__ == '__main__ ':
file = None
try:
with open('Example .txt ', 'r') as file:
content = file.read ()
print("File content :")
print( content )
except FileNotFoundError :
print("Error : File not found .")
except PermissionError :

Python Objects ADPG 35 / 80


CONTROL FLOW IN PYTHON IV

print("Error : Permission denied .")


finally :
if file:
file. close ()
print("File closed .")
else:
print("File not opened .")
print(" Execution completed .")

Python Objects ADPG 36 / 80


OPERATORS

Operators are symbols that perform operations on variables and values. Python
supports the following types of operators:
I Arithmetic Operators
I Comparison (Relational) Operators
I Logical Operators
I Bit-wise Operators
I Assignment Operators
I Special Operators

Python Objects ADPG 37 / 80


OPERATOR PRECEDENCE IN PYTHON
Operator precedence
determines the order in which operations are evaluated. Higher precedence
operators are evaluated first.

Precedence Operators
1 (Highest) ∗∗ (Exponentiation)
2 +x, -x, ~x (Unary operators)
3 *, /, //, % (Multiplication, Division, Floor Division, Modulus)
4 +, - (Addition, Subtraction)
5 <<, >> (Bitwise shift operators)
6 & (Bitwise AND)
7 |, ^ (Bitwise OR, XOR)
8 ==, !=, >, <, >=, <= (Comparison)
9 not (Logical NOT)
10 and (Logical AND)
11 (Lowest) or (Logical OR)

Python Objects ADPG 38 / 80


EXAMPLE OF PRECEDENCE

Example Code Explanation


result = 2 + 3 * 4 ** 2 1. ∗∗ is evaluated first: 4 ∗ ∗2 = 16.
print ( result ) # Output : 50 2. Then, ∗ is evaluated: 3 ∗ 16 = 48.
3. Finally, + is evaluated: 2 + 48 = 50.

Try this
result = (2 + 3) * 4 ** 2
print ( result ) # Output : ?

Python Objects ADPG 39 / 80


UNARY OPERATIONS

Operator Description Example Output


+ Unary plus (indicates positive) +5 5
- Unary minus (negates value) -5 -5
not Logical NOT (inverts boolean) not True False
~ Bitwise NOT (inverts bits) ~5 -6
Table: Examples of Unary Operators in Python

Python Objects ADPG 40 / 80


STRING
I Python strings are immutable - Once stored, the content is fixed
I They can be modified - Create new strings to reflect changes
I A character in a string can be accessed using [ ]
I Zero-based indexing
I −1 refers to the last character in the string

Interning..

x = 0 hello 0 x = 0 world 0

y=x y=?

x 0 hello 0
x 0 hello 0

y y x 0 World 0

Python Objects ADPG 41 / 80


STRING OPERATIONS
if __name__ == '__main__ ':
my_string = 'hello '

my_string = "hello " "world " # concatenation - valid

# Trying to change a character doesn 't work


my_string [0] = "H" # Error ! Strings are immutable

# length of a string
print (len( my_string ))

# locate the character (s) using indexes


print ( my_string [1]) # output = 'e'

Python Objects ADPG 42 / 80


STRING OPERATIONS
if __name__ == '__main__ ':
sentence = input ('Input a sentence : ')
# Case folding
print (f'All caps: { sentence . upper ()} ')
print (f'All small : { sentence .lower ()} ')
print (f'Title case: { sentence . title ()} ')
print (f'Case folded sentence { sentence . casefold ()} ')
# Slicing
print ( sentence [::])
print ( sentence [0: -1:2])
# reversing
reversed_string = sentence [:: -1]
print (f'Reversed string :', reversed_string )
#Check for Palindrome
#Need to use conditional statement

Python Objects ADPG 43 / 80


STRING SLICING
# slicing -
# extracting parts of a sequence [ start:end:step]
# +---+---+---+---+---+
# | H | e | l | l | o |
# +---+---+---+---+---+
# 0 1 2 3 4
# -5 -4 -3 -2 -1
if __name__ == '__main__ ':
my_string = 'hello '
print ( my_string [2:4])
# output = 'll ' ? What are the start
# and end indexes used?
print ( my_string [:4]) # output = 'hell '
print ( my_string [2:]) # output = ?
#what does the following code do?
print ( my_string ([ -1])

Python Objects ADPG 44 / 80


STRING OPERATIONS

words = sentence . split ()


print (" Number of words :", len( words ))
#title conversion
print ( sentence . title ())

Python Objects ADPG 45 / 80


PROBLEM I

1. Write a program to convert the last character of all the words in a sentence
into capital case. It should not convert single letter, propositions,
conjunctions. Clue: Use the title function and slicing techniques
2. Check whether string is a palindrome. Output True/False
3. Count the frequency of each character in a string and display the result.
4. Write a function to determine if two strings are anagrams of each other.
Example -listen and silent are anagrams
5. Count the frequency of each word in a sentence and output the result for
each word

Python Objects ADPG 46 / 80


PROBLEM II

6. Remove duplicate characters from a string.


7. Reverse the order of words in a sentence and reverse every word
8. Generate all permutations of a string
9. Write a function to encrypt a string using the following rules:
I Reverse the string
I Replace vowels with their ASCII value
I Append the length of the original string at the end
Example: hello  111ll101h5
Note: Use ord() function to get the ASCII value of a character

Python Objects ADPG 47 / 80


PROBLEM III

10. Write a function to decode the string encoded using the previous algorithm
given in 9
11. Write a function to convert a simple Markdown string to HTML. Rules:
I # becomes <h1>, ## becomes <h2>
I *text* becomes <em>text</em>
I **text** becomes <strong>text</strong>.
Key Functions: startswith(), replace()

Python Objects ADPG 48 / 80


PROBLEM IV

12. Given a string and a maximum line width (say 80 characters), wrap the text
to fit within the specified width. Break the text at word boundaries (do not
split words).
13. Find out whether an ISBN-10 string is valid or not
Example: ISBN-10 of 81-85015-96-1 is a valid string. It is verified as follows:
I sum = (8 × 10) + (1 × 9) + (8 × 8) + (5 × 7) + (0 × 6) + (1 × 5) + (5 × 4) + (9 × 3) +
(6 × 2) + (1 × 1)
I if sum mod 11 == 0, then it is a valid ISBN-10 string

Python Objects ADPG 49 / 80


Python Objects ADPG 50 / 80
TEST YOUR UNDERSTANDING
What does the code below print?
s = "6.00 is 6.0001 and 6.0002 "
new_str = ""
new_str += s[-1]
new_str += s[0]
new_str += s [4::30]
new_str += s[13:10: -1]
print ( new_str )
a) 260000 b) 26100 c) 26 100 d) 26 + all
characters
from the index
4
e) Sorry, I did not
review
Python Objects ADPG 51 / 80
CORE DATA TYPES

I Numbers
I Strings
I Lists
I Dictionaries
I Tuple

Python Objects ADPG 52 / 80


GARBAGE COLLECTION

Assume the following code:


x = 'Hello , World !'
x = 5
# what happens to the string
# stored in the memory ?

Garbage collection
I Python automatically manages memory efficiently.
I Objects are removed from memory once their reference count is 0
I Removing dereferenced objects up space is known as garbage collection.

Python Objects ADPG 53 / 80


LIST

I Compound data type 2


I Group of items belonging to the same type or different types
I Items are separated by a comma and enclosed with in square brackets [ ]
I Usually the items in a list have the same type
I Lists are mutable - while mutability is flexible, be mindful of unintended side
effects when modifying lists, as changes can affect other parts of your code
that reference the same list

2 An Informal Introduction to Python


Python Objects ADPG 54 / 80
COMMON OPERATIONS I

I Access Elements using index - list[0]


I Modify Elements - list[index] = new_value
I Add Elements -
I Append: list.append(value)
I Insert: {list.insert(index, value)
I Extend: list.extend([value1, value2])
I Remove Elements
I Remove: list.remove(value)
I Pop: list.pop(index)
I Clear: list.clear()

Python Objects ADPG 55 / 80


COMMON OPERATIONS II

I Search expressions: value in list


list.index(value) returns first index of value
I list.sort() - Sort the list in ascending order and return None. The sort is
in-place
sorted(list) - Returns a new list containing all items from the iterable in
ascending order.

Python Objects ADPG 56 / 80


COMMON OPERATIONS III

I list.reverse()
I len(list)
I Slicing: list[start:end:step]
I Copying: list.copy()

Python Objects ADPG 57 / 80


LIST EXAMPLES

if __name__ == '__main__ ':


string_list = ['Hello ', 'World ']
print ( string_list ) # output - [' Hello ', 'World ']

num_list = [1 ,2 ,3 ,4 ,5]
# concatenation
num_list . append (12) # num_list = [1 ,2 ,3 ,4 ,5 ,12]
# Slicing is similar to string slicing

Python Objects ADPG 58 / 80


LISTS ARE MUTABLE
>>> #Read -Eval -Print -Loop (REPL)
>>> fruits = ["apple ", " banana ", " cherry "]
>>> fruits [1] = "mango " # Change the second element
>>> fruits
["apple ", "mango ", " cherry "]
>>>
>>> # Remove the first occurrence of " mango"
>>> fruits . remove ("mango ")
>>> fruits
["apple ", " cherry "]
>>> fruits [:] # output - a copy of fruit
>>> fruit [:2] # output = ?
>>> fruit [1:] = # output =?
>>> fruit [1: len( fruits )] # output =?
some_fruits = fruits [1:2]
Python Objects ADPG 59 / 80
ASSIGNMENT OF LISTS
I Python Lists are mutable - Once stored, the content is fixed
I Slicing is same as in string
I Zero-based indexing
I An item in a list can be using [ ]
I −1 refers to the last item in the list

x = 0 apple 0 , 0 mango 0 x.append( 0 cherry 0 )


 

y=x y=?

x [ 0 apple 0 , 0 mango 0 ] x [ 0 apple 0 , 0 mango 0 , 0 cherry 0 ]

y y
Python Objects ADPG 60 / 80
OPERATIONS ON LISTS
We can insert, delete, modify and copy a slice of the contents of a list
>>> fruits = ['pineapple ', 'mango ', 'cherry ']
>>> fruits . insert [0,'berry ']
>>> fruits [3] = 'blueberry ' # cherry is replaced by blueberry
>>> fruits . remove ('mango ') # Remove by occurrence
>>> del fruits [0] # Remove the element at index
>>> fruits .clear ()

Python Objects ADPG 61 / 80


MULTIDIMENSIONAL LISTS

I Lists of lists
I Represent tabular or matrix-like data
I Access elements using double indexing: list[row][col].
I Can handle uneven rows (jagged lists).
I Created using nested lists or loops.
I Example: matrix = [[1, 2], [3, 4]].

Python Objects ADPG 62 / 80


OPERATIONS

I Access element: matrix[0][1] gives second element.


I Iterate with nested loops or comprehensions.
I Modify element: matrix[1][1] = 10.
I Add row: matrix.append([5, 6]).
I Remove row: matrix.pop(index).
I Flatten list: [elem for row in matrix for elem in row].

Python Objects ADPG 63 / 80


EXAMPLES

matrix = [ coordinates = [[0, 0], [1, 2], [3, 4]]


[1, 2, 3], # Accessing a coordinate pair
[4, 5, 6], print ( coordinates [1]) # Outputs ?
[7, 8, 9] # Modifying a coordinate
] coordinates [1][0] = 5
# print ( coordinates )
print ( matrix [1][2]) # Output : ?
# Output ?
#
for i, row in enumerate ( matrix ):
print (i, row)
output ?

Python Objects ADPG 64 / 80


Python Objects ADPG 65 / 80
NESTED DICTIONARY
sub_list = [[ 'a','b'],['c','d']]
nested_list = [ [1,2,'apple '],
[3,4,'orange '],
[5,'grapes ' ,6],
['python ',7, sub_list ]]

Python Objects ADPG 66 / 80


NESTED DICTIONARY
sub_list = [[ 'a','b'],['c','d']]
nested_list = [ [1,2,'apple '],
[3,4,'orange '],
[5,'grapes ' ,6],
['python ',7, sub_list ]]

print ( nested_list [3][2][0][0])


Python Objects ADPG 66 / 80
CORE DATA TYPES

I Numbers
I Strings
I Lists
I Tuple
I Dictionaries

Python Objects ADPG 67 / 80


WHAT ARE TUPLES?

I Equivalent to lists, but elements are immutable


I Immutable ordered collection of elements
I Defined with parentheses ()
I Can hold different data types
Example
# Creating a tuple
my_tuple = (1, "Hello ", 3.14)

Python Objects ADPG 68 / 80


KEY FEATURES OF TUPLES

I Elements accessed via indexing


I Support slicing like lists
I Cannot modify elements after creation
I Used for fixed data collections
Example
# Accessing tuple elements
my_tuple = (1, 2, 3, 4)
print ( my_tuple [1]) # Output : 2
print ( my_tuple [:3]) # Output : (1, 2, 3)

Python Objects ADPG 69 / 80


OPERATIONS WITH TUPLES

I Concatenate using + s = 'temp ' *5 # output ?


I Repeat using * l = [1 ,2]*5 # output ?
I Check membership with in t = (1 ,2)*5 # output ?
I Supports iteration with for tup = t + (3 ,4)# output ?

Example
# Tuple operations
tuple1 = (1, 2)
tuple2 = (3, 4)

print (3 in tuple2 ) # Output : True

Python Objects ADPG 70 / 80


CORE DATA TYPES

I Numbers
I Strings
I Lists
I Dictionaries
I Tuple

Python Objects ADPG 71 / 80


DICTIONARY

I Another built-in collection object


I Dictionaries are mutable - you can add, remove, or modify key-value pairs
after creation
I Keys don’t maintain any specific order. Accessing them relies on the key
itself, not their position
I Items are stored key-value pairs
I Each key acts as a unique identifier and there cannot be any duplicate key
I Efficient lookup mechanisms to retrieve any item using the key or value
I You can store other dictionaries within a dictionary, creating nested data
structures for complex relationships

Python Objects ADPG 72 / 80


SAMPLE CODE

>>> person = {"name": "Ram", "age": 25, "city": "CHN"}


>>> person ["name"] = 'Alice ' # Modify value
>>> print ( person ["name"])# Output : Alice
>>> person ["age"] = 35 # Modify value
>>> #Add new KV pair
>>> person [" skills "] = [" coding ", " writing "]
>>> person
>>> age = my_dict .get("age") # Retrieves the value 30
>>> age
>>> # Handling missing keys:
>>> value = my_dict .get("hobby ", "Not specified ")
>>> value
'Not specified '

Python Objects ADPG 73 / 80


GENERATORS

Generator Expressions
I Concise way to create iterators: Generate values on demand.
I Syntax: (expression for item in iterable)
I Useful for processing sequences efficiently.

if __name__ == '__main__ ':


numbers = [1, 2, 3, 4]
number_string = "-".join(str(num) for num in numbers )
# Output : "1 -2 -3 -4"

Python Objects ADPG 74 / 80


FUNCTIONS

Python Objects ADPG 75 / 80


INPUT AND OUTPUT

Python Objects ADPG 76 / 80


EXCEPTION HANDLING

Python Objects ADPG 77 / 80


COMPREHENSION

Python Objects ADPG 78 / 80


DECORATORS

Python Objects ADPG 79 / 80


REFERENCES I

References ADPG 80 / 80

You might also like