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

Learn Python Elements Complete Book

LEARN PYTHON ELEMENTS is a comprehensive guide aimed at beginners to introduce them to Python programming. The eBook covers Python's core elements through four chapters, including an overview, modules, control flow, and data structures, with practical exercises and quizzes to reinforce learning. By the end, readers will have a solid foundation in Python, preparing them for more advanced topics.

Uploaded by

Table Table
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)
7 views

Learn Python Elements Complete Book

LEARN PYTHON ELEMENTS is a comprehensive guide aimed at beginners to introduce them to Python programming. The eBook covers Python's core elements through four chapters, including an overview, modules, control flow, and data structures, with practical exercises and quizzes to reinforce learning. By the end, readers will have a solid foundation in Python, preparing them for more advanced topics.

Uploaded by

Table Table
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/ 63

LEARN

PYTHON
ELEMENTS

FATIMAH RAHMAT . NURUL SHAKIRAH MOHD ZAWAWI . MUNIRAH AB RAHMAN


LEARN

PYTHON
ELEMENTS

FATIMAH RAHMAT
NURUL SHAKIRAH MOHD ZAWAWI
MUNIRAH AB RAHMAN

First Edition

2024
Copyright ©2024
All rights reserved. No part of this publication may be
reproduced, distributed, or transmitted in any form or by any
means, including photocopying, recording, or other electronic or
mechanical methods, without the prior written permission of
the publisher, except in the case of brief quotations embodied
in critical reviews and certain other noncommercial uses
permitted by copyright law. For permission requests, write to
the publisher, addressed “Attention: Permission Coordinator,” at
the address below.

Politeknik Mersing
Jalan Nitar,
86800 Mersing
Johor Darul Ta’zim
Telephone : 07-7980001
Fax : 07-7980002
Website : https://pmj.mypolycc.edu.my/web

Mode of access: Internet


First Edition, 2024
eISBN : 978-967-2904-86-1

Authors :
Fatimah Rahmat
Nurul Shakirah Mohd Zawawi
Munirah Ab Rahman

Proofreader :
Siti Nazirah Mohd Paiman

Reviewers :
DR. Norhaidah Abu Haris
DR. Azizah Rahmat

Designer :
Nurul Shakirah Mohd Zawawi
PREFACE
Welcome to LEARN PYTHON ELEMENTS, a guide designed to
introduce you to the basics of Python programming. Whether
you're a beginner or looking to refresh your skills, this eBook
offers a structured path to mastering Python.

Python is a versatile, high-level programming language widely


used in web development, data analysis, AI, scientific
computing, and more. Its simplicity and readability make it
ideal for both beginners and experienced programmers.

This eBook explores Python's core elements through four


detailed chapters:

Chapter 1: Python Overview


This chapter covers Python's origins, setting it up on your system, and
basic syntax. You'll learn about variables, basic input/output operations,
and write your first Python program. A quiz at the end of the chapter
will assess your understanding towards this topic.

Chapter 2: Module Overview


Learn about Python modules, which organize code into manageable
sections. This chapter covers creating and using modules, importing
them, and includes practical exercises.

Chapter 3: Conditional and Looping Overview


Focus on control flow statements in Python, including conditionals and
loops. Learn to use ‘if’, ‘elif’, and ‘else’ statements, ‘for’ and ‘while’
loops, and loop control statements. Practical examples and exercises
help you apply what you've learned.

Chapter 4: Data Structures Overview


Explore Python's data structures, both ordered and unordered. Learn
about lists, tuples, dictionaries, and sets, and how to use them
effectively. Practical exercises and a quiz reinforce your knowledge.

Each chapter includes practical exercises and quizzes to test your


understanding and reinforce learning. By the end of this eBook, you'll
have a solid foundation in Python and be ready for more advanced
topics.

Let's embark on this journey to learn Python together. Happy coding!


CONTENTS
Instructions to Fork and Use a Repl on 1
Replit.com
Chapter 1 : Python Overview 2
1.1 What is Python? 3
1.2 History of Python 5
1.3 Setting Up Python 6
1.4 Basic Characteristics of Python
Programming Syntax
7

1.5 Variables and Basic Input/Output in Python 10


