0% found this document useful (0 votes)
15 views63 pages

CSC301_updated150524

FUD- CSC 301 Copy
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)
15 views63 pages

CSC301_updated150524

FUD- CSC 301 Copy
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

CSC301 LECTURE NOTE:

Structured Programming
2023/2024 Academic Session

Page 1 of 63
Structured Programming:

Structured programming is a programming paradigm that emphasizes a logical and organized


approach to writing code. It aims to improve code readability, maintainability, and reliability
compared to older, unstructured programming styles.
Here are some key characteristics of structured programming:

• Focus on Control Flow: Structured programs use well-defined control flow structures like
loops (for repeating tasks) and conditional statements (for making decisions) to organize
the program's execution.

• Use of Subroutines (Functions): Breaking down complex tasks into smaller, reusable
subroutines (functions) promotes modularity and code reusability.

• Emphasis on Readability: Structured programming encourages the use of clear and


consistent coding practices, making the code easier to understand for both the programmer
who wrote it and others who might need to read or modify it later.

Benefits of Structured Programming:

• Reduced Errors: The organized structure helps prevent logical errors and makes
debugging easier.

• Easier Maintenance: Modular code with clear functionality allows for easier
modifications and additions to the program in the future.

• Improved Collaboration: Well-structured code is easier for other programmers to


understand, facilitating teamwork and code sharing.

Structured Programming Elements:

Structured programming relies on a few fundamental elements to achieve its goals:

• Sequence: The basic building block, where instructions are executed one after another in
the order they are written.

• Selection: Conditional statements (like if/else) allow the program to choose between
different execution paths based on certain conditions.

Page 2 of 63
• Iteration: Loops (like for/while) enable the program to repeat a block of code a specific
number of times or until a certain condition is met.

• Subroutines (Functions): Reusable blocks of code that perform specific tasks, improving
code organization and reusability.

Common Structured Programming Constructs:

• if statements: Execute a block of code if a specific condition is true.

• else statements: Provide an alternative set of instructions if the condition in the "if"
statement is false.

• for loops: Repeat a block of code a specific number of times.

• while loops: Repeat a block of code as long as a certain condition remains true.

• Functions: Independent blocks of code that can be called from different parts of the
program to perform specific tasks.

Structured design principles


Structured design principles are a set of guidelines that promote creating well-organized,
maintainable, and efficient software systems. These principles build upon the foundation of
structured programming concepts you previously learned about. Here are some key structured
design principles:

1. Modularization:

o Break down the system into smaller, independent modules that perform specific
functionalities.

o Each module should have a well-defined purpose, clear inputs, and well-defined
outputs. This promotes code reusability and easier maintenance.

2. Information Hiding:

o Modules should encapsulate their internal data and implementation details.

Page 3 of 63
o They should only expose necessary functionalities through well-defined interfaces
(functions or methods). This reduces complexity and dependencies between
modules.

3. Low Coupling:

o Modules should be loosely coupled, meaning they should depend as little as


possible on the internal workings of other modules.

o This minimizes the impact of changes in one module on other parts of the system.

4. High Cohesion:

o Each module should focus on a single, well-defined functionality.

o This improves code clarity and maintainability as the purpose of each module is
clear.

5. Control Flow Hierarchy:

o The overall structure of the system should follow a clear hierarchy.

o High-level modules should control the flow of execution, delegating tasks to lower-
level modules. This promotes organization and simplifies reasoning about the
system's behavior.

6. Data Abstraction:

o Focus on data structures and their manipulation rather than the specific
implementation details of data storage.

o This allows for flexibility in data storage and retrieval mechanisms without
affecting the core functionality of the modules.

These principles are interrelated and work together to create robust software systems. By
following these guidelines, developers can create code that is:

• Easier to understand: Clear module structure and well-defined interfaces make the code
more readable for both the programmer who wrote it and others who need to maintain it.

Page 4 of 63
• Easier to maintain: Modifications and bug fixes are simpler to implement when the code
is modular and has low coupling.

• More reliable: Fewer dependencies between modules mean that changes in one part are
less likely to cause unintended consequences in other areas.

• More reusable: Well-designed modules with clear functionalities can be reused in different
parts of the system or even in other projects.

Abstraction and modularity are two key concepts that go hand-in-hand in structured design
principles. They both play a crucial role in creating well-organized, maintainable, and efficient
software systems. Here's a breakdown of each concept and how they work together:
Abstraction:

• Concept: Abstraction focuses on hiding the implementation details of a piece of code and
exposing only its essential functionalities. It allows programmers to work with concepts at
a higher level, without worrying about the intricate details of how things work underneath.

• Benefits:

o Simpler Interfaces: Abstraction allows modules to present simple interfaces


(functions or methods) that describe what they do, rather than how they do it. This
makes the code easier to understand and use.

o Focus on Functionality: Programmers can focus on the overall functionality of the


system without getting bogged down in low-level details.

o Flexibility: Abstraction allows for flexibility in implementation. The underlying


mechanisms can be changed without affecting the functionality exposed by the
interface, as long as the expected behavior remains the same.

Modularity:

• Concept: Modularity refers to the practice of breaking down a system into smaller,
independent modules that perform specific tasks. Each module is self-contained and has a
well-defined purpose, inputs, and outputs.

