Learn Python Elements Complete Book
Learn Python Elements Complete Book
PYTHON
ELEMENTS
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
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.
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.
Python’s syntax is
clear and concise.
Interpreted Language
Python code is executed
line by line, which makes
Key
debugging easier.
No need to declare
variable types explicitly.
Extensive Libraries
Has a rich set of libraries
and frameworks for
various tasks.
You Know?
3
Here are some key benefits that make
Python a favorite among programmers:
Increased Portability
Productivity
Internet of
Things (IoT)
Framework Flexibility
4
1.2 HISTORY OF PYTHON
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?
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.
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
Example:
Whitespace
Good indentation:
7
Colon (:) for Code Blocks
Use a colon (:) to start a code block in loops, conditionals, and function
definitions.
Example:
Comments
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
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.
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.
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:
Reading the Input: The user types something and presses Enter.
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.
The print() function is used to output data to the console. You can use it to
display strings, numbers, variables, and more.
Basic Usage
Printing Variables
12
2
Arithmetic Operations
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:
14
String Formatting
You can use formatted strings (f-strings) to include variables and
expressions within your print statement:
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
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.
Key Points:
You can list all the modules installed in Python. Here are the most common
methods:
21
2.2 IMPORTING MODULES
To use a module in your code, you need to import it. Python provides several
ways to import modules:
Example:
Example:
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
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
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:
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:
Examples:
26
Using the datetime 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.
29
CODE HERE
Interactive Coding Practices
Chapter 2
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.1 if statements
Concept
Example
Output
34
3.1.2 elif statements
Syntax
Example
Output
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
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)
The break
statement
terminates the
loop
prematurely.
The continue
statement skips
the rest of the
code inside the
loop for the
current iteration
only.
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.
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
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.
Modifying Lists
45
4.2 ORDERED
DATA
4.2.2 TUPLES STRUCTURES
Immutability of Tuples
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
47
4.4 COMPARING ORDERED AND UNORDERED DATA STRUCTURES
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
56
LEARN PYTHON ELEMENTS
e ISBN 978-967-2904-86-1
9 789672 904861
POLITEKNIK MERSING
(online)