Fundamentals of Programming
Fundamentals of Programming
Programming
AN INTRODUCTION TO COMPUTER PROGRAMMING
AND PYTHON
What is Computer Program?
u Interpreted: Run
Evaluating Results
u Errors
Occur when our code attempts to do something it isn’t allowed to do.
u Incorrect results
Code run successfully, but do not do what we want/expect it to do.
WHAT ARE THE
Execution PROCESSES THAT THE
CODE UNDERGOES
model BEFORE IT CAN BE
RUN(EXECUTED)
Execution Model
1.High-Level Program:
2. Compiler
Role: Translates high-level source code into an intermediate representation (IR). This step involves
syntax and semantic analysis.
3. Optimization Passes
Role: Translates high-level source code into an intermediate representation (IR). This step involves
syntax and semantic analysis.
Role: Improve the IR by optimizing performance and reducing the code size.
5. Code Generation
Role: Converts the lower-level IR into assembly code, which is specific to a given CPU architecture.
6. Assembler
Role: Translates assembly code into machine code (binary code).
Output: Machine Code.
7. Executable File
Format: The final output that contains machine code and can be executed by
the operating system.
1. Source Code
2. Interpreter
Role: Executes the source code directly. The interpreter reads the code, parses it, and performs the
instructions in real-time.
Output: Direct execution of commands without producing intermediate machine code.
Interpretation
3. Execution
The interpreter translates each line of code into an internal representation and
then executes it immediately.
This process is repeated for each statement or line of code in the program.
3.3 Compilation & Interpretation Summary
No Intermediate Machine Code: Unlike compilation, interpretation does not generate machine code.
Slower Execution: Since the source code is processed in real-time, interpretation can be slower compared to compiled
machine code execution.
Ease of Debugging: Easier to debug due to the ability to execute code incrementally and test parts of the program
interactively.
Example of Interpreters
Python Interpreter: Executes Python code directly without needing a separate compilation step.
JavaScript Engine: In web browsers, JavaScript is interpreted to execute scripts on the client side.
3.3 Compilation & Interpretation Summary
Summary
Interpretation involves reading and executing high-level code directly, without translating it into
machine code beforehand.
Compilation translates the entire high-level program into machine code before execution, which is then
run by the CPU.
In some modern programming environments, a combination of both techniques is used. For instance,
many languages use Just-In-Time (JIT) compilation, where an interpreter compiles code to machine
code at runtime to optimize performance while maintaining some of the benefits of interpretation.
In Compiled languages the entire program/code is converted to machine code first before it can be run
while in Interpreted Languages it is run first then each line of code is interpreted(actually it is still
converted into machine code) and executed.
In JIT the interpreter scans the entire code to evaluated for hotspots or candidate for compilation and
then compiles them first before the entire program/code is run.
THE SET OF RULES THAT
DEFINES THE STRUCTURE OF A
PROGRAM.
SYNTAX SPECIFIES HOW
SYMBOLS, KEYWORDS, AND
OPERATORS SHOULD BE
ARRANGED TO FORM VALID
Syntax PROGRAM STATEMENTS.
Example:
In Python, the syntax for a
conditional statement is:
if condition:
# do something
THE MEANING OF THE
CONSTRUCTS IN A
PROGRAMMING LANGUAGE.
3. SOLID Principles
Description: A set of five principles aimed at making object-
oriented design more understandable, flexible, and maintainable.
S: Single Responsibility Principle - A class should have one reason
to change (it should have only one job).
O: Open/Closed Principle - Software entities should be open for
extension but closed for modification.
L: Liskov Substitution Principle - Subtypes must be substitutable for
their base types without altering the correctness of the program.
I: Interface Segregation Principle - Clients should not be forced to
depend on interfaces they do not use.
D: Dependency Inversion Principle - High-level modules should not
depend on low-level modules; both should depend on
abstractions.
Programming principles
4. Separation of Concerns
Description: Different concerns or aspects of a program should be
separated into distinct sections. For example, separate business
logic from user interface code.
Goal: Improve modularity, making it easier to manage and
update code.
5. Composition Over Inheritance
Description: Favor composing objects with reusable components
rather than relying heavily on inheritance hierarchies.
Goal: Increase flexibility and reduce tight coupling between
classes.
Programming principles
8. Fail Fast
Description: A system should report errors as soon as they are
detected, rather than allowing them to propagate or surface
later.
Goal: Facilitate quicker debugging and identification of issues.
9. Don't Repeat Yourself (DRY)
Description: As discussed earlier, avoid duplicating code or logic
to minimize maintenance and improve clarity.
10. Continuous Refactoring
Description: Regularly revisit and improve code, making it cleaner
and more efficient.
Goal: Maintain code quality and adapt to new requirements over
time.
Programming principles
Conclusion
These principles serve as guidelines for writing effective,
maintainable, and efficient code. While they may
sometimes conflict, understanding and applying them
judiciously can lead to better software design and
development practices
Abstraction
Examples:
• Functions: Abstract a sequence of instructions into a callable unit.
• Classes and Objects: Abstract real-world entities into objects with
properties and behaviors.
• Modules/Namespaces serve as a way to group related functions,
classes, and variables, providing a higher-level abstraction for
organizing code. They help manage complexity by encapsulating
functionality and enabling separation of concerns.
• Procedures (or methods, in some contexts) also provide an
abstraction by grouping a series of instructions into a single
callable unit. They are similar to functions but may have a more
specific role in certain programming paradigms, such as
procedural programming, where they might be tied more closely
to the control flow of the program.
THE STYLE OR APPROACH
TO PROGRAMMING
Programming SUPPORTED BY THE
LANGUAGE.(HOW CAN
paradigms CAN CODE BE GROUP ED
THAT CAN BE REFERENCED
OR CALLED)
Common Paradigms
Common Paradigms:
v Procedural Programming: Focuses on procedures or routines (e.g., C,
Pascal).
v Object-Oriented Programming (OOP): Focuses on objects and classes
(e.g., Java, Python).
v Functional Programming: Treats computation as the evaluation of
mathematical functions (e.g., Haskell, Lisp).
v Event-Driven Programming: Focuses on responding to events or user
actions (e.g., JavaScript).
Procedural Programming
3. Higher-Order Functions: These are functions that can take other functions as arguments or return
functions as results. They enable powerful abstractions and can be used to create reusable code.
4. Immutability: In functional programming, data is often immutable, meaning it cannot be changed
after it's created. Instead of modifying data structures, new versions of them are created. This leads
to fewer bugs related to state changes and makes it easier to reason about code.
5. Function Composition: This concept involves combining simple functions to build more complex ones.
Function composition allows for a more modular approach to programming.
6. Recursion: Functional programming often uses recursion as a primary means of performing repeated
operations, rather than relying on traditional loops. This is due to the emphasis on immutability and
pure functions.
Programming paradigms
Data Types define the kind of data a variable can hold, such as integers, floats,
strings, or booleans. Understanding how to declare and use variables correctly is
fundamental to programming.
In Python, variable declaration and assignment are simple and straightforward.
Python is dynamically typed, which means you don't need to declare a variable
type explicitly; the type is inferred based on the value you assign to it.
Variable types determine how much memory is required to store the variable’s
value, and memory allocation occurs based on these types when the variable is
declared or initialized
In statically typed languages (like C, C++, and Java), memory is typically
allocated at the time of declaration because the type is known at compile time.
In dynamically typed or interpreted languages (like Python and JavaScript),
memory is allocated when the variable is assigned a value, as the type is inferred
at runtime
Variable
The main purpose of initialization is to ensure that the variable starts with
a known value, allowing it to be used effectively in computations and
operations from the moment it is defined.
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Relational/Comparison Operators
Example: a == b
• Not equal to (!=): Checks if the values of two operands are not equal.
Example: a != b
• Greater than (>): Checks if the value of the left operand is greater than the right operand.
Example: a > b
• Less than (<): Checks if the value of the left operand is less than the right operand.
Example: a < b
• Greater than or equal to (>=): Checks if the value of the left operand is greater than or equal to the right
operand
.Example: a >= b
• Less than or equal to (<=): Checks if the value of the left operand is less than or equal to the right operand.
Example: a <= b
Logical Operators
Assignment (=):
Assigns the right-hand operand to the left-hand operand.
Example: a = b
Add and Assign (+=):
Adds the right-hand operand to the left-hand operand and assigns
the result to the left-hand operand.
Example: a += b
Subtract and Assign (-=):
Subtracts the right-hand operand from the left-hand operand and
assigns the result to the left-hand operand.Example: a -= b
Multiply and Assign (*=):
Multiplies the right-hand operand with the left-hand operand and
assigns the result to the left-hand operand.Example: a *= b
Assignment Operators
Operators
u Others(per language; visit documentation)
Control
structures/
Flow Control
Types of Control Structures
1. Sequential Control
2. Selection/Decision Control (Conditional Statements)
3. Repetition/Looping Control
4. Jump/Branching Control
Algorithms
1. Quick Sort: Divides the array into smaller sub-arrays and sorts them.
2. Merge Sort: Divides the array into halves, sorts them, and merges the sorted halves.
Types of Algorithms
Using an IDE can make your programming journey smoother and more
enjoyable.
It combines everything you need into one tool, helping you learn and
code more effectively!
Advantages of Using an IDE
1. Easier Coding: IDEs help you write code faster by suggesting what you
might want to type next. This feature is called code completion (a feature
that predicts and suggests code as you type).
2. Debugging Made Simple: If your code has mistakes (called bugs), IDEs
have tools that let you stop the program at certain points (called
breakpoints) so you can see what’s going wrong and fix it. Debugging
(the process of finding and fixing errors in your code) is easier with these
tools.
3. Organized Projects: IDEs help you keep your files organized. Instead of
searching through folders, everything is in one place, making it easier to
manage your projects.
4. Version Control: IDEs often have built-in tools that connect with version
control systems (software that helps manage changes to your code over
time, like Git). This helps you keep track of changes, collaborate with
others, and revert to earlier versions if needed.
Advantages of Using an IDE
5. Automated Builds: When you’re ready to run your code, IDEs can
compile it (convert your code into a program) and check for errors
automatically, saving you time and effort. Build automation (the
process of automatically creating a software build) is a big help.
6. User-Friendly Interface: IDEs have a graphical interface (visual layout
that allows you to interact with the software using buttons and
menus) that is easier to navigate compared to writing everything in a
basic text editor. You can click buttons instead of remembering
complex commands.
7. Customization with Plugins: Many IDEs allow you to add extra features
(called plugins or extensions) to tailor the environment to your needs.
This makes your coding experience more efficient.
Advantages of Using an IDE
Portability
The ability of the code to run on different platforms without
modification.
Example: Python is known for its high portability, as Python
programs can run on various operating systems with little or no
change.
Programming Concepts
Performance
How efficiently a language can execute instructions. This includes
factors like speed, memory usage, and the efficiency of compiled
code.
Example: C is known for its high performance, making it suitable for
system-level programming.
Programming Concepts
Memory Management
Automatic vs. Manual Memory Management:
Automatic Memory Management: The language handles
memory allocation and deallocation (e.g., Java, Python).
Manual Memory Management: The programmer is responsible for
managing memory (e.g., C, C++).
Programming Concepts
Concurrency Support
The ability to handle multiple tasks at once, either through multi-
threading or multi-processing.
Example: Java provides built-in support for multi-threading,
while Python offers the threading and multiprocessing modules.
Programming Concepts
Error Handling
Mechanisms to handle runtime errors and exceptions.
Example: Python uses try, except, and finally blocks to
manage exceptions.
Extensibility
The ability to extend the language with new
features, libraries, or tools.
Example: Python can be extended with C or C++
modules for performance-critical tasks.
Programming Concepts
Community Support
The presence of an active community that
contributes to the language's development, provides
resources, and offers help to developers.
Example: Python has a large, active community
with extensive documentation and third-party
libraries.
Programming Concepts
Ease of Learning
How easy it is for beginners to learn and start
programming in the language.
Example: Python is often praised for its simplicity
and readability, making it a popular choice for
beginners.
INTRODUCING PYTHON
Python PROGRAMMING
LANGUAGE
What is Python?