• Benefits:

Page 5 of 63
o Reusability: Modular code can be reused in different parts of the system or even
in other projects. This saves time and effort by avoiding rewriting the same code
multiple times.

o Maintainability: Smaller, well-defined modules are easier to understand, test, and


modify. If a bug is found, it's easier to isolate and fix within a specific module.

o Reduced Complexity: By breaking down the system into smaller components, the
overall complexity is reduced, making it easier to manage and reason about the
system's behavior.

Together:

Abstraction and modularity work together to create well-structured systems. Here's how:

• Modularization provides the foundation: By breaking down the system into modules,
you create opportunities for abstraction.

• Abstraction enhances modularity: By hiding internal details within modules, you create
cleaner interfaces that promote reusability and maintainability.

Example:

Imagine a system for managing a library.

• Modularization: You might create separate modules for tasks like adding books,
searching for books, and managing borrowing and returning.

• Abstraction: Each module would expose functions like "addBook(title, author)" or


"searchBook(title)" without revealing the underlying data structures or database
interactions.

This approach allows programmers to use these modules without worrying about the low-level
details and promotes code reuse across different parts of the library management system.

In essence, abstraction hides the "how" and focuses on the "what," while modularity breaks down
the system into manageable components. Both works together to create clean, maintainable, and
efficient software systems.
Stepwise refinement
Page 6 of 63
Stepwise refinement is a software development technique used to break down a complex problem
into smaller, more manageable pieces. It involves a step-by-step process of taking a high-level
overview of the desired program and gradually adding more detail until you have a complete and
functional program.

Here's a breakdown of the key aspects of stepwise refinement:

• Start with a General Idea: Begin with a broad description of what the program should
accomplish. This initial description might be phrased in plain English, focusing on the
overall functionality.

• Refine into Smaller Steps: Break down the general idea into smaller, more specific steps
or subtasks. Each subtask should be a well-defined unit of functionality that contributes to
achieving the overall goal.

• Repeat the Process: For each subtask, continue to refine it further by breaking it down
into even smaller, more detailed steps. This iterative process continues until each step is
clear, concise, and easily translated into code.

• Implementation: Once the steps are refined to a sufficient level of detail, you can start
writing the actual code for each step.

Benefits of Stepwise Refinement:

• Reduced Complexity: Breaking down a large problem into smaller, more manageable
pieces makes it easier to understand, design, and implement.

• Fewer Errors: By focusing on smaller units of code, it's easier to identify and fix errors
during the development process.

• Improved Maintainability: Well-refined code with clear subtasks is easier to modify and
update in the future as requirements change.

• Modular Design: Stepwise refinement often leads to a more modular design, where the
program is composed of independent, reusable code components.

Here's an example of stepwise refinement:

Imagine you're writing a program to calculate the area of a triangle.


Page 7 of 63
• Initial Idea: Write a program that calculates the area of a triangle.

• Refinement 1: The program should first get the length of the base and height of the triangle
from the user.

• Refinement 2: Once it has the base and height, the program should calculate the area using
the formula (1/2) * base * height.

• Refinement 3: The program should display the calculated area to the user.

Here's another real-world scenario of stepwise refinement:

Imagine you're developing a simple calculator application. Here's how stepwise refinement can be
applied:

1. Overall Functionality: The application performs basic arithmetic operations (addition,


subtraction, multiplication, division) on user-provided numbers.

2. Sub-problems:

o Get user input for two numbers.

o Perform the selected arithmetic operation on the numbers.

o Display the calculated result.

3. Further Refinement:

o Get user input: Prompt the user for the first number, store it in a variable. Repeat
for the second number.

o Perform operation: Based on user selection (addition, subtraction, etc.), use


appropriate mathematical operators on the stored numbers.

o Display result: Format and display the calculated result on the screen.

By following this stepwise refinement approach, you can gradually transform the high-level idea
of calculating the triangle area into a series of well-defined steps that can be implemented as code.
Page 8 of 63
Stepwise refinement is a valuable technique for programmers of all experience levels. It helps to
create well-structured, maintainable, and efficient software systems.

Structured Design Techniques


Structured design (SD) is a systematic approach to designing software applications. It emphasizes
modularity, reusability, and maintainability of the code. Here are some key structured design
techniques:
1. Top-Down Design (Decomposition):
• This technique involves breaking down a complex system into smaller, more manageable
subsystems or modules.
• Each module has a well-defined function and interacts with other modules through clearly
defined interfaces.
• You start by identifying the main functionalities of the system and then progressively
decompose them into smaller, more specific sub-functions.
Imagine you're designing a software application for managing an online bookstore.
Here's how top-down design can be applied:
• Level 1 (Overall System): The system allows users to browse books, add items to
a cart, checkout, and manage their accounts.
• Level 2 (Subsystems):
User Management: Handles user registration, login, and account details.
Inventory Management: Tracks book information, stock levels, and order
processing.
Shopping Cart: Facilitates adding, removing, and managing items before
checkout.
Order Processing: Processes payments, generates invoices, and manages order
fulfillment.
Search and Recommendation: Enables users to search for books and receive
recommendations.
2. Functional Decomposition:
• This technique focuses on identifying the functional requirements of the system and
translating them into functional modules.

