0% found this document useful (0 votes)
18 views18 pages

Module 4

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)
18 views18 pages

Module 4

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/ 18

MODULE 4

Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
Example
print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
Example
a = "Hello"
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings are Arrays


• Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.
• However, Python does not have a character data type, a single character is simply a
string with a length of 1.
• Square brackets can be used to access elements of the string.
Example
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)

String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))

Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.

Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)

Python - Modify Strings


Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))

Split String
The split() method returns a list where the text between the specified separator becomes the list
items.

Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Python - String Methods

Python Collections (Arrays)


There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
• Dictionary is a collection which is ordered** and changeable. No duplicate members.

Python Lists
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
• When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
• If you add new items to a list, the new items will be placed at the end
of the list.

Changeable
The list is changeable, meaning that we can change, add, and remove items
in a list after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:

Example
Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

Python - Access List Items


Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Python - Add List Items


Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Python - Remove List Items


The remove() method removes the specified item.
Example: Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Clear the List


The clear() method empties the list.
The list still remains, but it has no content.
Example
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Python - List Methods

List Items - Data Types


List items can be of any data type:

Example

String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

Python Tuples
• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.

Features of Python Tuple


o Tuples are an immutable data type, meaning their elements cannot be changed after
they are generated.
o Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.

Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example

Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length
To determine how many items a tuple has, use the len() function:

Example

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Python - Access Tuple Items


thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Python - Update Tuples
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are
other ways to add items to a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

Remove Items
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Loop Through a Tuple


You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

Join Two Tuples


To join two or more tuples you can use the + operator:
Example
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
Python - Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it
was found

Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.
The data is stored as key-value pairs using a Python dictionary.
o This data structure is mutable
o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any
Python object. The keys, in contrast, are immutable Python objects, such as strings, tuples,
or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and
before, dictionaries are generally unordered.

Creating the Dictionary


Curly brackets are the simplest way to generate a Python dictionary, although there are
other approaches as well. With many key-value pairs surrounded in curly brackets and a
colon separating each key from its value, the dictionary can be built. (:).
Syntax:
1. Dict = {"Name": "Gayle", "Age": 25}
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an
item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
print(len(thisdict))

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

type()
From Python's perspective, dictionaries are defined as objects with the data type
'dict':
<class 'dict'>
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))

The dict() Constructor


It is also possible to use the dict() constructor to make a dictionary.
Example
Using the dict() method to make a dictionary:
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Python - Add Dictionary Items


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Python - Remove Dictionary Items


The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Python - Loop Dictionaries


for x in thisdict:
print(thisdict[x])

What are Sets in Python?


• Python sets are a fundamental data structure that provide a collection of unique
elements, making them incredibly useful in various programming scenarios.
• Set operations in Python allow for efficient manipulation and analysis of sets, enabling
developers to perform tasks like intersection, union, difference, and more.
Understanding these operations is essential for optimizing code, handling data, and
simplifying complex tasks within Python programs.
• Sets in Python are very much like lists except that their elements are immutable (you
cannot change or edit an element of a set after it has been declared).
• But, you can surely add/delete elements from the set.
• A set is a mutable, unordered collection of elements, where the elements themselves
are immutable. Another feature of a set is that it can contain elements of various types.
This implies that you can have a collection of numbers, strings, and even tuples in the
same set!

Python Set Operations


1. Set Union
The union of two sets is the set that contains all of the elements from both sets
without duplicates. To find the union of two Python sets, use the union()
method or the | syntax.
Here is an example of how to perform a union set operation in python.

set1 = {11, 22, 33}


set2 = {33, 54, 75}
# Perform union operation using the `|` operator or the `union()` method
union_set = set1 | set2
# Or: union_set = set1.union(set2)

print(union_set)

2. Set Intersection
The intersection of two sets is the set that contains all of the common elements of both sets.
To find the intersection of two Python sets, we can either use the intersection() method or &
operator.
Here is an example to demonstrate this.
• Python
set1 = {11, 22, 33}
set2 = {33, 54, 75}
# Perform intersection operation using the `&` operator or the `intersection()` method
intersection_set = set1 & set2
# Or: intersection_set = set1.intersection(set2)
print(intersection_set)

3. Set Difference
The difference between the two sets is the set of all the elements in the first set that are not
present in the second set. To accomplish this, we can either use the difference() function or
the – operator in python.
Here is an example to demonstrate this.
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = set1.difference(set2)
print(set3)
set4 = set1 - set2
print(set4)

4. Set Symmetric Difference


The symmetric difference between the two sets is the set containing all the elements that
are either in the first or second set but not in both. In Python, you can use either the
symmetric difference() function or the ^ operator to achieve this.
Here is an example that demonstrates this.
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = set1.symmetric_difference(set2)
print(set3)
set4 = set1 ^ set2
print(set4)

Other Set Operations in Python


These are not so common but they are useful in seeing how sets are related to each other.

Issubset
The issubset() operation is used in Python to check whether a set is a subset of another set.
Here’s an example to demonstrate this:
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4}
print(set2.issubset(set1))
print(set1.issubset(set2))
Isdisjoint
The isdisjoint() operation in Python is used to check whether two sets have any common
elements. If the two sets have no common elements, then they are said to be disjoint.
Here’s an example to demonstrate this:
• Python
set1 = {1, 2, 3, 4, 5}
set2 = {6, 7, 8}
print(set1.isdisjoint(set2))
set3 = {4, 5, 6}
set4 = {6, 7, 8}
print(set3.isdisjoint(set4))

File Handling in Python


• File handling in Python is a powerful and versatile tool that can be used to perform a
wide range of operations.
• Python supports file handling and allows users to handle files i.e., to read and write
files, along with many other file handling options, to operate on files.
• The concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, like other concepts of Python, this
concept here is also easy and short.
Advantages of File Handling in Python
• Versatility : File handling in Python allows you to perform a wide range of operations,
such as creating, reading, writing, appending, renaming, and deleting files.
• Flexibility : File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files , etc.), and to perform
different operations on files (e.g. read, write, append, etc.).
• User – friendly : Python provides a user-friendly interface for file handling, making it
easy to create, read, and manipulate files.
• Cross-platform : Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python
• Error-prone: File handling operations in Python can be prone to errors, especially if
the code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, etc.).
• Security risks : File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on
the system.
• Complexity : File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code
to ensure that files are handled properly and securely.
• Performance : File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.

You might also like