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

Cprog 1 1

Uploaded by

alejandroabe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views60 pages

Cprog 1 1

Uploaded by

alejandroabe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Computer Programming 1

An Introduction to Computer
Programming and Python
What is Computer Program?
• a collection of instructions that can be
executed by a computer to perform a specific
task or set of tasks.
What is Computer Programming?
• the process of designing and creating
programs
• written in a programming language
– is a formal language that specifies a sequence of
operations for the computer to follow
– Examples: Python, Java, C++, etc.
Why Learn Programming?
• - Growing demand for programmers in various
industries
• - Programming skills for problem-solving and
logical thinking
• - Role of programming in innovation and
technological advancements
• - Gateway to careers in IT, data science, AI, etc.
Programming Concepts & Principles
1. Syntax
The set of rules that defines the structure of a
program.
Syntax specifies how symbols, keywords, and
operators should be arranged to form valid program
statements.
• Example: In Python, the syntax for a conditional
statement is:
• if condition:
# do something
Programming Concepts & Principles

2. Semantics
The meaning of the constructs in a
programming language. Semantics determine
what happens when a valid statement or
expression is executed.
The semantics of the if statement
determine that the block of code will execute
only if the condition is true.
Programming Concepts & Principles
3. Execution Model
Interpreted vs. Compiled:
• Interpreted Languages: Code is executed line-by-line
by an interpreter (e.g., Python, JavaScript).
• Compiled Languages: Code is translated into
machine code by a compiler before execution (e.g., C,
C++).
Just-In-Time (JIT) Compilation: A hybrid
approach where code is compiled at runtime (e.g.,
Java, C#).
3. Execution Model

3.1 Compilation: The overall process of


translating a high-level programming language
(such as C, C++, or Java) into machine code
that can be executed by a computer's CPU.
This involves several intermediate steps and
transformations.
3.1 Compilation
3.1 Compilation

1.High-Level Program:
Format: Source code written in a high-level language (e.g., C, C++, Java).
3. Compilation

2. Compiler
Role: Translates high-level source code into an intermediate representation (IR). This step involves syntax
and semantic analysis.
Output: Intermediate Representation (IR).
A lower-level, platform-independent code used for optimization and transformation.
3. Compilation

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.
Output: Optimized Intermediate Representation (IR).
An optimized version of IR that's closer to machine code.
3. Compilation

5. Code Generation
Role: Converts the lower-level IR into assembly code, which is specific to a given CPU architecture.
Output: Assembly Code.
Human-readable low-level instructions for the CPU.
3.1 Compilation

6. Code Generation
Role: Converts the lower-level IR into assembly code, which is specific to a given CPU architecture.
Output: Assembly Code.
Human-readable low-level instructions for the CPU.
3.1 Compilation

5. Assembler
Role: Translates assembly code into machine code (binary code).
Output: Machine Code.
Binary code that the CPU can execute directly.
3.1 Compilation

6. Executable File
Format: The final output that contains machine code and can be executed by the operating system.
Example: A file with a .exe extension on Windows or an ELF file on Linux.
3.2 Interpretation

Interpretation refers to the process of executing a high-level


program directly, line by line or statement by statement,
without first translating it into machine code. Instead of
converting the entire program into machine code before
execution, an interpreter processes the source code on the
fly.
3.2 Interpretation

1. Source Code
Format: High-level source code (e.g., Python, JavaScript).
3.2 Interpretation

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.
3.2 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
Key Characteristics of Interpretation
Real-Time Execution: The program is executed line by line or statement by statement.
No Intermediate Machine Code: Unlike compilation, interpretation does not generate machine code. Instead, it directly interprets and
executes the source code.
Flexibility: Interpreters can offer interactive environments, such as REPLs (Read-Eval-Print Loops), where users can run code snippets
interactively.
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 an Interpreter
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.

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.
Programming Concepts & Principles

Variables
A variable in programming is a symbolic name associated with a storage
location in memory, which holds data that can be modified during program
execution. Variables act as containers for storing data values, and they allow
programmers to manipulate and use data throughout a program.
Ex.
age
name
Reserved words (also known as keywords) are specific words in a programming
language that have a predefined meaning and cannot be used as identifiers (such as
variable names, function names, or any other user-defined names). These words are
reserved by the language itself because they are used to perform specific functions,
define structures, or control the flow of a program.
Programming Concepts & Principles

Identifiers
Names used to identify variables, functions, classes, etc., such as myVariable,
calculateSum.
Programming Concepts & Principles

Data Type
A data type in programming is a classification that specifies the type of data that a variable can hold
and the operations that can be performed on that data. Data types are fundamental to
understanding how a programming language handles data and are crucial for defining variables and
function return types.
In summary, data types are essential building blocks in programming, providing structure,
constraints, and clarity to how data is handled within a program.

Ex.

int
String
Boolean
Programming Concepts & Principles

Constant
A constant in programming is a value that cannot be altered during the execution of a program. Once a
constant is defined and assigned a value, that value remains fixed throughout the lifetime of the program.
Constants are useful when you need to ensure that specific values remain unchanged, such as
mathematical constants, fixed configuration values, or any other data that should not be modified.
Programming Concepts & Principles
4. Type System
Static vs. Dynamic Typing:
• Static Typing: The type of a variable is determined at
compile time (e.g., C, Java).
• Dynamic Typing: The type of a variable is determined at
runtime (e.g., Python, JavaScript).
• Strong vs. Weak Typing:
• Strong Typing: Types are strictly enforced, and implicit
conversions are limited (e.g., Python, Java).
• Weak Typing: The language performs implicit type
conversions more freely (e.g., JavaScript, PHP).
Programming Concepts & Principles
5. Paradigms
The style or approach to programming supported by
the language.
Common Paradigms:
• Procedural Programming: Focuses on procedures or routines
(e.g., C, Pascal).
• Object-Oriented Programming (OOP): Focuses on objects and
classes (e.g., Java, Python).
• Functional Programming: Treats computation as the evaluation
of mathematical functions (e.g., Haskell, Lisp).
• Event-Driven Programming: Focuses on responding to events
or user actions (e.g., JavaScript).
Programming Concepts & Principles

6. Abstraction
The ability to define complex structures or
operations in a simplified manner.
Examples:
• Functions: Abstract a sequence of instructions
into a callable unit.
• Classes and Objects: Abstract real-world entities
into objects with properties and behaviors.
Programming Concepts & Principles

7. 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 & Principles

8. 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 & Principles

9. 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 & Principles

10. 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 & Principles

11. Error Handling


Mechanisms to handle runtime errors and
exceptions.
Example: Python uses try, except, and
finally blocks to manage exceptions.

Runtime vs Compile time


Programming Concepts & Principles

12. 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 & Principles

13. Libraries and Frameworks


Collections of pre-written code that
provide tools and functions for various tasks,
reducing the need to write code from
scratch.
Example: Python has extensive libraries for
data science, web development, and more (e.g.,
NumPy, Django).
Programming Concepts & Principles

14. 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 & Principles

15. 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.
Programming Concepts & Principles

• Variables are used to store data that can be manipulated by


the program.
• 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.
Programming Concepts & Principles

Operators
• Arithmetic
• Relational
• Logical
• Assignment
• Others(visit documentation)
Programming Concepts & Principles

Operators
• Arithmetic
– EMDAS
– Modulus – returns remainder
– Div – drops remainder
Programming Concepts & Principles
Operators

Relational/Comparison
• Equal to (==): Checks if the values of two operands are equal.
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
Programming Concepts & Principles

Operators
Logical
• Logical AND (and): Returns True if both operands are true.
Example:
a and b
• Logical OR (or): Returns True if at least one of the operands is
true.
Example:
a or b
• Logical NOT (not): Reverses the logical state of its operand.
Example:
not a
Programming Concepts & Principles
Operators
Assignment
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
Divide and Assign (/=):
Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.Example: a /= b
Floor Divide and Assign (//=):
Performs floor division on the operands and assigns the result to the left-hand operand.Example: a //= b
Modulus and Assign (%=):
Takes modulus using two operands and assigns the result to the left-hand operand.Example: a %= b
Exponent and Assign (**=):
Performs exponential (power) calculation on the operands and assigns the result to the left-hand operand.Example: a **= b
Bitwise AND and Assign (&=):
Performs bitwise AND on the operands and assigns the result to the left-hand operand.Example: a &= b
Bitwise OR and Assign (|=):
Performs bitwise OR on the operands and assigns the result to the left-hand operand.Example: a |= b
Bitwise XOR and Assign (^=):
Performs bitwise XOR on the operands and assigns the result to the left-hand operand.Example: a ^= b
Bitwise Left Shift and Assign (<<=):
Performs bitwise left shift on the operands and assigns the result to the left-hand operand.Example: a <<= b
Bitwise Right Shift and Assign (>>=):
Programming Concepts & Principles

Operators
• Others(per language; visit documentation)
Programming Concepts & Principles

Control Structures
Types of Control Structures
1.Sequential Control
2.Selection/Decision Control (Conditional
Statements)
3.Repetition/Looping Control
4.Jump/Branching Control
Programming Concepts & Principles
Data Structures
A data structure is a specialized format for organizing, managing, and
storing data in a computer so that it can be accessed and modified
efficiently. Data structures provide a way to arrange data in a form that is
suitable for specific types of operations or algorithms, allowing for efficient
data manipulation, retrieval, and storage.

* variables can hold 1 value while data structures can hold multiples values

*While a variable typically holds a single value, it can also hold references
to data structures (like arrays, lists, or objects) that contain multiple values.
Programming Concepts & Principles

Function
A function in programming is a reusable block of code that performs a specific
task or a set of tasks. Functions are fundamental building blocks in many
programming languages, allowing you to organize code, reduce repetition,
and improve readability and maintainability. Functions can take inputs,
process those inputs, and produce an output.
A function is defined once and can be called (or invoked) multiple times throughout a program.
Programming Concepts & Principles

Class
A class in programming is a blueprint for creating objects (a particular data structure),
providing initial values for state (member variables or fields), and implementations of
behavior (member functions or methods). A class defines a new data type, which can
encapsulate data and the functions that operate on that data. Classes are a central
concept in object-oriented programming (OOP).
Programming Concepts & Principles

Algorithm

An algorithm is a well-defined, step-by-step procedure or set of rules


that describes how to perform a specific task or solve a particular
problem. In computer science and programming, algorithms are the
backbone of problem-solving and are used to process data, perform
computations, automate reasoning, and carry out other essential
tasks.
Programming Concepts & Principles

Pseudocode

Pseudocode is an informal way of writing the logic of a program or


algorithm in plain language. It is not written in a specific programming
language but rather in a simplified, structured format that resembles
code. Pseudocode is used to design algorithms before actually
implementing them in a programming language.
Programming Concepts & Principles

Comments

Comments are annotations or explanations added to the source code of a


program. They are ignored by the compiler or interpreter and do not
affect the execution of the code. Comments are used to clarify the
purpose of the code, describe the logic, and provide additional context or
notes for anyone reading the code.
What is Python?
• Brief history and evolution of Python
• Python as a versatile, high-level programming
language
• Key features: simplicity, readability, large
standard library
• Common use cases: web development, data
science, automation, etc.
Why Python?
• Easy to learn and use for beginners
• Extensive libraries and frameworks
• Strong community support
• Cross-platform compatibility
• High demand in the job market
Step-by-Step Guide to Installing Python

• Download Python from their official website


• Follow steps for installation by the installer
• Verifying the installation
– Open terminal/command prompt
– Type python
– Type print(“Hello Programming!”)
– Enter
• Lookup issues online/ask for help
Integrated Development Environments
(IDEs)
• -Install either of the ff:
– Python IDEs: VS Code, Thonny
• Create file called hello.py
• Type the ff. code in the file:
print(“hello Python IDE!”)
• Save file
• Run file (click triangle icon on the IDE)
Programming Concepts & Principles

Variable Declaration and Assignment Examples


1. Basic Variable Declaration and Assignment:
1. You declare and assign a value to a variable in one step.
# Example of integer assignment
age = 25
# Example of string assignment
name = "John Doe"
# Example of float assignment
height = 5.9
# Example of boolean assignment
is_student = True
Programming Concepts & Principles
Variable Declaration and Assignment Examples

Multiple Variable Assignment:


1. You can assign values to multiple variables simultaneously.
# Assigning values to multiple variables in one line
x, y, z = 1, 2, 3
# Assigning the same value to multiple variables
a = b = c = 100
Programming Concepts & Principles

Variable Declaration and Assignment Examples

Dynamic Typing and Reassignment:


1. Variables can be reassigned to different types of values.
# Initially assigning an integer value
var = 10
print(var)
# Output: 10
# Reassigning the variable to a string value
var = "Hello”
print(var)
# Output: Hello
# Reassigning the variable to a float value
var = 3.14
print(var)
# Output: 3.14
Programming Concepts & Principles
Variable Declaration and Assignment Examples

Type Annotations (Optional):


1. Python allows you to use type annotations to indicate the expected type of a variable, but this is not enforced by the interpreter.
# Using type annotations
name: str = "Alice"
age: int = 30
height: float = 5.5
is_student: bool = False
Uninitialized Variables:
2. Unlike some languages, Python does not require variables to be declared before assignment. If you try to use a variable before
assigning a value to it, you will get a NameError.
# This will raise a NameError
print(x)
# Error: NameError: name 'x' is not defined
# Correct usage after assignment
x = 10
print(x)
# Output: 10

• These examples illustrate how you can declare and assign values to variables in Python. The language's flexibility with types
and simple syntax make it easy to work with variables.
Continue Your Python Journey

• To continue your Python journey, here are some recommended


resources:
• - **Official Python Documentation:** The go-to resource for all things
Python. (https://docs.python.org/)
• - **Codecademy:** Interactive Python courses for beginners.
(https://www.codecademy.com/learn/learn-python-3)
• - **Automate the Boring Stuff with Python:** A book that teaches
Python through practical projects. (https://automatetheboringstuff.com/)
• - **Python.org Tutorials:** Free tutorials for Python programming.
(https://www.python.org/about/gettingstarted/)
• - **Stack Overflow:** A community where you can ask questions and
share knowledge. (https://stackoverflow.com/questions/tagged/python)

You might also like