Page 9 of 63
• Each module performs a specific task or set of related tasks, and the overall system
functionality is achieved through the coordinated interaction of these modules.
• Data Flow Diagrams (DFDs) are commonly used to represent the flow of data between
modules and external entities (e.g., users, databases). DFDs depict the system at different
levels of detail, providing a clear understanding of how data is processed within the system.

Consider an ATM (Automated Teller Machine) system.


We can decompose its functionality into modules:
Authentication Module: Verifies user identity using PIN or card details.
Account Information Module: Retrieves account balance and transaction history.
Withdrawal Module: Processes withdrawal requests, updates account balance,
and dispenses cash.
Deposit Module: Processes cash deposits and updates account balance.
Transfer Module: Transfers funds between accounts (if applicable).

3. Cohesion and Coupling:


• Cohesion: This refers to the degree of focus and relatedness of the functionalities within a
module. A highly cohesive module performs a single, well-defined task and avoids
unrelated functionalities. This improves code readability, maintainability, and reduces the
likelihood of errors.
Cohesion Example:
High Cohesion: A module responsible for calculating the total cost of items in
a shopping cart, including applying discounts and taxes. This module performs
a single, well-defined task.
Low Cohesion: A module that calculates the total cost, displays order details
on the screen, and updates the inventory database. This mixes unrelated
functionalities and reduces maintainability.
• Coupling: This refers to the level of interdependence between modules. Loosely coupled
modules have minimal dependencies on each other, making them more reusable and easier
to modify independently. Tight coupling can lead to maintenance challenges and difficulty
in isolating and fixing issues.

Page 10 of 63
Coupling Example:
Loose Coupling: Two modules: One retrieves product information from a
database, and another displays it on the user interface. They interact through a
well-defined interface (e.g., function call) without relying on each other's internal
details.
Tight Coupling: A module directly modifies data structures used by another
module. This creates a dependency and makes changes in one module potentially
impact the other, hindering independent maintenance.

4. Modularization:
• This principle emphasizes breaking down the system into independent, self-contained
modules that can be developed, tested, and maintained separately.
• Modules communicate with each other through well-defined interfaces, promoting code
reusability and reducing redundancy.
Think about a word processing application. Here, modules can be:
Document Editor: Handles text input, formatting, and editing functionalities.
Spell Checker: Checks for spelling errors and suggests corrections.
File I/O Module: Opens, saves, and manages document files.
Print Module: Prepares documents for printing and interacts with the printer.

5. Information Hiding:
• This technique focuses on encapsulating the internal implementation details of a module
and only exposing its functionality through a public interface.
• This promotes code security, maintainability, and allows for independent modifications to
the internal implementation without affecting other parts of the system that rely on the
module's functionality.
Consider a library management system. The "BorrowBook" module can:
Public Interface: Function to borrow a book, taking user ID and book ID as input.
Hidden Implementation: Internally, the module verifies user eligibility, updates the
book's availability status in the database, and generates a loan record. Users only interact

Page 11 of 63
with the public interface, unaware of the internal workings, promoting maintainability and
security.
By understanding and applying these techniques, developers can create software that is not only
functional but also well-organized, maintainable, and easier to modify and update as needs evolve.

Benefits of Structured Design:


• Improved Maintainability: Modular design with clear interfaces makes code easier to
understand, modify, and debug.
• Reduced Complexity: Decomposition helps manage complexity by breaking down large
systems into smaller, more manageable units.
• Enhanced Reusability: Well-designed modules can be reused in other projects, promoting
code efficiency, and reducing development time.
• Error Reduction: Modularization and information hiding can help prevent errors from
propagating throughout the system.
• Better Communication: Structured design techniques promote clear documentation and
communication between developers.
By following these techniques, structured design helps create well-organized, maintainable, and
reliable software applications. While there are other design methodologies that have emerged,
structured design remains a valuable foundation for building high-quality software.
Programming Paradigm
A programming paradigm is a fundamental approach or style of programming that defines how
you structure, organize, and solve problems in your code. It provides a set of principles, concepts,
and techniques that shape how you think about and implement computer programs. Here are some
of the most common programming paradigms:
1. Imperative Programming:
• Focus: The focus is on controlling the flow of execution and manipulating the state of
the program to achieve a desired outcome.
• Concept: The programmer gives the computer a series of explicit instructions, step by step,
dictating how to achieve the desired outcome. The program's state (data values) can be
modified as the instructions are executed.
Step-by-Step Instructions:

Page 12 of 63
Imperative programs provide a series of explicit instructions to the computer, outlining
each step it needs to take to solve the problem. These instructions typically involve:
o Assignments: Assigning values to variables to store data.
o Input/Output operations: Reading data from the user or external sources and
displaying results.
o Conditional statements: Making decisions based on certain conditions, like if
statements to execute different code blocks depending on whether a condition is
true or false.
o Loops: Repeating a block of code a specific number of times or until a certain
condition is met (e.g., for loops, while loops).
o Function calls: Reusing pre-written code blocks (functions) to perform specific
tasks.
State Changes:
Imperative programs manipulate the state of the program during execution. This state refers
to the values stored in variables at any given point in time. As the program progresses
through the instructions, the values in variables can change, reflecting the program's current
state.
Example:
Python
# Simple imperative program to calculate the area of a rectangle