1.6 Writing Your First Python Program 14
Interactive Coding Practices (Chapter 1) 16
1.7 Test Your Knowledge 17
Chapter 2 : Module Overview 20
2.1 What is Module? 21
2.2 Importing Modules 22
2.3 Creating Your Own Modules 23
2.4 Basic Module Example 24
2.5 Built-In Module 26
2.6 Practical Exercises 29
Interactive Coding Practices (Chapter 2) 30
2.7 Test Your Knowledge 31
CONTENTS
Chapter 3 : Conditional & Looping Overview 33
3.1 Conditional Statements 34
3.2 Loops 38
3.3 Combining Conditional Statements and
Loops
40

3.4 Practical Exercises 40


Interactive Coding Practices (Chapter 3) 41
3.5 Test Your Knowledge 42
Chapter 4 : Data Structures Overview 44
4.1 What is Data Structures? 45
4.2 Ordered Data Structures 45
4.3 Unordered Data Structures 47
4.4 Comparing Ordered and Unordered Data
Structures
48

4.5 Practical Exercises 49


Interactive Coding Practices (Chapter 4) 50
4.6 Test Your Knowledge 51
Feedback 54
Related Work 55
References 56
INSTRUCTIONS
Instructions to Fork and Use a Repl
on Replit.com

Open the Link/Image:


Click on the link/image provided to you.
This will open the Repl project in your web
browser.

Log In or Sign Up:


If you are not already logged in, you will
need to log in or sign up for a Replit
account.
You can sign up using your email, Google, or
GitHub account.

Fork the Repl:


Once the Repl project is open, you will see a “Fork”
button at the top right corner of the screen. Click on it.
A dialog box will appear asking you to name your
forked Repl. You can keep the default name or change
it.
Click “Fork Repl.”

Edit Your Forked Repl:


After forking, the project will be copied to
your Replit account, and redirected to the
forked Repl.
You can now make any changes to the code
in the editor.

Run Your Forked Repl:


To run the code, click the “Run” button at the top of
the screen.
The output will appear in the console window at the
bottom of the screen.

1
CHAPTER 1
PYTHON
OVERVIEW

2
OBJECTIVES
This chapter will introduce you to Python's history, features, and basic
syntax. By the end of this chapter, you'll be able to write simple Python
programs and understand the core concepts that make Python popular.

1.1 WHAT IS PYTHON?


Python is a high-level, interpreted programming language known for its
readability and simplicity. It was created by Guido van Rossum and first
released in 1991. Python emphasizes code readability with its significant use
of whitespace and clean syntax, which allows programmers to express
concepts in fewer lines of code compared to other languages like Java or
C++.

Easy to Read and Write

Python’s syntax is
clear and concise.

Interpreted Language
Python code is executed
line by line, which makes

Key
debugging easier.

Features: Dynamically Typed

No need to declare
variable types explicitly.

Extensive Libraries
Has a rich set of libraries
and frameworks for
various tasks.

You Know?

Python is a versatile and powerful programming language used in


various fields, from web development to data science.

3
Here are some key benefits that make
Python a favorite among programmers:

Increased Portability
Productivity

Python can significantly Python runs on many


boost a programmer’s different platforms and
productivity, allowing systems, enabling your
them to accomplish up programs to reach a
to ten times more work wider audience without
in a given time requiring significant
compared to other changes.
languages.

Internet of
Things (IoT)

Python is widely used in


the IoT industry to
control smart devices.
These devices can be
controlled by voice
commands or mobile
apps, making them more
interactive.

Framework Flexibility

Python has numerous Python's versatility


frameworks that provide a enables its application
skeleton for different across various industries,
types of applications, increasing job
speeding up development opportunities. Skills can
and reducing errors. be transferred to
Example: Web frameworks different fields like
like Django and Flask help network administration or
in quickly building web IT security if desired.
applications.

4
1.2 HISTORY OF PYTHON

Python was created by Guido Van Rossum.


Illustration: Unnikrishnan

Present
Python 2
2020 End-of-Life
Declared
Declared
Python 2.7's 2015
End-of-Life

2008 Released
Python 3.0
Released
Python 2.0 2000
Released
1994 Python 1.0

Implementation
started 1989
Python
1980 Conceived

You Know?

The name of the Python programming language comes from an old


BBC television comedy sketch series called Monty Python’s Flying
Circus.

5
1.3 SETTING UP PYTHON

Before you start coding, you need to set up your Python environment. Follow
these steps to install Python on your computer:

Download Python:
Go to the official Python website and download the latest version.

Install Python:
Run the installer and follow the instructions. Make sure to check the box that
says "Add Python to PATH."

