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

Unit 3 Notes

This document provides an overview of complex data types in Python, including strings, lists, tuples, and dictionaries. It covers their characteristics, methods, and common operations, as well as the building blocks of Python programs such as variables, data types, control structures, and functions. Additionally, it explains how to define and call functions in Python, emphasizing the importance of these concepts in programming.

Uploaded by

Haina Kherkatary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 3 Notes

This document provides an overview of complex data types in Python, including strings, lists, tuples, and dictionaries. It covers their characteristics, methods, and common operations, as well as the building blocks of Python programs such as variables, data types, control structures, and functions. Additionally, it explains how to define and call functions in Python, emphasizing the importance of these concepts in programming.

Uploaded by

Haina Kherkatary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit-3

Python Complex Data Types

Python Strings: A String is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change it. Strings are
used widely in many different applications, such as storing and manipulating text data, representing
names, addresses, and other types of data that can be represented as text. We will create a string
using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple quotes can
be used to declare multiline strings in Python.

Example:
#Create string type variables
name = "Python"
print(name)
message = "I love Python."
print(message)

Output:
Python
I love Python.

Access String Characters in Python: We can access the characters in a string in three ways.

1. Indexing: One way is to treat strings as a list and use index values.
Example:
greet = 'hello'
# access 1st index element
print(greet[1])

Output:
"e"

2. Negative Indexing: Similar to a list, Python allows negative indexing for its strings.

Example:
greet = 'hello'
# access 4th last element
print(greet[-4])

Output:
"e"

3. Slicing: Access a range of characters in a string by using the slicing operator colon (:) .

Example:
greet = 'Hello'
# access character from 1st index to 3rd index
print(greet[1:4])

Output:
"ell"

Note: If we try to access an index out of the range or use numbers other than an integer, we will get
errors.
Python Strings are immutable: In Python, strings are immutable. That means the characters of a
string cannot be changed.

Example:
message = ‘Hello World’
message[0] = 'E'
print(message)

Output:
TypeError: 'str' object does not support item assignment. However, we can assign the variable name
to a new string.

Example:
message = ’Hello World’
# assign new string to message variable
message = 'Hello Friends'
prints(message);

Output:
prints "Hello Friends"