length = float(input("Enter the length: "))


width = float(input("Enter the width: "))

area = length * width # Calculate the area

print("The area of the rectangle is:", area)

In this example:
• The user inputs the length and width, which are assigned to variables length and width.

Page 13 of 63
• The area variable is then assigned the product of length and width, representing the
calculated area.
• Finally, the area value is printed, showcasing the program's state at that point (the
calculated area).
Key Characteristics:
• Imperative programs are often procedural, meaning they break down the problem into
smaller, sequential steps.
• Focus on mutability: Variables can be modified throughout the program, allowing for
dynamic changes to the program's state.
• Control flow plays a central role, with conditional statements and loops dictating the
execution path based on conditions and repetitions.
Advantages:
• Suitable for low-level programming: Imperative style offers precise control over
hardware and memory management, making it well-suited for system programming tasks.
• Easier to understand for beginners: The step-by-step approach can be intuitive for those
new to programming, as the logic flows sequentially.
• Widely used: Many popular programming languages (C, C++, Java) are primarily
imperative, making it a familiar and established paradigm.
Disadvantages:
• Can become complex for large projects: Managing complex program flow and state
changes in large imperative programs can be challenging and lead to code that's difficult
to maintain.
• Error-prone: Imperative code relies heavily on state management, which can increase the
risk of bugs if variables are not handled carefully.
In conclusion, imperative programming provides a fundamental approach for controlling
the flow of execution and manipulating program state. While it offers advantages in certain
areas, understanding its strengths and limitations is crucial for choosing the right paradigm
for your programming endeavors.
2. Object-Oriented Programming (OOP):
• Focus: Organizing code around objects, which encapsulate data (attributes) and related
functionalities (methods).

Page 14 of 63
• Concept: OOP promotes a more modular and reusable approach to programming by
creating objects that represent real-world entities or concepts. These objects have attributes
that hold their data and methods that define their behavior. Objects interact with each other
through method calls, promoting collaboration and information hiding (encapsulating data
within the object).
Example:
Imagine a program simulating a library. You could create objects like Book with attributes like
title, author, and genre. The Book object might have methods like borrow and return. Separately,
you could have a Library object that manages a collection of Book objects and provides
functionalities like searching for books or checking availability.
Advantages:
• Modularity and Reusability: Objects can be reused in different parts of the program or
even in other projects, promoting code maintainability and efficiency.
• Data Hiding: Encapsulation protects data integrity and promotes better control over how
data is accessed and modified.
• Real-World Modeling: OOP allows you to model real-world entities and their
relationships, making the code more intuitive and easier to understand.
Disadvantages:
• Steeper Learning Curve: OOP concepts like inheritance and polymorphism can be more
complex to grasp for beginners compared to imperative programming.
• Overhead: Creating and managing objects can introduce some overhead compared to
simpler procedural approaches.

3. Functional Programming:
• Focus: Treating computation as the evaluation of mathematical functions.
• Concept: Functions are first-class citizens, meaning they can be assigned to variables,
passed as arguments to other functions, and returned as results. Functions avoid modifying
existing data and instead produce new outputs based on their inputs. This promotes
immutability and reduces side effects, leading to more predictable code.

Page 15 of 63
• Example: Languages like Haskell and Lisp are known for functional programming. You
might write a function to calculate the factorial of a number, taking the number as input
and returning the factorial as output, without altering any external variables.
Advantages:
• Immutability: Leads to more predictable and less error-prone code, as data remains
constant throughout the program.
• Declarative Style: Focuses on what the program should achieve rather than how, allowing
for concise and readable code.
• Parallelization: Functional programs are often well-suited for parallel processing due to
the lack of reliance on mutable state.
Disadvantages:
• Not all problems fit well: Certain tasks that involve modifying existing data structures
might be less intuitive in a functional style.
• Debugging: Reasoning about how functions transform data can sometimes be trickier
compared to imperative code with explicit state changes.

4. Declarative Programming:
• Focus: Specifying the desired outcome or goal, rather than the specific steps to achieve it.
• Concept: The programmer declares what the program should do, and the underlying
system figures out how to achieve it. This can involve logic programming, where rules and
relationships are defined, or markup languages like HTML, where you specify the structure
and content of a web page without explicitly controlling every detail of its display.
• Example: SQL (Structured Query Language) is a declarative language. You specify the
data you want to retrieve from a database using a query, and the database management
system handles the details of fetching the data efficiently.
Advantages:
• Conciseness: Declarative languages often allow you to express complex logic in a compact
and readable manner.
• Focus on What: You focus on the desired outcome, letting the system handle the "how."

Page 16 of 63
• Domain-Specific Languages (DSLs): Declarative languages can be tailored to specific
domains, making them more intuitive for those working in that area (e.g., SQL for
databases).
Disadvantages:
• Limited Control: You might have less control over the exact execution flow compared to
imperative programming.
• Debugging: Debugging issues in declarative code can sometimes be more challenging due
to the separation between what you specify and how it's achieved.

5. Procedural Programming:
• Focus: Breaking down a program into procedures (functions) that perform specific tasks.
• Concept: Like imperative programming, but with an emphasis on dividing the program
logic into smaller, reusable procedures. This promotes code modularity and organization.
• Example: Procedural programming can be seen in many imperative languages. You might
create separate functions for calculating the area of a circle, the volume of a cube, and so
on, making the code more organized and easier to reuse.
Choosing a Paradigm:
The most suitable paradigm for a project depends on the problem you're trying to solve and the
desired qualities of your code. Here's a general guideline:
• Imperative: Well-suited for low-level tasks, system programming, and controlling
hardware.
• OOP: Effective for modeling real-world entities and building complex systems with
reusable components.
• Functional: Ideal for tasks requiring immutability, avoiding side effects, and working with
data streams.
• Declarative: Useful for expressing desired outcomes concisely and leveraging built-in
optimization in systems.
• Procedural: Good for organizing code into smaller, reusable blocks, often used alongside
other paradigms.

Page 17 of 63
Remember, some languages can support multiple paradigms to varying degrees. Understanding
these paradigms will empower you to choose the right approach for your programming endeavors
and write more effective, maintainable, and well-structured code.

Structured Programming with Python


Brief History of Python
Late 1980s:
• Conception: Guido van Rossum, at Centrum Wiskunde & Informatica (CWI) in the
Netherlands, began developing Python as a successor to the ABC programming language.
• Goals: He aimed for a language that was:
o Easy and intuitive to learn and use.
o Open-source and community-driven.
o Readable and maintainable, with code resembling plain English.
o Suitable for everyday tasks, allowing for rapid development.
1991:
• Version 0.9.0: The initial public release of Python.
1994:
• Version 1.0: Introduced key features like lambda functions, map, filter, and reduce,
expanding Python's capabilities.
2000:
• Version 2.0: Added significant features like list comprehensions and garbage collection,
improving Python's efficiency and memory management.
2008:
• Version 3.0 (Python 3.000): A major revision that addressed limitations in Python 2 but
introduced backward compatibility challenges.
• Focus on the Future: Python 3 paved the way for modern language features and
improvements.
2020:
• Version 2.7.18: The last official release of Python 2. The development community shifted
focus entirely to Python 3.

Page 18 of 63
Present Day:
• Python's Rise: Python has become one of the most popular programming languages
worldwide.
• Widespread Use: It's employed in various domains, including web development, data
science, machine learning, scripting, automation, and scientific computing.
• Active Community: A large and active developer community contributes to Python's
ongoing development, libraries, and frameworks.
Key Takeaways:
• Python's design philosophy emphasizes readability, ease of use, and code maintainability.
• It has evolved significantly since its inception, becoming a versatile and powerful
language.
• Python's active community and vast ecosystem of libraries and frameworks contribute to
its continued success.

Taxonomy of Python Types


Python, like many programming languages, has a rich type of system that helps categorize data
and ensures program correctness. Here's a breakdown of the key types in Python:
1. Built-in Types:
These are fundamental types provided by the Python language itself. They represent basic data
elements used for various operations.
• Integers (int): Represent whole numbers, positive, negative, or zero (e.g., 10, -5, 0).
• Floats (float): Represent decimal numbers (e.g., 3.14, -10.25).
• Strings (str): Represent sequences of characters enclosed in quotes (single ‘’ or double ""
quotes) (e.g., "Hello", 'World').
• Booleans (bool): Represent logical truth values, True or False.
• None: A special value indicating the absence of a value.
2. Sequences:
These types represent ordered collections of items that can be accessed by index.
• Lists (list): Mutable ordered sequences of elements enclosed in square brackets [].
Elements can be of different types (e.g., [1, "apple", 3.14]).

Page 19 of 63
• Tuples (tuple): Immutable ordered sequences of elements enclosed in parentheses ().
Elements cannot be changed after creation (e.g., (10, "banana", True)).
3. Sets (set):
• Unordered collections of unique elements enclosed in curly braces {}. Duplicates are
automatically removed. (e.g., {1, "orange", 2, "orange"})
4. Dictionaries (dict):
• Unordered collections of key-value pairs enclosed in curly braces {}. Keys must be unique
and immutable (often strings). Values can be of any type. (e.g., {"name": "Alice", "age":
30, "city": "New York"})
5. Composite Types:
These types are user-defined and combine existing types to create more complex data structures.
• Classes: Blueprints for creating objects with attributes (data) and methods (functions).
• Modules: Reusable blocks of code containing functions, classes, and variables.
Special Cases:
• Byte Arrays (bytes): Represent sequences of raw bytes, often used for binary data or
interacting with external systems.
Type Checking and Conversions:
• Python is dynamically typed, meaning variable types are not explicitly declared. However,
type checks can be performed using the type() function.
• Type conversions (casting) can be done explicitly using functions like int(), float(), str(),
etc.
Remember, understanding these core types and their usage is essential for writing effective Python
programs. By leveraging the appropriate types for your data, you can ensure code clarity,
correctness, and memory efficiency.

Characteristics of Python program


Here are some of the key characteristics of a Python program:
Readability:
• Clear and Concise Syntax: Python code is known for its readability, resembling plain
English. It uses indentation and whitespace to define code blocks, making the structure
clear. This contrasts with languages that rely on curly braces or other delimiters.

Page 20 of 63
Interpreted Language:
• No Compilation Needed: Python is an interpreted language. This means the code is
executed line by line by an interpreter at runtime, rather than being compiled into machine
code beforehand. This allows for faster development cycles and easier debugging.
Dynamically Typed:
• No Explicit Type Declarations: Unlike some languages where you need to declare the
data type of a variable (e.g., integer, string), Python is dynamically typed. The interpreter
infers the type of a variable based on the value assigned to it. This can make Python more
flexible but requires careful attention to avoid type errors.
Object-Oriented:
• Supports Object-Oriented Programming (OOP): Python allows you to define classes
and objects, which encapsulate data (attributes) and functionality (methods) related to a
particular concept. This promotes code modularity, reusability, and maintainability.
However, Python doesn't strictly enforce object-oriented principles, allowing for
procedural and functional programming styles as well.
Use of Built-in Data Structures:
• Rich Set of Data Types: Python provides various built-in data structures like lists, tuples,
dictionaries, and sets. These data structures offer efficient ways to store and organize
different types of data.
Focus on Code Maintainability:
• Emphasis on Readability: As mentioned earlier, Python's design philosophy prioritizes
clear and readable code. This is achieved through features like indentation, meaningful
variable names, and docstrings (explanatory comments).
Extensive Libraries and Frameworks:
• Large Ecosystem: Python offers a vast collection of third-party libraries and frameworks
that extend its functionalities. These libraries provide pre-written code for various tasks,
saving you time and effort in development.
Cross-Platform Compatibility:
• Runs on Multiple Operating Systems: Python code can be written and executed on
different operating systems like Windows, macOS, and Linux with minimal changes. This
makes it a versatile language for various development environments.

Page 21 of 63
Automatic Memory Management:
• Garbage Collection: Python handles memory management automatically using a process
called garbage collection. This removes unused objects from memory, preventing memory
leaks and simplifying development.
High-Level Language:
• Focus on Functionality: Python is a high-level language, meaning it abstracts away low-
level details of computer hardware and memory management. This allows programmers to
focus on the logic and functionality of their code rather than system specifics.

Uses of Python
Python's versatility makes it a popular choice across a wide range of applications. Here are some
of the prominent uses of Python:
Web Development:
• Backend Development: Python excels in server-side scripting for web applications.
Frameworks like Django and Flask streamline the development process, allowing you to
build complex web applications efficiently.
• Full-Stack Development: While primarily known for backend development, Python can
be used for full-stack development when combined with frontend frameworks.
Data Science and Machine Learning:
• Data Analysis and Visualization: Python libraries like NumPy, Pandas, and Matplotlib
empower you to analyze, manipulate, and visualize data effectively.
• Machine Learning Algorithms: Scikit-learn, a popular Python library, provides a
comprehensive set of tools and algorithms for building machine learning models.
TensorFlow and PyTorch are other powerful frameworks used for deep learning
applications.
Automation and Scripting:
• Automating Tasks: Python's ability to interact with the operating system and other
applications makes it perfect for automating repetitive tasks, saving time and effort.
Scientific Computing:

Page 22 of 63
• Numerical Computations: Libraries like SciPy and SymPy offer functionalities for
scientific and mathematical computing, making Python a valuable tool for scientists,
engineers, and researchers.
Desktop Applications:
• GUI Development: Frameworks like Tkinter and PyQt allow you to create graphical user
interfaces (GUIs) for desktop applications.
Game Development:
• 2D Game Development: Libraries like Pygame provide a foundation for building 2D
games. Python can also be used for scripting within game engines.
Artificial Intelligence (AI):
• AI Development: Python's readability and extensive libraries like TensorFlow and
PyTorch make it a popular language for prototyping and developing AI applications.
Education:
• Beginner-Friendly Language: Python's clear syntax and gentle learning curve make it an
excellent choice for introducing programming concepts to students.
Other Use Cases:
• Web Scraping: Python can be used to extract data from websites.
• Network Programming: Libraries like sockets allow for network programming tasks.
• System Administration: Python scripts can be used for system administration tasks.
In essence, Python's versatility and rich ecosystem of libraries and frameworks make it a powerful
tool across various domains. From web development and data science to automation and scientific
computing, Python empowers you to tackle a wide range of programming challenges.

Python Program Structure


A well-structured Python program adheres to specific conventions that enhance readability,
maintainability, and overall code quality. Here's a breakdown of the typical structure of a Python
program:
1. Comments (Optional):
• Explanation and Documentation: Comments are lines of text ignored by the Python
interpreter but provide explanations for human readers.
• Types: You can use two main commenting styles:

Page 23 of 63
o Single-line comments: Start with a hash symbol (#).
o Multi-line comments: Use triple quotation marks (''' or """). These comments can
span multiple lines.
Python
# This is a single-line comment

"""
This is a multi-line comment
that can span multiple lines.
"""

2. Import Statements (Optional):


• Using External Modules: If your program needs functionalities from external modules or
libraries, you'll use import statements at the beginning of your code. These statements make
the functionalities from those modules available in your program.
Python
import math # Import the math module

3. Function Definitions (Optional):


• Reusable Code Blocks: Functions are named blocks of code that perform specific tasks.
You can define functions to modularize your code and improve reusability.
Python
def greet(name):
"""Prints a greeting message."""
print("Hello,", name)

4. Main Block:
• Program Execution Starting Point: The indentation block (usually starting after import
statements and function definitions) is where the core logic of your program resides. This
is often referred to as the main block, although Python doesn't have an explicit main
function definition like some other languages.

Page 24 of 63
Python
# Call the greet function
greet("Alice")

# Additional program logic here

Key Points:
• Indentation: Python relies on indentation to define code blocks. Consistent indentation
(usually 4 spaces) is crucial for proper program structure and execution.
• Whitespace: Whitespace (spaces, tabs, newlines) is essential for readability, but extra
whitespace generally doesn't affect program execution.
• Docstrings (Optional): Docstrings are multi-line strings (using triple quotes) placed at the
beginning of functions, classes, or modules to provide documentation about their purpose,
usage, and parameters.
Example Structure:
Python
# Single-line comment explaining the program's purpose
def calculate_area(length, width):
"""Calculates the area of a rectangle."""
area = length * width
return area

# Main block
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))

area = calculate_area(length, width)


print("The area of the rectangle is:", area)

Page 25 of 63
Variables: Variables are containers for storing data values.
Creating Variables: Python has no command for declaring a variable. A variable is created the
moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after
they have been set.

Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting

If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type

You can get the data type of a variable with the type() function.

Example
x=5
y = "John"
print(type(x))
print(type(y))

Output:
<class 'int'>
<class 'str'>
Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Page 26 of 63
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive

Variable names are case-sensitive.

Example

This will create two variables:

a=4
A = "Sally"
#A will not overwrite a

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:

• A variable name must start with a letter or the underscore character.


• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.

Example
Legal variable names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Example
Illegal variable names:

2myvar = "John"
my-var = "John"
my var = "John"
Page 27 of 63
Multi Words Variable Names
Variable names with more than one word can be difficult to read. There are several techniques
you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:

myVariableName = "John"
Pascal Case
Each word starts with a capital letter:

MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:

my_variable_name = "John"

Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Note: Make sure the number of variables matches the number of values, or else you will get an
error.

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Page 28 of 63
Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.

Example

Unpack a list:

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


x, y, z = fruits
print(x)
print(y)
print(z)

Output Variables

The Python print() function is often used to output variables.

Example
x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:

Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:

Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".

For numbers, the + character works as a mathematical operator:

Page 29 of 63
Example
x=5
y = 10
print(x + y)

In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:

Example
x=5
y = "John"
print(x + y)

The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:

Example
x=5
y = "John"
print(x, y)

Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as
global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function. The global variable with the same name will remain as it was,
global and with the original value.

Page 30 of 63
Example

Create a variable inside a function, with the same name as the global variable

x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

Built-in Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

Example

Print the data type of the variable x:

x=5
print(type(x))

Page 31 of 63
Python Numbers

There are three numeric types in Python:

• int
• float
• complex

Variables of numeric types are created when you assign a value to them:

Example
x = 1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use the type() function:

Example
print(type(x))
print(type(y))
print(type(z))

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example

Integers:

x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
Float

Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Page 32 of 63
Example

Floats:

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

Example

Floats:

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Complex

Complex numbers are written with a "j" as the imaginary part:

Example

Complex:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))
Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

Page 33 of 63
Example

Convert from one type to another:

x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Note: You cannot convert complex numbers into another number type.

Random Number

Python does not have a random() function to make a random number, but Python has a built-in
module called random that can be used to make random numbers:

Example

Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

Python Casting
Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types.
Page 34 of 63
Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

Example

Integers:

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example

Floats:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Example

Strings:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

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)
Or three single quotes:

Page 35 of 63
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.

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

Get the character at position 1 (remember that the first character has the position 0):

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

Page 36 of 63
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)

Use it in an if statement:

Example

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

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)

Use it in an if statement:

Example

print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

Page 37 of 63
Python - Slicing Strings
Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.

Slice From the Start

By leaving out the start index, the range will start at the first character:

Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])
Slice To the End

By leaving out the end index, the range will go to the end:

Example

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])

Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example

Get the characters:

From: "o" in "World!" (position -5)

Page 38 of 63
To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Python - Modify Strings

Python has a set of built-in methods that you can use on strings.

Upper Case
Example

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())
Lower Case
Example

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
Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
Split String

Page 39 of 63
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 Concatenation


String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)
Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)
Python - Format - Strings

String Format

As we learned in the Python Variables chapter, we CANNOT combine strings and numbers like
this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using f-strings or the format() method!

Page 40 of 63
F-Strings

F-String was introduced in Python 3.6 and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal and add curly
brackets {} as placeholders for variables and other operations.

Example

Create an f-string:

age = 36
txt = f"My name is John, I am {age}"
print(txt)
Placeholders and Modifiers

A placeholder can contain variables, operations, functions, and modifiers to format the value.

Example

Add a placeholder for the price variable:

price = 59
txt = f"The price is {price} dollars"
print(txt)

A placeholder can include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type, like .2f which
means fixed point number with 2 decimals:

Example

Display the price with 2 decimals:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

A placeholder can contain Python code, like math operations:

Example

Perform a math operation in the placeholder, and return the result:

txt = f"The price is {20 * 59} dollars"


print(txt)
Page 41 of 63
Python - Escape Characters
Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double
quotes:

Example

You will get an error if you use double quotes inside a string that is surrounded by double
quotes:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."


Escape Characters

Other escape characters used in Python:

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value

Python - String Methods

String Methods

Python has a set of built-in methods that you can use on strings.

Page 42 of 63
Note: All string methods return new values. They do not change the original string.

Method Description
capitalize() Converts the first character to upper case
casefold()Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was
found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was
found
rindex() Searches the string for a specified value and returns the last position of where it was
found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value

Page 43 of 63
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

Python Booleans
Booleans represent one of two values: True or False.
Boolean Values

In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated, and Python returns the Boolean
answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False:

Example

Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return,

Example

Evaluate a string and a number:

Page 44 of 63
print(bool("Hello"))
print(bool(15))

Example

Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))
print(bool(y))

Most Values are True


Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

Example

The following will return True:

bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "",
the number 0, and the value None. And of course, the value False evaluates to False.

Example

The following will return False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Page 45 of 63
One more value, or object in this case, evaluates to False, and that is if you have an object that is
made from a class with a __len__ function that returns 0 or False:

Example
class myclass():
def __len__(self):
return 0

myobj = myclass()
print(bool(myobj))
Functions can Return a Boolean

You can create functions that returns a Boolean Value:

Example

Print the answer of a function:

def myFunction() :
return True

print(myFunction())

You can execute code based on the Boolean answer of a function:

Example

Print "YES!" if the function returns True, otherwise print "NO!":

def myFunction() :
return True

if myFunction():
print("YES!")
else:
print("NO!")

Python also has many built-in functions that return a boolean value, like the isinstance() function,
which can be used to determine if an object is of a certain data type:

Example

Check if an object is an integer or not:

x = 200
print(isinstance(x, int))

Page 46 of 63
Python Operators

Operators are used to perform operations on variables and values. In the example below, we use
the + operator to add together two values:

Example
print(10 + 5)

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3

Page 47 of 63
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3 print(x)

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or x >= y


equal to

<= Less than or equal x <= y


to

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements is x < 5 or x < 4


true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

Page 48 of 63
Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same x is y


object

is not Returns True if both variables are not the same x is not y
object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is x not in y


not present in the object

Python Bitwise Operators. Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from the right x << 2
shift and let the leftmost bits fall off

>> Signed right Shift right by pushing copies of the leftmost x >> 2
shift bit in from the left, and let the rightmost bits
fall off

Page 49 of 63
Operator Precedence

Operator precedence describes the order in which operations are performed.

Example

Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((6 + 3) - (6 + 3))
Example

Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:

print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence at the
top:

Operator Description

() Parentheses

** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and


modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is not in not in Comparisons, identity, and membership
operators

not Logical NOT

and AND

Page 50 of 63
or OR

If two operators have the same precedence, the expression is evaluated from left to right.

Example

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression
from left to right:

print(5 + 4 - 7 + 3)

Python Lists
mylist = ["apple", "banana", "cherry"]
List

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:

Example

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.

Note: There are some list methods that will change the order, but in general: the order of the
items will not change.

Page 51 of 63
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)
List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

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


print(len(thislist))
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]

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

Page 52 of 63
type()

From Python's perspective, lists are defined as objects with the data type 'list':

<class 'list'>
Example

What is the data type of a list?

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


print(type(mylist))
The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


print(thislist)
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.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.

Python If ... Else

Page 53 of 63
Python Conditions and If statements

Python supports the usual logical conditions from


mathematics:

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

These conditions can be used in several ways, most


commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so
we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
Other programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Page 54 of 63
Elif

The elif keyword is Python's way of saying "if the


previous conditions were not true, then try this
condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we
print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Page 55 of 63
Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Example

One line if statement:

if a > b: print("a is greater than b")


Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the
same line:

Example

One line if else statement:

a=2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example

One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And

The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:

Page 56 of 63
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not

The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:

Example

Test if a is NOT greater than b:

a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

Nested If

You can have if statements inside if statements, this is called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Page 57 of 63
The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put
in the pass statement to avoid getting an error.

Example
a = 33
b = 200

if b > a:
pass

Python While Loops


Python Loops

Python has two primitive loop commands:

• while loops
• for loops

The while Loop

With the while loop we can execute a set of


statements as long as a condition is true.

Example

Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop


will continue forever.

The while loop requires relevant variables to be


ready, in this example we need to define an indexing variable, i, which we set to 1.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Page 58 of 63
Example

Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example

Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).

Page 59 of 63
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list:

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


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":
print(x)
The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when x is "banana":

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


for x in fruits:
print(x)
if x == "banana":
break

Example

Exit the loop when x is "banana", but this time the break comes before the print:

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


for x in fruits:
if x == "banana":

Page 60 of 63
break
print(x)
The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the
next:

Example

Do not print banana:

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


for x in fruits:
if x == "banana":
continue
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

Example

Using the start parameter:

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):

Page 61 of 63
Example

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)
Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Example

Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by a break statement.

Example

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


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

for x in adj:
for y in fruits:
print(x, y)

Page 62 of 63
The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass
Exercise:

Loop through the items in the fruits list.

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


? x ? fruits?
print(x)

Page 63 of 63

You might also like