Python Unit - 3
Python Unit - 3
Introduction to Strings:
In Python, a string is a sequence of characters enclosed within quotes.
Strings are widely used to store text data such as names, messages, or any
combination of letters, digits, and symbols.
2. Double Quotes
b = "Python"
print(b)
Output:
Python
Empty String
An empty string is a string that has no characters.
It is written as just a pair of quotes:
empty = ""
print(empty)
Output:
Nothing is printed because the string is empty.
2. Indexing in Strings
Each character in a string has a position (index).
Forward Indexing → starts from 0 to length-1
Backward Indexing → starts from -1 to -length
Example:
word = "HELLO"
print(word[0]) # H (first character)
print(word[4]) # O (last character using forward index)
print(word[-1]) # O (last character using backward index)
print(word[-5]) # H (first character using backward index)
Output:
H
O
O
H
Summary
Strings are sequences of characters enclosed in 'single', "double", or
'''triple''' quotes.
They can be empty ("").
Strings are immutable (cannot be changed after creation).
Characters in a string are accessed using indexes (both positive and
negative).
Traversing a String in Python:
What does Traversing Mean?
Traversing a string means visiting each character of the string one by one.
Since a string is a sequence of characters, we can use its indexes or a loop
to access each character.
Example:
name = "superb"
for ch in name:
print(ch, "-", end=" ")
Output:
s-u-p-e-r-b–
for i in range(len(word)):
print("Index:", i, "Character:", word[i])
Output:
Index: 0 Character: P
Index: 1 Character: y
Index: 2 Character: t
Index: 3 Character: h
Index: 4 Character: o
Index: 5 Character: n
Example:
text = "Hello"
i=0
Example:
1. Print each character of a string
# Program to print each character of a string
string1 = input("Enter a string: ")
Output:
Input: Hello
Output: H e l l o
count = 0
vowels = "aeiouAEIOU"
for ch in string1:
if ch in vowels:
count += 1
[Link] Operators
Strings can be compared using relational operators (==, !=, <, >, <=,
>=).
Comparisons are done based on lexicographical order (like dictionary
order, using ASCII/Unicode values).
Example:
print("apple" == "apple") # True
print("apple" != "banana") # True
print("cat" < "dog") # True (because 'c' comes before 'd')
print("Zebra" > "apple") # False (because 'Z' has smaller ASCII value
than 'a')
Output:
True
True
True
False
Summary
+ → Concatenates strings
* → Repeats string
in / not in → Check for substring presence
Relational operators → Compare strings alphabetically
Summary:
Use ord(char) → gives ASCII value.
Use chr(number) → gives character for that ASCII.
String comparison in Python is based on these ASCII values.
Positive indices:
a m a z i n g
0 1 2 3 4 5 6
1. Full String
print(word[0:7]) # Output: amazing
Explanation: Starts from index 0 to index 6 (7 is excluded).
2. Slice First 3 Characters
print(word[0:3]) # Output: ama
Explanation: Takes characters at positions 0, 1, and 2.
1. capitalize() Method:
Definition
The capitalize() method in Python is a string method that returns a copy of the
string with its first character converted to uppercase and the rest of the
characters converted to lowercase.
Syntax
[Link]()
Example
txt = "python is FUN!"
x = [Link]()
print(x)
Output
Python is fun!
2. count() Method:
Definition
Returns the number of times a specified substring occurs in the string.
Syntax
[Link](value, start, end)
Example
txt = "I love apples, apple are my favorite fruit"
x = [Link]("apple", 10, 24)
print(x)
Output
1
3. endswith() Method:
Definition
Checks if a string ends with a specified substring.
Returns True if it does, otherwise False.
Syntax
[Link](value, start, end)
Example
txt = "Hello, welcome to my world."
x = [Link]("my world.")
print(x)
Output
True
4. find() Method:
Definition
Finds the index of the first occurrence of a specified substring.
Returns -1 if the value is not found.
Similar to index(), but index() raises an error if not found.
Syntax
[Link](value, start, end)
Example
txt = "Hello, welcome to my world."
x = [Link]("e")
print(x)
Output
1
5. replace() Method:
Definition
Replaces all occurrences of a substring with another substring.
Syntax
[Link](oldvalue, newvalue, count)
Example
txt = "one one was a race horse, two two was one too."
x = [Link]("one", "three")
print(x)
Output
three three was a race horse, two two was three too.
6. split() Method:
Definition
Splits a string into a list of substrings based on a given separator.
Default separator is whitespace.
Syntax
[Link](separator, maxsplit)
Example
txt = "hello, my name is Peter, I am 26 years old"
x = [Link](", ")
print(x)
Output
['hello', 'my name is Peter', 'I am 26 years old']
7. join() Method:
Definition
Joins all elements of an iterable (list, tuple, dictionary, etc.) into a
single string.
A string must be provided as the separator.
Syntax
[Link](iterable)
Example
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = [Link](myDict)
print(x)
Output
nameTESTcountry
8. isalpha() Method:
Definition
Returns True if all characters in the string are alphabetic (a–z or A–Z).
Returns False if the string contains numbers, spaces, or special
characters.
Syntax
[Link]()
Example
txt = "Company10"
x = [Link]()
print(x)
Output
False
9. isalnum() Method:
Definition
Returns True if all characters are alphanumeric (letters and numbers).
Returns False if the string contains spaces or special characters.
Syntax
[Link]()
Example
txt = "Company 12"
x = [Link]()
print(x)
Output
False
Lists in Python:
Definition
A list in Python is a collection of ordered elements (items) that can store
values of any type (integers, strings, floats, even other lists).
Lists are enclosed in square brackets [ ] with elements separated by
commas.
Lists are mutable, meaning their elements can be changed, added, or
removed after creation.
2. Nested Lists:
A list that contains another list as an element is called a nested list.
L1 = [3, 4, [5, 6], 7]
Here:
1. L1 has 4 elements: 3, 4, [5, 6], and 7.
2. L1[2] → [5, 6] (a list itself).
3. Length of L1 = 4 (since [5, 6] is counted as one element).
3. Accessing List Elements:
Similar to strings, list elements are accessed using indexes:
vowels = ['a', 'e', 'i', 'o', 'u']
print(vowels[0]) # 'a'
print(vowels[2]) # 'i'
print(vowels[1:4]) # ['e', 'i', 'o'] (slicing)
4. Traversing a List:
Traversal means accessing and processing each element of the list.
Done using loops:
L = ['P', 'y', 't', 'h', 'o', 'n']
for a in L:
print(a)
Output:
P
y
t
h
o
n
List Operations in Python:
1. Joining Lists
We can join (concatenate) two lists using the + operator.
Both operands must be lists.
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8]
result = list1 * 2
print(result)
Output:
[1, 2, 3, 4, 1, 2, 3, 4]
3. Slicing Lists
We can extract a portion (slice) of a list using indexes.
Syntax:
seq = L[start:stop]
Rules:
o Starts from index start.
o Stops before index stop.
o The result is a new list (a slice).
Example:
List1 = [10, 20, 30, 40, 50, 60]
seq = List1[2:-1]
print(seq)
Output:
[30, 40, 50]
print(lst1)
Output:
[10, 12, 14, 16]
1. Updating Elements
To update (change) an element in a list, simply assign a new value to the
desired index.
Syntax:
List[index] = new_value
Example:
lst1 = [10, 12, 14, 16]
print(lst1)
Output:
[10, 12, 24, 16]
2. Deleting Elements
(a) Using del Statement
We can remove an element at a given index, or a slice of elements.
Syntax:
del List[index] # Removes element at index
del List[start:stop] # Removes elements in range
Example:
lst = [10, 12, 14, 16]
1. index() Method
Returns the position of the first occurrence of a specified value.
fruits = [4, 55, 64, 32, 16, 32]
x = [Link](32)
print(x)
Output:
3
2. append() Method
Adds a single element to the end of the list.
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
[Link](b)
print(a)
Output:
['apple', 'banana', 'cherry', ['Ford', 'BMW', 'Volvo']]
3. extend() Method
Adds all elements of another iterable (list, tuple, etc.) to the list.
fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
[Link](points)
print(fruits)
Output:
['apple', 'banana', 'cherry', 1, 4, 5, 9]
4. insert() Method
Inserts an element at a specific position.
fruits = ['apple', 'banana', 'cherry']
[Link](1, "orange")
print(fruits)
Output:
['apple', 'orange', 'banana', 'cherry']
5. pop() Method
Removes the element at the given index (default: last element) and
returns it.
fruits = ['apple', 'banana', 'cherry']
x = [Link](1)
print(x) # Removed element
print(fruits) # Updated list
Output:
banana
['apple', 'cherry']
6. remove() Method
Removes the first occurrence of a specified element.
fruits = ['apple', 'banana', 'cherry']
[Link]("banana")
print(fruits)
Output:
['apple', 'cherry']
7. clear() Method
Removes all elements from the list.
fruits = ['apple', 'banana', 'cherry', 'orange']
[Link]()
print(fruits)
Output:
[]
8. count() Method
Returns the number of occurrences of a specified value.
fruits = ['apple', 'banana', 'cherry']
x = [Link]("cherry")
print(x)
Output:
1
9. reverse() Method
Reverses the elements of the list.
fruits = ['apple', 'banana', 'cherry']
[Link]()
print(fruits)
Output:
['cherry', 'banana', 'apple']
Tuples in Python:
1. Introduction
A tuple is a sequence data type in Python used to store multiple values
of any type.
Tuples are immutable → once created, their elements cannot be
changed.
Difference from lists:
o List → mutable (elements can be changed).
o Tuple & String → immutable (cannot be changed directly).
2. Creating Tuples
Tuples are created by enclosing elements in parentheses ( ), separated
by commas.
my_tuple = (1, 'apple', 3.14) # Tuple with mixed data types
empty_tuple = () # Empty tuple
single_element_tuple = (5,) # Tuple with one element (note the comma)
Without the comma, (5) would just be treated as an integer, not a tuple.
3. Accessing Tuple Elements
Elements are accessed using indexes, similar to lists.
Indexing starts at 0.
my_tuple = (1, 'apple', 3.14)
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: apple
print(my_tuple[2]) # Output: 3.14
So, tuples are like lists, but immutable. They are often used to store fixed
collections of items.
1. Concatenation (+)
Tuples can be joined together using the + operator.
tuple1 = (1, 2)
tuple2 = (3, 4)
2. Repetition (*)
Tuples can be repeated using the * operator.
my_tuple = ('hello',) * 3
print(my_tuple)
Output:
('hello', 'hello', 'hello')
3. Slicing
Tuples support slicing to extract a portion of elements.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])
Output:
(2, 3, 4)
These are the three main tuple operations: Concatenation, Repetition, and
Slicing.
print(cmp(T1, T2)) # -1
print(cmp(T1, T3)) # 0
print(cmp(T2, T1)) # 1
Note: cmp() was removed in Python 3.
In Python 3, comparisons use relational operators (==, <, >, etc.).
2. len() Function
Returns the number of elements in a tuple.
T2 = (100, 200, 300, 400, 500)
print(len(T2))
Output:
5
3. max() Function
Returns the largest element in a tuple.
T = (100, 200, 300, 400, 500)
print(max(T))
Output:
500
4. min() Function
Returns the smallest element in a tuple.
T = (100, 200, 300, 400, 500)
print(min(T))
Output:
100
1. count()
Returns the number of times a specified value appears in the tuple.
Example:
my_tuple = (1, 2, 3, 2, 2, 5)
print(my_tuple.count(2))
Output:
3
2. index()
Searches the tuple for a specified value.
Returns the index (position) of the first occurrence of that value.
Example:
my_tuple = (1, 2, 3, 2, 2, 5)
print(my_tuple.index(5))
Output:
5
If the value is not found, ValueError is raised.
That’s it — only count() and index() are available for tuples because they
cannot be modified.
Dictionaries in Python
1. Introduction
A dictionary stores key-value pairs.
Unlike lists, dictionary keys can be any data type (not just integers).
Dictionaries are unordered → items are not stored in any particular
sequence.
Syntax:
my_dict = {'key1': 'value1', 'key2': 'value2', ..., 'keyn': 'valuen'}
Example:
A = {1: "one", 2: "two", 3: "three"}
print(A)
# Output: {1: 'one', 2: 'two', 3: 'three'}
3. Traversing a Dictionary
Use a for loop to access keys and values:
H = {'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print(i, ":", H[i], end=" ")
# Output: {}
4.6 keys()
Returns a list of keys:
print(my_dict.keys())
# Output: dict_keys(['name', 'age'])
5.7 values()
Returns a list of values:
print(my_dict.values())
Note: If you call items() and values() without changing the dictionary, the order
of values will correspond to keys in items().
Functions in Python
1. Introduction to Functions
A function in Python is a named block of code designed to perform a specific
task. Functions allow us to break a program into smaller, manageable parts,
making it easier to read, debug, and reuse code.
Functions contain lines of code that are executed sequentially from top
to bottom.
Using functions reduces code repetition and helps structure programs
logically.
Every Python program can use built-in functions, create user-defined
functions, or use functions from modules.
2. Categories of Functions
Functions in Python can be broadly classified into three categories:
i. Module Functions
A module is a separate file that contains Python code such as functions,
classes, and variables.
Python provides a standard library of modules that contain useful
functions for tasks like mathematics, file handling, and string
manipulation.
To use a module, it must be imported into the program using the import
keyword.
Syntax to import a module:
import module_name
Example: Using the math module
import math
4. Default Arguments
Parameters can have default values. If the caller does not provide a
value, the function uses the default.
Rules:
1. Only parameters at the end of the parameter list can have default
values.
2. Default values must be constants.
Example:
def greet(message, times=1):
print(message * times)
greet('Welcome') # Output: Welcome
greet('Hello', 2) # Output: HelloHello
Another example with multiple defaults:
def fun(a, b=1, c=5):
print('a is', a, 'b is', b, 'c is', c)
5. Flow of Execution
Python executes a program line by line from top to bottom.
Function definitions do not execute immediately; they only define the
function.
When a function is called, the program jumps to the function body,
executes all statements, and returns to the point of the call.
If a function calls another function, the program jumps again, executes
the called function, and returns to the caller.
Example:
def greet():
print("Hello")
def welcome():
print("Welcome")
greet()
print("Have a nice day!")
welcome()
Flow of Execution:
1. welcome() is called
2. Prints "Welcome"
3. Calls greet() → prints "Hello"
4. Returns → prints "Have a nice day!"
Output:
Welcome
Hello
Have a nice day!
6. Summary
Functions help organize code, reuse logic, and reduce errors.
Types of functions:
o Module functions → imported from external modules
o Built-in functions → available in Python by default
o User-defined functions → created by programmers
Parameters allow functions to work on inputs; arguments are the actual
values.
Default values make some arguments optional.
Execution flow jumps to the function body when called and returns after
execution.