Python Multiline String: We can also create a multiline string in Python. For this, we use triple double
quotes """ or triple single quotes '''.

Example:
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)

Output:
Never gonna give you up
Never gonna let you down

Python String Manipulation: String manipulation in Python refers to the various operations you can
perform on strings, such as combining, splitting, searching, replacing, and formatting strings. Python
provides several built-in methods and operators for manipulating strings.

Here are some common string manipulation operations in Python:


Compare Two Strings: We use the == operator to compare two strings. If two strings are equal, the
operator returns True. Otherwise, it returns False.

Example:
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)

Output:
False
True

Join Two or More Strings: In Python, we can join (concatenate) two or more strings using the +
operator.

Example:
greet = "Hello, "
name = "Edu Desire"
# using + operator
result = greet + name
print(result)

Output:
Hello, Edu Desire

Iterate Through a Python String: We can iterate through a string using a for loop.

Example:
greet = 'Hello'
# iterating through greet string
for letter in greet:
print(letter)

Output:
H
e
l
l
o

Python String Formatting (f-Strings): Python f-Strings make it really easy to print values and variables.

Example:
name = 'Cathy'
country = 'UK'
print(f'{name} is from {country}')

Output:
Cathy is from UK

Python String Length: In Python, we use the len() method to find the length of a string.

Example:
greet = 'Hello'
# count length of greet string
print(len(greet))

Output:
5

Methods of Python String:


Besides those mentioned above, there are various string methods present in Python. Here are some
of those methods.

Methods Description
upper() converts the string to uppercase
lower() converts the string to lowercase
partition() returns a tuple
replace() replaces substring inside
find() returns the index of first occurrence of substring
rstrip() removes trailing characters
split() splits string from left
startswith() checks if string starts with the specified string
isnumeric() checks numeric characters
index() returns index of substring

Python List: A list is a built-in data structure that allows you to store and manipulate a collection of
items. Lists are ordered, mutable (changeable), and can contain elements of different data types.
They are defined using square brackets [] and items are separated by commas.

Example of creating a list in Python:


my_list = [1, 2, 3, 'a', 'b', True]
In this example, my_list is a list that contains integers, strings, and a boolean value.

Lists have several important characteristics and support various operations:

1. Accessing Elements: You can access individual elements in a list using indexing. Indexing starts
from 0, so the first element is at index 0, the second element is at index 1, and so on. Negative
indexing allows you to access elements from the end of the list.

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[0])
print(my_list[-1])

Output:
1
5

2. Modifying Elements: Lists are mutable, meaning you can change the value of individual elements
or modify the list itself.

Example:
my_list = [1, 2, 3, 4, 5]
my_list[2] = 'a'
print(my_list)

Output:
[1, 2, 'a', 4, 5]

my_list.append(6)
print(my_list)

Output:
[1, 2, 'a', 4, 5, 6]

3. Slicing: Slicing allows you to extract a portion of a list. It is done by specifying a start index, an end
index (exclusive), and an optional step size.

Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4])

Output:
[2, 3, 4]

4. List Operations: Lists support various operations, including concatenation, repetition, length
calculation, membership testing, and more.

Example:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

concatenated_list = list1 + list2


print(concatenated_list) #Output: [1, 2, 3, 'a', 'b', 'c']

repeated_list = list1 * 3
print(repeated_list) #Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

length = len(my_list)
print(length) #Output: 5
print(2 in my_list) # Output: True

5. List Methods: Lists have several built-in methods that allow you to perform operations such as
adding or removing elements, sorting, reversing, and more.

Example:
my_list = [4, 2, 1, 3]
my_list.append(5)
print(my_list) #Output: [4, 2, 1, 3, 5]

my_list.remove(2)
print(my_list) #Output: [4, 1, 3, 5]

my_list.sort()
print(my_list) #Output: [1, 3, 4, 5]

Tuples in python: A tuple is an ordered, immutable collection of elements. Similar to lists, tuples can
store multiple items of different data types, such as integers, floats, strings, or even other tuples.
However, unlike lists, tuples cannot be modified once created, making them immutable.

Example of creating a tuple in Python:


my_tuple = (1, 2, 'a', 'b', True)
In this example, my_tuple is a tuple that contains integers, strings, and a boolean value.

Tuples have several important characteristics:

1.Immutable: Once a tuple is created, its elements cannot be modified or reassigned. This
immutability ensures the integrity of data stored in the tuple.

2. Ordered: Tuples maintain the order of elements as they are defined, and this order is preserved
throughout the tuple's lifetime.

3. Indexing and Slicing: You can access individual elements of a tuple using indexing, similar to lists.
Additionally, you can use slicing to extract a portion of a tuple.
Example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) #Output: 1
print(my_tuple[1:4]) #Output: (2, 3, 4)

4. Tuple Packing and Unpacking: Tuple packing involves creating a tuple by assigning multiple values
to a single variable, while tuple unpacking involves assigning the values of a tuple to multiple
variables.

Example:
#Tuple Packing
my_tuple = 1, 2, 'a'
print(my_tuple) #Output: (1, 2, 'a')
# Tuple Unpacking
a, b, c = my_tuple
print(a) #Output: 1
print(b) #Output: 2
print(c) #Output: 'a'

5. Size and Length: You can determine the size or length of a tuple using the len() function.

Example:
my_tuple = (1, 2, 3, 4, 5)
size = len(my_tuple)
print(size)
Output: 5

Remark: Tuples are commonly used when you want to store a collection of values that should not be
modified. They are useful for situations where data integrity and immutability are desired, such as
representing coordinates, database records, or returning multiple values from a function.

Dictionaries in python: A dictionary is a built-in data structure that allows you to store and retrieve
data in key-value pairs. It is an unordered collection of elements where each element is identified by a
unique key. Dictionaries are defined using curly braces {} and consist of key-value pairs separated by
colon (:) .

Example of creating a dictionary in Python:


my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
In this example, my_dict is a dictionary that contains three key-value pairs.

Dictionaries have several important characteristics:

1. Key-Value Pairs: Dictionaries store data as key-value pairs, where each key is unique and associated
with a corresponding value. Keys are used to access and retrieve values from the dictionary.

2. Mutable: Dictionaries are mutable, meaning you can modify, add, or remove key-value pairs after
the dictionary is created.

3. Unordered: Dictionaries are unordered, which means the order of key-value pairs may vary and is
not guaranteed. The order of elements in a dictionary is based on the hash value of the keys.

4. Accessing Values: You can access values in a dictionary by referencing the corresponding key using
square brackets [] or the get() method. If the key does not exist, an error occurs when using square
brackets, while get() returns None or a specified default value.
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict['name']) # Output: Alice
print(my_dict.get('age')) # Output: 25
print(my_dict.get('gender')) # Output: None
print(my_dict.get('gender', 'Unknown')) # Output: Unknown

5. Modifying and Adding Entries: You can modify the value of an existing key or add new key-value
pairs to a dictionary.

Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
my_dict['age'] = 26 # Modifying an existing key-value pair
my_dict['gender'] = 'Female' # Adding a new key-value pair
print(my_dict)

6. Removing Entries: You can remove entries from a dictionary using the del keyword or the pop()
method, which removes and returns the value associated with a given key.

Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
del my_dict['age'] # Removing a specific key-value pair
my_dict.pop('city') # Removing and returning the value of a key
print(my_dict)

Remark: Dictionaries are widely used when you want to store and retrieve data using descriptive
keys. They are useful for representing structured information, configuration settings, or mapping
relationships between entities. Dictionaries provide efficient lookup and retrieval operations based on
keys, making them an essential tool in Python programming.

Building Blocks of Python Programs:

● Variables: Used to store data values. Variables are created when they are first assigned a value.
● Data Types: Python has several built-in data types, including integers, floats, strings, booleans,
lists, tuples, sets, and dictionaries.
● Operators: Used to perform operations on variables and values. Python supports arithmetic
operators (+, -, *, /), comparison operators (==, !=, <, >, <=, >=), logical operators (and, or, not), and
more.
● Control Structures: Used to control the flow of a program. Includes conditional statements (if, elif,
else) and loops (for, while).
● Functions: Blocks of reusable code that perform a specific task. Functions help in organising code
and promoting reusability.
● Modules: Files containing Python code that define functions, classes, and variables. Modules can
be imported into other Python programs to use their functionality.
● Classes: Blueprint for creating objects. Classes define attributes (data) and methods (functions)
that operate on those attributes.
● Exception Handling: Used to handle errors and exceptions that occur during program execution.
Includes try, except, else, and finally blocks.
● Input and Output: Python provides functions for reading input from the user (input) and writing
output to the screen (print) or files (open, read, write).
● Libraries and Packages: Python's standard library includes a wide range of modules and packages
that provide additional functionality for tasks such as web development, data manipulation, and
scientific computing.
By combining these building blocks, you can create Python programs to solve a variety of problems,
from simple scripts to complex applications.

Python Functions: A function is a block of code that performs a specific task. There are two types of
function in Python programming:
1. Standard library functions: These are built-in functions in Python that are available to use.
2. User-defined functions: We can create our own functions based on our requirements.

Part of Function: A function typically consists of several parts:

1. Function Definition: The function definition is where you define the name of the function and
specify any input parameters (arguments) it requires.
Syntax: def function_name(arguments):

Example:
def greet(name):
print("Hello, " + name + "!")

2. Function Body: The function body contains the block of code that gets executed when the function
is called. It performs the desired task or computation. The body is indented under the function
definition.

Example:
def greet(name):
print("Hello, " + name + "!")
# Additional code in the function body
print("Welcome to our program!")

3. Parameters (Arguments): Parameters are placeholders for values that are passed into the function
when it is called. They allow you to provide input values to the function. Parameters are listed inside
the parentheses in the function definition.

Example:
def greet(name):
print("Hello, " + name + "!")

4. Return Statement (Optional): The return statement is used to specify the value or values that the
function should return as the result of its execution. It is optional, and if omitted, the function will
return None by default.

Example:
def add_numbers(a, b):
return a + b

5. Function Call: The function call is where you invoke or execute the function with specific arguments
(input values) to perform its task. You use the function name followed by parentheses, with
arguments (if any) inside the parentheses.

Example:
greet("Alice")

Python Function Declaration: The syntax to declare a function is:


def function_name(arguments):
# function body
Return
Here,
● def: keyword used to declare a function
● function_name: any name given to the function
● arguments: any value passed to function
● return (optional): returns value from a function

Example:
def greet():
print('Hello World!')

Here, we have created a function named greet(). It simply prints the text Hello World!. This function
doesn't have any arguments and doesn't return any values.

Calling a Function in Python: In the above example, we have declared a function named greet().
def greet():
print('Hello World!')

Now, to use this function, we need to call it. Here's how we can call the greet() function in Python.
# call the function
greet()

Example:
def greet():
print('Hello World!')
# call the function
greet()
print('Outside function')

Output:
Hello World!
Outside function

Function Arguments: The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1. Default Arguments: Default arguments allow you to assign default values to parameters in a
function definition. If an argument is not provided when calling the function, the default value is
used. Default arguments are helpful when you want to provide a common value that is used most of
the time but can be overridden if needed.

Example:
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )

function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)

Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30

2. Keyword Arguments: Keyword arguments allow you to specify arguments by their parameter
names when calling a function, rather than relying on the order of arguments in the function
definition. By using keywords, you can explicitly associate values with specific parameters, regardless
of their position.

Example:
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )

function( 50, 30)

# Calling function and passing arguments using keyword


print( "With using keyword" )
function( n2 = 50, n1 = 30)

Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50

Example: Add Two Numbers


# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum

# calling function with two values


result = add_numbers(5, 4)
print('Sum: ', result)

Output:
Sum: 9

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy