CSC301_FinalCopy
CSC301_FinalCopy
Structured Programming
2023/2024 Academic Session
Page 1 of 69
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.
Page 2 of 69
• 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.
Page 3 of 69
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.
• 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.
Page 4 of 69
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:
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.
Page 5 of 69
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
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.
• Initial Idea: Write a program that calculates the area of a triangle.
Page 6 of 69
• 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.
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.
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:
Page 7 of 69
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.
• 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.
Page 8 of 69
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.
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.
Page 9 of 69
• 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
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.
Page 10 of 69
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
In this example:
• The user inputs the length and width, which are assigned to variables length and width.
• 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.
Page 11 of 69
• 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).
• 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:
Page 12 of 69
• 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.
• 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:
Page 13 of 69
• 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."
• 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.
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.
Page 14 of 69
• 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.
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.
Page 15 of 69
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]).
• 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.
Page 16 of 69
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.
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.
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.
Page 17 of 69
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:
• 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.
Page 18 of 69
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.
"""
This is a multi-line comment
that can span multiple lines.
"""
Page 19 of 69
"""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.
Python
# Call the greet function
greet("Alice")
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: "))
Page 20 of 69
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'>
Page 21 of 69
Single or Double Quotes?
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
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:
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
Page 22 of 69
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
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"
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.
Page 23 of 69
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)
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:
Output Variables
Example
x = "Python is awesome"
print(x)
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Page 24 of 69
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".
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.
Page 25 of 69
Global variables can be used by everyone, both inside of functions and outside.
Example
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.
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)
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:
Page 26 of 69
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
You can get the data type of any object by using the type() function:
Example
x=5
print(type(x))
Python Numbers
• 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:
Page 27 of 69
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.
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.
Page 28 of 69
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
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:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
Page 29 of 69
#convert from float to int:
b = int(y)
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.
• 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)
Page 30 of 69
• 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:
Example
Strings:
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 31 of 69
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.
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
for x in "banana":
print(x)
String Length
Example
Page 32 of 69
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Use it in an if statement:
Example
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
Use it in an if statement:
Example
Page 33 of 69
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example
b = "Hello, World!"
print(b[2:5])
By leaving out the start index, the range will start at the first character:
Example
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:])
Page 34 of 69
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
b = "Hello, World!"
print(b[-5:-2])
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
a = "Hello, World!"
print(a.upper())
Lower Case
Example
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:
Page 35 of 69
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
Example
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
The split() method returns a list where the text between the specified separator becomes the list
items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Example
a = "Hello"
b = "World"
c=a+b
print(c)
Example
a = "Hello"
b = "World"
Page 36 of 69
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!
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
price = 59
txt = f"The price is {price} dollars"
print(txt)
Page 37 of 69
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
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Example
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:
Page 38 of 69
Example
The escape character allows you to use double quotes when you normally would not be allowed:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
String Methods
Python has a set of built-in methods that you can use on strings.
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
Page 39 of 69
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
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
Page 40 of 69
Python Booleans
Booleans represent one of two values: True or False.
Boolean Values
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)
Example
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
print(bool("Hello"))
print(bool(15))
Page 41 of 69
Example
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Any list, tuple, set, and dictionary are True, except empty ones.
Example
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
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
bool(False)
bool(None)
bool(0)
bool("")
bool(())
Page 42 of 69
bool([])
bool({})
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
Example
def myFunction() :
return True
print(myFunction())
Example
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:
Page 43 of 69
Example
x = 200
print(isinstance(x, int))
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)
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Page 44 of 69
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
|= 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)
== Equal x == y
!= Not equal x != y
Page 45 of 69
and Returns True if both statements are x < 5 and x < 10
true
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
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:
is not Returns True if both variables are not the same x is not y
object
Python Bitwise Operators. Bitwise operators are used to compare (binary) numbers:
Page 46 of 69
& AND Sets each bit to 1 if both bits are 1 x&y
<< 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
Operator Precedence
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
Page 47 of 69
* / // % Multiplication, division, floor division, and
modulus
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not in Comparisons, identity, and membership
operators
and AND
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 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.
Page 48 of 69
Example
Create a List:
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.
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
To determine how many items a list has, use the len() function:
Page 49 of 69
Example
Example
Example
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
It is also possible to use the list() constructor when creating a new list.
Page 50 of 69
Example
There are four collection data types in the Python programming language:
*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.
• 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
Page 51 of 69
These conditions can be used in several ways, most commonly in "if statements" and loops.
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
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
Page 52 of 69
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".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
Page 53 of 69
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
a=2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:
Example
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
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Page 54 of 69
Or
Example
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
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 55 of 69
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 Loops
• while loops
• for loops
Example
i=1
while i < 6:
print(i)
i += 1
Page 56 of 69
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.
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and continue with the next:
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the condition no longer is true:
Example
Page 57 of 69
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).
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
The for loop does not require an indexing variable to set beforehand.
Example
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:
Page 58 of 69
Example
Example
Exit the loop when x is "banana", but this time the break comes before the print:
With the continue statement we can stop the current iteration of the loop, and continue with the
next:
Example
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.
Page 59 of 69
Example
for x in range(6):
print(x)
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
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):
Example
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.
Page 60 of 69
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
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
for x in adj:
for y in fruits:
print(x, y)
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:
Page 61 of 69
Python Functions
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
Page 62 of 69
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.
A parameter is the variable listed inside the parentheses in the function definition.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
Example
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
my_function("Emil")
Page 63 of 69
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter name:
Page 64 of 69
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return Values
Example
def my_function(x):
return 5 * x
Page 65 of 69
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement
function definitions cannot be empty, but if you for some reason have a function definition with
no content, put in the pass statement to avoid getting an error.
Example
def myfunction():
pass
Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or ONLY keyword
arguments.
To specify that a function can have only positional arguments, add , / after the arguments:
Example
def my_function(x, /):
print(x)
my_function(3)
Without the , / you are actually allowed to use keyword arguments even if the function expects
positional arguments:
Example
def my_function(x):
print(x)
my_function(x = 3)
But when adding the , / you will get an error if you try to send a keyword argument:
Example
def my_function(x, /):
print(x)
my_function(x = 3)
Page 66 of 69
Keyword-Only Arguments
To specify that a function can have only keyword arguments, add *, before the arguments:
Example
def my_function(*, x):
print(x)
my_function(x = 3)
Without the *, you are allowed to use positionale arguments even if the function expects
keyword arguments:
Example
def my_function(x):
print(x)
my_function(3)
But when adding the *, / you will get an error if you try to send a positional argument:
Example
def my_function(*, x):
print(x)
my_function(3)
You can combine the two argument types in the same function.
Any argument before the /, are positional-only, and any argument after the *, are keyword-only.
Example
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Page 67 of 69
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically elegant
approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We
use the k variable as the data, which decreases (-1) every time we recurse. The recursion ends
when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Exercise: Write a python program that takes a number as input from the user and uses three
functions to display the following outputs:
a) The number of digits in the input number.
b) The reverse of the input number.
c) Whether the input number is a palindrome or not. A palindrome is a number that is the same
when read forward or backward, such as 121 or 12321.
Page 68 of 69
Solution:
Python
Page 69 of 69