Verify Installation:
Open a terminal (Command Prompt on Windows) by press ‘Win + R’, type
‘cmd’ and press ‘Enter’.
Check the Python version by type ‘python --version’. You should see the
installed Python version to confirm a successful installation.
Check the pip version by type ‘pip --version’ and press ‘Enter’. You should
see the installed pip version to confirm that pip is also installed.

Install a Python IDE:


While Python comes with IDLE (Integrated Development and Learning
Environment), you might want to install a more advanced Integrated
Development Environment (IDE) for easier coding. Popular IDEs for Python
include:
PyCharm:
Go to the PyCharm website.
Download the Community Edition (free) and install it following the
instructions on the website.
VS Code:
Go to the VS Code website.
Download and install Visual Studio Code.
Install the Python extension from the VS Code marketplace for Python
support.

How to install Python


3.12.3 on Windows 11

6
1.4 BASIC CHARACTERISTICS OF PYTHON PROGRAMMING SYNTAX
Python syntax is the set of rules that dictate how Python code should be
written. Here are the key aspects:

Indentation

Indentation is crucial in Python to define code blocks like functions,


loops, and conditional statements.
Consistent indentation is required to maintain the correct structure of
the code.
Use leading whitespace (either tabs or spaces, but not both) to set the
indentation level of a line. By default, a single indentation level in Python
is four spaces (or one tab).

Example:

Whitespace

Python is sensitive to whitespace, meaning the amount of indentation


matters.

Good indentation:

Bad indentation (can cause errors):

7
Colon (:) for Code Blocks

Use a colon (:) to start a code block in loops, conditionals, and function
definitions.

Example:

Comments

Comments are used to add notes and explanations in the code.


