Introduction2Python 2
Introduction2Python 2
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
ADPG 3 / 80
INTERPRETED AND COMPILED LANGUAGES
Aspect Python (Interpreted) Compiled Languages
ADPG 5 / 80
LIMITATIONS OF PYTHON INTERPRETER
ADPG 6 / 80
COMMON STRUCTURES
# Statements
sum = x + y
print ("The sum is:", sum)
// 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 ()
// Entry point
fn main () {
// Declarations
let x = 10;
let y = 5;
// Statements
let sum = x + y;
println !("The sum is: {}", sum );
}
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
Python ADPG 17 / 80
INDENTATION
1 ManyPython
IDEs ADPG of spaces can be configured)
convert tabs into spaces (the number 18 / 80
INDENTATION EXAMPLE
Python ADPG 19 / 80
IDENTIFIERS IN PYTHON
Basics ADPG 20 / 80
RULES FOR CREATING IDENTIFIERS
Basics ADPG 21 / 80
A SIMPLE BNF FOR PYTHON IDENTIFIER
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
···
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
Examples:
# Example objects in Python
x = 10 # int object
y = "Hello " # str object
z = [1, 2, 3] # list object
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.
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 }!")
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.
I Loop Control
I break: Exits the loop.
I continue: Skips the current iteration.
I pass: Placeholder for empty blocks.
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 :
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
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)
Try this
result = (2 + 3) * 4 ** 2
print ( result ) # Output : ?
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
# length of a string
print (len( my_string ))
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
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()
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
I Numbers
I Strings
I Lists
I Dictionaries
I Tuple
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.
I list.reverse()
I len(list)
I Slicing: list[start:end:step]
I Copying: list.copy()
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
y=x y=?
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 ()
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]].
I Numbers
I Strings
I Lists
I Tuple
I Dictionaries
Example
# Tuple operations
tuple1 = (1, 2)
tuple2 = (3, 4)
I Numbers
I Strings
I Lists
I Dictionaries
I Tuple
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.
References ADPG 80 / 80