CSC301 Lecture Note-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

CSC301 LECTURE NOTE:

Structured Programming
2023/2024 Academic Session

Page 1 of 35
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 35
• 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 35
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 35
• 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 35
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 35
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 35
• 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 35
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 35
• 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 35
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 35
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 35
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 35
• 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 35
• 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 35
• 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 35
• 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 35
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 35
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 35
• 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 35
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 35
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 35
• 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 35
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 35
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 35
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 35
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 35
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 35
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 35
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 35
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 35
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 35
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 35
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 35
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'

Page 35 of 35

You might also like