Single-line comments start with #.
Multi-line comments can be enclosed in triple quotes (" " ") or (' ' ') or
highlight selected lines and press ‘Ctrl + /’.

Example:

8
Variables & Assignment

Variables are used to store data. Python supports various data types like
integers, floats, strings, and booleans.
Variables are created by assigning values using the = operator.
Python is dynamically typed, meaning the variable type is determined at
runtime.

Example:

Data Types

Python supports various data types like integers, floats, strings, lists, tuples,
and dictionaries.

Example:

Functions

Functions are defined using the def keyword, followed by the function
name and parameters.
The function body must be consistently indented.

Example:

9
1.5 VARIABLES AND BASIC INPUT/OUTPUT IN PYTHON

Understanding these fundamentals is critical for anyone starting out with


Python programming, as they form the foundation for more advanced topics.

Variables
Store data that can be referenced and
manipulated throughout a program. In Python,
you don't need to declare a variable type
explicitly. The type is inferred from the value
you assign to the variable.

Assigning Values to Variables

Dynamic Typing
Python employs dynamic typing, allowing
you to change a variable’s type by assigning
it a value of a different type.

Variable Names
Should begin with a letter (a-z, A-Z) or an
underscore (_), followed by letters, underscores,,
or digits (0-9), and they are case-sensitive.

10
Input/Output

You can take user input and print output to the console. Python provides
the input() function to read user input and the print() function to display
output.

Using the input() Function

in Python, the input() function is used to take input from the user. It reads a
line from the input (usually from the keyboard), converts it into a string, and
returns that string.

Basic Usage:
The simplest use of input() is to prompt the user to enter some data:

How it Works:

Prompting the User: The string provided as an argument to input() is


displayed as a prompt to the user.

Reading the Input: The user types something and presses Enter.

Returning the Input: The entered text is returned as a string.

Example:

11
Converting Input Data Types

Since input() always returns a string, you might need to convert the input to
another data type, such as an integer or float, if necessary.

Example: Converting Input

Example: Using input() with Different Data Types

Using the print() Function

The print() function is used to output data to the console. You can use it to
display strings, numbers, variables, and more.

Basic Usage

The simplest use of print() is to display a string:

Printing Variables

12
2

Using F-Strings for Formatted Output

F-strings (formatted string literals) are a way to format strings by


embedding expressions inside curly braces {}.

Example: Combining Text and Variables

Arithmetic Operations

Perform basic arithmetic operations such as addition, subtraction,


multiplication, and division.

Try the 1. Create variables to store your age, height, and name. Print
following
exercises in them out.
the 2. Write a program that takes two numbers as input and prints
interactive
coding their sum.
window: 3. Create a simple calculator that performs addition,
subtraction, multiplication, and division based on user input.

13
1.6 WRITING YOUR FIRST PYTHON PROGRAM
Before writing your first program, let’s check the keywords in Python. You
can find all the keywords using the keyword module, which is included in
Python's standard library. Here's a simple way to list all the keywords.

This will output a list of all the keywords in Python. Keywords are reserved
words that have special meaning and cannot be used as identifiers (variable
names, function names, etc.).

Now, let’s write your first Python program! We’ll start with the traditional
"Hello, World!" example.

Example:

In Python, the print() function is used to output text and other information
to the console. It's among the most widely used features for information
display, troubleshooting, and user interaction.

Here’s a basic overview of how print() works and some of its features:

Basic Usage
The simplest use of print() is to output text:

Printing Multiple Items


You can print multiple items by separating them with commas. print() will
add a space between each item:

14
String Formatting
You can use formatted strings (f-strings) to include variables and
expressions within your print statement:

End and Separator Parameters


The print() function has optional parameters end and sep:
sep: Specifies the separator between items. The default is a space.
end: Specifies what to print at the end. The default is a newline
character (\n).

Example with sep:

Example with end:

Example of All Parameters Together

4. Write a program that takes the width and height of a


Try the rectangle as input and calculates its area.
following 5. Write a program to convert temperature from Celsius to
exercises in
the Fahrenheit.
interactive
coding
window:

6. Write a program that asks the user for their birth year, then
calculates and prints their age.

15
CODE HERE
Interactive Coding Practices
Chapter 1

1. C1 Coding Practices: Variables, Addition and Simple


Calculator.
2. C1 Coding Practices: Area, Temperature and Age.

Click here for the instruction to Fork and Use a Repl on Replit.com

C
S
L
C
I Platform: Replit.com
A
C
N
K

16
1.7 TEST YOUR KNOWLEDGE

C
S
L
Chapter 1 Python C
I
C
Overview (Quizizz) A
N
K

17
C
S
L
Chapter 1 Python C
I
C
Overview (Wordwall) A
N
K

18
SUMMARY AND FURTHER READING

In this chapter, you've learned the basics of Python, including what Python
is, its history, how to set it up, and its basic syntax. You also explored how
to work with variables and basic input/output operations, and you wrote
your first Python program.

Steps:

Continue to the next chapter where we'll dive into Python's modules.
Explore additional resources and exercises in the eBook to strengthen your
understanding.

Interactive Quiz:

Test your knowledge with a short interactive quiz. Answer the questions
based on what you've learned in this chapter.

19
CHAPTER 2
MODULE
OVERVIEW

20
OBJECTIVES
In this chapter, we will look at Python modules, which let you break up your
code into more manageable chunks. Modules are essential for structuring
large programs, promoting code reuse, and improving readability. By the end
of this chapter, you’ll understand how to create and use modules
effectively.

2.1 WHAT IS MODULE?


A module in Python is a file containing Python definitions and statements.
Modules can define functions, classes, and variables. They can also include
runnable code. The code in a module can be reused by importing it into
other modules or scripts.

Key Points:

You can import


modules into other Modules promote
modules or scripts code reusability
using the import and organization.
Modules are statement. By dividing
single files with This allows you code into
a .py extension. to reuse modules, you
functions, can keep your
classes, and programs
variables defined modular and
in the module. maintainable.

You can list all the modules installed in Python. Here are the most common
methods:

pip list pip freeze

This is the most This command


straightforward way to provides a similar
Using the pip see all installed output to pip list but
Command packages. formats it in a way
1. Open your terminal
or command that is easy to copy
prompt. into a requirements.txt
2. Run the following file.
command: pip list pip freeze

21
2.2 IMPORTING MODULES
To use a module in your code, you need to import it. Python provides several
ways to import modules:

Import the Entire Module:

Example:

Import Specific Attributes from a Module:

Example:

Import All Attributes from a Module:

Example:

22
2.3 CREATING YOUR OWN MODULES

You can create your own modules by writing Python code in a .py file. Let’s
create a simple module and use it in another script.

Create a Module File: Create a file named my_module.py and add the
following code:

Import and Use the Module: Create another file named main.py and add
the following code:

23
2.4 BASIC MODULE EXAMPLE

STEP 1: Create the Module

Create a file named mymodule.py.

EXPLANATION
Module File (mymodule.py):
Function greet(name): This function takes a name as input and
returns a greeting string.
Function add(a, b): This function takes two numbers as inputs and
returns their sum.
Class Person: This class represents a person with attributes name
and age, and a method info() that returns a formatted string with the
person's information.

24
STEP 2: Use the Module

Create another file named main.py in the same directory.

EXPLANATION
Main File (main.py):
Importing the Module: The import mymodule statement imports the
mymodule.py file so that its functions and classes can be used in
main.py.
Using greet Function: Calls mymodule.greet("Inara")") to greet Inara
and prints the result.
Using add Function: Calls mymodule.add(10, 5) to add two numbers
and prints the result.
Using Person Class: Creates an instance of Person with the name
"Irhash" and age 30, and prints the person's information using the info
method.

25
Running the Example: To see the output, run the main.py script:

python main.py

Output:

This example demonstrates the basic structure and usage of a Python


module. You can expand the module with more functions and classes as
needed, and import it into other scripts to reuse the code.

2.5 BUILT-IN MODULE

Python comes with a rich set of built-in modules that you can use to
perform various tasks. Some commonly used built-in modules include:

random datetime math os


Generates Manipulates Provides Interacts with
random dates and times. mathematical the operating
numbers. functions. system

Examples:

Using the random Module:

26
Using the datetime Module:

Using the math Module:

In this example, you will write a Python program that uses the math module
to perform various mathematical operations, including calculating the
square root, factorial, power, and trigonometric functions.

27
Using the os Module:

In this example, we will write a Python program that uses the os module to
perform various file and directory operations, such as listing files in a
directory, creating a directory, and checking for the existence of a file or
directory.

28
1. Try modifying the program to create a new file in the new
directory and then list all files in that directory.
Try the
2. Create your own module with two functions: one for
following greeting a user and another for adding two numbers. Then,
exercises in
the
import and use this module in another script.
interactive 3. Try using the random and datetime modules to perform
coding
window: tasks such as generating random numbers and displaying
the current date and time.
4. Try modifying the program to calculate and print the square
root, factorial, power, and trigonometric functions for
different numbers and angles.

2.6 PRACTICAL EXERCISES

Exercise 1: Creating and Using a Module


1. Create an advanced calculator module that includes functions for
addition, subtraction, multiplication, division, square root, factorial,
power, and trigonometric calculations (sine, cosine, and tangent).
2. Import this module and perform calculations based on user input.

Exercise 2: Using Built-in Modules


1. Write a program that uses the os module to list all files in the current
directory.
2. Write a program that uses the datetime module to print the current date
in the format YYYY-MM-DD.

29
CODE HERE
Interactive Coding Practices
Chapter 2

1. C2 Coding Practices: Modules.


2. C2 Exercise 1: Creating and Using a Module.
3. C2 Exercise 2: Using Built-in Modules.

Click here for the instruction to Fork and Use a Repl on Replit.com

C
S
L
C
I Platform: Replit.com
A
C
N
K

30
2.7 TEST YOUR KNOWLEDGE

C
S
L Chapter 2 Module
C
I Overview (Quizizz) A
C
N
K

31
SUMMARY AND FURTHER READING

In this chapter, you’ve learned about Python modules, how to import them,
and how to create your own. You’ve also explored some built-in modules
and practiced using them.

Steps:

Continue to the next chapter where we'll dive into Python's modules.
Explore additional resources and exercises in the eBook to strengthen your
understanding.

Interactive Quiz:

Test your knowledge with a short interactive quiz. Answer the questions
based on what you've learned in this chapter.

32
CHAPTER 3
CONDITIONAL
&LOOPING
O VERVIEW
33
OBJECTIVES
In this chapter, we will explore the concepts of conditional statements and
loops in Python. These are essential for controlling the flow of a program,
making decisions, and performing repetitive tasks efficiently

3.1 CONDITIONAL STATEMENTS


Conditional statements allow you to execute different blocks of code based
on certain conditions whether a condition is true or false. They are
fundamental for controlling the flow of a program. Python provides several
types of conditional statements:

3.1.1 if statements

Concept

The if statement tests a condition.


If the condition is True, the code
block under the if statement is Syntax
executed.

Example

Output

34
3.1.2 elif statements

The elif (short for else if) statement checks another


Concept condition if the previous conditions were False.

Syntax

Example

Output

3.1.3 else statements

The else statement catches anything which isn't


Concept
caught by the preceding conditions.

Syntax

Example

Output

35
DETAILED EXAMPLE
Let's look at a more detailed example that uses if, elif, and else statements
together.

EXAMPLE OUTPUT

EXPLANATION
1. The code first checks if score is
greater than or equal to 90. If
true, it prints "Grade: A".
2. If the first condition is false, it
checks if score is greater than
or equal to 80. If true, it prints
"Grade: B".
3. This process continues with
additional elif statements
checking for grades C and D.
4. If none of the if or elif
conditions are true, the else
block executes and prints
"Grade: F".

COMBINING CONDITIONS
You can combine multiple conditions using logical operators (and, or, not).

EXAMPLE

OUTPUT

36
NESTED CONDITIONALS
Nested conditionals are conditionals inside other conditionals, allowing for
more complex decision-making.

EXAMPLE

OUTPUT

3.1.4 PRACTICAL EXERCISES

Exercise 1: Voting Eligibility Checker


Write a Python program to check if a person is eligible to vote. A person is
eligible if they are 18 years or older.

Exercise 2: Temperature Check


Write a Python program to categorize the weather based on temperature
input:
Above 30: "It's hot"
Between 20 and 30: "It's warm"
Below 20: "It's cold"

37
3.2 LOOPS
Loops are used to execute a block of code repeatedly. Python provides two
main types of loops:

for loop
A for loop is used to iterate over a sequence (such as a list, tuple,
dictionary, set, or string).

Syntax:

Example:

Output:

while loop
A while loop repeatedly executes a target statement as long as a given
condition is true.

Syntax:

Example:

Output:

38
LOOP CONTROL STATEMENT (break, continue, pass)

break Example: Output:

The break
statement
terminates the
loop
prematurely.

continue Example: Output:

The continue
statement skips
the rest of the
code inside the
loop for the
current iteration
only.

pass Example: Output:

The pass
statement is a
null operation;
nothing happens
when it
executes. It is
used as a
placeholder.

39
3.3 COMBINING CONDITIONAL STATEMENTS AND LOOPS
You can combine conditional statements and loops to perform more
complex tasks. For example, you can use a loop to iterate over a list of
numbers and use conditional statements to print whether each number is
even or odd.

3.4 PRACTICAL EXERCISES

Exercise 3: Sum of Natural Numbers


Write a Python program to calculate the sum of the first 10 natural numbers
using a while loop.

Exercise 4: Multiplication Table


Write a Python program to print the multiplication table of a given number
using a for loop.

Exercise 5: Factorial Calculation


Write a Python program to calculate the factorial of a given number using a
for loop.

Exercise 6: Prime Numbers


Write a Python program to print all prime numbers between 1 and 100 using
a for loop and conditional statements.

Exercise 7: FizzBuzz
Example:
Write a Python program that prints the numbers from 1 to 50. For multiples
of three, print "Fizz" instead of the number, and for multiples of five, print
"Buzz". For numbers that are multiples of both three and five, print
"FizzBuzz".
Output:

40
CODE HERE
Interactive Coding Practices
Chapter 3

1. C3 Practical Examples.
2. C3 Practical Exercises.

Click here for the instruction to Fork and Use a Repl on Replit.com

C
S
L
C
I Platform: Replit.com
A
C
N
K

41
3.5 TEST YOUR KNOWLEDGE

C
S
L Chapter 3 Conditional and
C
I Looping Overview (Google A
C Form) N
K

42
SUMMARY AND FURTHER READING

In this chapter, you’ve learned about conditional statements and loops in


Python. You’ve also practiced writing programs that use these constructs to
control the flow of execution and perform repetitive tasks.

Continue to the next chapter where we’ll dive into Python’s functions
and how to define and call them.
Explore additional resources and exercises in the eBook to strengthen
your understanding.

Interactive Quiz:

Test your knowledge with a short interactive quiz. Answer the questions
based on what you've learned in this chapter.

43
CHAPTER 4
DATA
STRUCTURES
O VERVIEW
44
OBJECTIVES
In this chapter, we will explore Python's built-in data structures. These are
essential for storing and organizing data efficiently. We will cover lists,
tuples, dictionaries, and sets.

4.1 WHAT IS DATA STRUCTURES?


Data structures are essential tools for organizing and storing data efficiently.
In Python, understanding how to use different data structures is crucial for
writing efficient and effective code.

IMPORTANCE OF DATA STRUCTURES IN PYTHON


Data structures allow you to manage collections of data,
enabling efficient data manipulation, storage, and retrieval.
They are fundamental for solving complex problems and
optimizing performance.

4.2 ORDERED 4.2 .1 LISTS


DATA
STRUCTURES

Definition and Characteristics


Lists are ordered, mutable collections that can hold a variety of data
types.
They allow duplicate elements.

Creating List Accessing Elements

Modifying Lists

Common List Methods

45
4.2 ORDERED
DATA
4.2.2 TUPLES STRUCTURES

Definition and Characteristics


Tuples are ordered, immutable collections that can hold a variety of data
types.
They allow duplicate elements.

Creating Tuples Accessing Elements

Immutability of Tuples

4.2 ORDERED 4.2.3 DICTIONARIES


DATA
STRUCTURES

Definition and Characteristics


Dictionaries are mutable collections of key-value pairs.
As of Python 3.7, dictionaries maintain the insertion order of keys. In
Python 3.6 and earlier, they are unordered.

Creating
Dictionaries

Accessing and
Modifying Values

Dictionary Methods

46
4.3 UNORDERED DATA STRUCTURES

4.3.1 SETS
Definition and Characteristics
Sets are unordered collections of unique elements.
They are mutable but do not allow duplicate elements.

Creating Sets

Adding and Removing Elements

Set Operations (Union, Intersection, Difference)

47
4.4 COMPARING ORDERED AND UNORDERED DATA STRUCTURES

Differences and Use Cases


Lists and tuples maintain
order, making them
suitable for ordered data.
Dictionaries (as of Python
3.7) also maintain order
but are used for key-
value pairs.
Sets are used when
unique elements are Performance Considerations
needed without a specific Lists provide efficient
order. index-based access but
can be slower for
insertions and deletions
in large lists.
Dictionaries offer fast
lookups, insertions, and
deletions.
Sets are optimized for
membership tests and
set operations.
When to Use Each Data
Structure
Use lists for ordered
collections that may
change over time.
Use tuples for fixed
collections of related
items.
Use dictionaries for key-
value pair mappings.
Use sets for collections
of unique elements.

48
4.5 PRACTICAL EXERCISES
List Operations
Write a Python program to create a list of your favorite movies, add a new
movie, and print the updated list.

Tuple Operations
Write a Python program to create a tuple of your favorite books and print
each book on a new line.

Dictionary Operations
Write a Python program to create a dictionary with information about your
favorite movie (title, director, year) and print each key-value pair on a new
line.

Set Operations
Write a Python program to create a set of your favorite sports, add a new
sport, and print the updated set.

49
CODE HERE
Interactive Coding Practices
Chapter 4

1. C4 Practical Exercises.

Click here for the instruction to Fork and Use a Repl on Replit.com

C
S
L
C
I Platform: Replit.com
A
C
N
K

50
4.6 TEST YOUR KNOWLEDGE

C
S
L
Chapter 4 Data Structures C
I
C
Overview (ProProfs) A
N
K

51
C
S
L
Chapter 4 Data Structures C
I
C
Overview (Wordwall) A
N
K

52
SUMMARY AND FURTHER READING

In this chapter, you’ve learned about data structures such as list, tuples,
dictionaries and sets in Python. You’ve also practiced writing programs that
manipulate and work with data structures effectively.

Continue to the next chapter where we’ll dive into Python’s functions
and how to define and call them.
Explore additional resources and exercises in the eBook to strengthen
your understanding.

Interactive Quiz:

Test your knowledge with a short interactive quiz. Answer the questions
based on what you've learned in this chapter.

53
Provide your feedback for this ebook to help us improve

FEEDBACK
your learning experience.

54
RELATED WORK

Scan
or
C li c k

55
REFERENCES
Amit Thinks. (2024, April 11). How to install Python
3.12.3 on Windows 11. YouTube.
https://www.youtube.com/watch?v=1nMYaJiHBGw

JetBrains. (2019). PyCharm. JetBrains.


https://www.jetbrains.com/pycharm/

Python Institute. (n.d.). About Python.


https://pythoninstitute.org/about-python

Python. (2019). Download Python.


https://www.python.org/downloads/

Replit, Inc. (n.d.). Replit: The collaborative browser-


based IDE. Replit. https://replit.com/

Visual Studio Code. (2016, April 14). Visual Studio Code.


https://code.visualstudio.com/Download

56
LEARN PYTHON ELEMENTS

e ISBN 978-967-2904-86-1

9 789672 904861

POLITEKNIK MERSING
(online)

You might also like