0% found this document useful (0 votes)
31 views85 pages

Unit 1

This document serves as an introduction to basic computer programming, covering essential concepts such as computer hardware and software, programming languages, and data types. It explains the role of algorithms in solving computational problems and provides examples of programming syntax, variables, and operators. Additionally, it highlights Python as a versatile programming language suitable for various applications, including web development and scientific computing.

Uploaded by

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

Unit 1

This document serves as an introduction to basic computer programming, covering essential concepts such as computer hardware and software, programming languages, and data types. It explains the role of algorithms in solving computational problems and provides examples of programming syntax, variables, and operators. Additionally, it highlights Python as a versatile programming language suitable for various applications, including web development and scientific computing.

Uploaded by

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

Unit 1

Introduction to basic Computer Program


Agenda

● Computer Basics
● Basic Computer Programs
What is a computer?
The term “computer” could literally be used to identify any device that
calculates. Initially, the computer was designed as a tool to manipulate numbers
& solves arithmetic problems, this original use is understandable, since most of
the early designers and users were mathematician, scientists & engineers.

“A computer is an electronic device that processes data,


converting it into information that is useful to people.” (Norton,
2013)
What is a computer?
The term “computer” could literally be used to identify any device that
calculates. Initially, the computer was designed as a tool to manipulate
numbers & solves arithmetic problems; this original use is
understandable, since most of the early designers and users were
mathematician, scientists & engineers.

“A computer is an electronic device that processes data,


converting it into information that is useful to people.”
(Norton, 2013)
Hardware

Hardware is any computer device that are connected to it and we can see
and touch physically. The computer hardware provide the necessary
resources for executing software instructions and interacting with users
and other devices.
PSU: Power Supply Unit
It receives the power from the wall plug and
distributes it to the various components.

CPU: The Central Processing Unit is the


component that will perform your instructions
and computations.

RAM: For the CPU to work, it needs to store


the data that it is working with somewhere. It
is stored in the RAM (Random Access
Memory)
Input Devices: These are devices that provide
input from the user to the computer

Mouse, Keyboard

Output devices: These are the devices that the


computer shows the output to interact with the
user.

Speakers - Output in the form of audio.


Monitor - Output in the form of pictures.

Storage (SSD, HDD) - output in the form of a


saved/stored file
Software
Software is a Programs which tell the computer what to do.

Software has to work with hardware. Software is the part of computer that we
can see and use but we cannot touch it directly. If we want to use it, we must
make sure that the software has been installed inside the computer.
Operating System: An Operating System is a master control program, which act
as interface between user and the computer. It manages the computer's resources
and provides a platform for running applications. Example: Windows (2000, 95,
98, XP, Vista), Windows 7, Windows 10, and Unix, Linux, Mac OS.
Application:
These are the programs that users interact with to perform specific tasks like watching
movies, playing games, browsing the internet, editing documents, etc. An application (app)
is basically a program or a product that we design for end-user requirements only.
Eg. Library management, Payroll
system, production and planning,
inventory management,
Ms Office, etc…
Connectivity: Computers can also communicate with other computers
and devices over networks, such as the internet.
Question

What is the smallest unit of Storage?


Storage Unit
Bit (binary digit) is the smallest unit of data that a computer can process and
store.
Binary Digit
A bit is always in one of two physical states, similar to an on/off light switch.

In the computer world, everything is represented using binary digits (bits): 0


and 1.

So how can we humans that work with numbers, texts and images
communicate / work with computers that can understand just 0s and 1s?
Binary to Human readable format (decimal)
For humans we have 10 symbols: 0,1,2,3,4,5,6,7,8,9

It is called decimal number system

After symbols have been exhausted, we start again with an extra digit: 10, 11, 12, 13,
14, 15, 16, 17 ... 99

When the extra two digits are exhausted, we again add another digit: 100, 101, 102, ...
999

Similarly, with computers, when you exhaust a digit you add another one just like we do
but it is with 0 and 1
Binary to Human Readable Format
Example:
We can say
0 in a computer is 0 for a human
1 in a computer is 1 for a human.
-0][
[p
10 in a computer is 2 for a human
11 in a computer is 3 for a human
How?
Conversion Decimal to Binary
-0][
[p
Conversion from Binary to Decimal
The given binary number is (10011) .
2
= (1 × 20) + (1 × 21) + (0 × 22) + (0 × 23) + (1 × 24)
=(1 × 1) + (1 × 2) + (0 × 4) + (0 × 8) + (1 × 16)

= 1 + 2 + 0 + 0 + 16 = (19)
10

Note: A0 = 1
Binary Addition
Binary addition is similar to decimal number(base 10) addition except
Binary takes base two and follows given four rules.

Rules:
● 0+0=0
● 0+1=1
● 1+0=1
● 1 + 1 = 10
Binary Addition: Example
Given Rule Add previous Record
Step Carry
Binary applied carry(if any) answer

10001
1. 1&1 1 + 1 = 10 - 1 0
(+) 1 1 1 0 1 2. 0 + 1(use rule
0&0 0+0=0 - 1
0 +1 = 1)
———————–
3. 0 &1 0+1=1 - - 1
101110
4. 0 &1 0+1=1 - - 1

5. 1&1 1 + 1 = 10 - - 10
Representation of text in Computer
ASCII - American Standard Code for Information Interchange
Its a character encoding standard that represents text in computers and
other devices that use text.
ASCII uses set of 128 characters.
Each character represented by a unique 7-bit binary number.
Example:
A is 65 a is 97
B is 66 b is 98
. .
. .
Z is 90 z is 122
Example:
So When you are typing Hello, write down how it will be represented in Binary.

Text -> ASCII -> Binary (Computer World)

Hello ->

72 101 108 108 111 ->

01001000 01100101 01101100 01101100 01101111


Computer Programs
Computer Programs
Despite all the wonderful and amazing things that computers can do, computers
are not very smart.

Computers can only follow the instructions given by human.

“A computer program is a sequence of step-by-step instructions given to


computers to manipulate data in order to perform a certain task.”

Example: Calculator App, it’s a program. It will take your number and symbols and
will display the output on your screen.
Programming

Programming is the process of creating a set of instructions that tell a


computer how to perform a task.
Programming Language
You write a program using a programming language.

Example of Programming Language: Python, C, Java, Kotlin, Javascript, PHP

The different programming languages were created to solve different needs but at
the end of the day, you are writing instructions for the computer that will at the end
be run in the CPU.
Python
Python programming language is built to be make easier to use and read

For example, lets see the simple code written in C

Code in Python
Python Versions
Python 3 (recent version, python 3.12.4) Python installation

Python 2 Click link below to view how to install python


in Windows OS

https://www.youtube.com/watch?v=yivyNCtVVD
k
Why Python?
● Compatible with different platforms (Windows, MAC, Linux Unix etc…)
● It has a simple syntax (similar to English language with influence from
mathematics)
● It runs on an interpreter system, code can be executed as soon as it is
written.
● It can be treated in a procedural way, an object-oriented way or a
functional way.
Application of Python
● used for scripting and automation tasks within operating systems
○ Examples: automate backups, manage user accounts, or monitor system
performance.
● Used for web development. Python-based web frameworks like Django, Pyramid, and
Flask are used to handle backend or server-side functionality of sites and services like
Spotify, Reddit, and Mozilla.
○ Example: Google and YouTube depend largely on Python for critical infrastructure.
● Used for game development. Libraries like Pygame provide a framework for building 2D
games, while engines like Panda3D and Godot support the development of both 2D and
3D games.
○ Example: sims 4, World of Tanks, Disney’s Toontown Online,etc….
● Used for scientific and Numeric computing. Libraries like NumPy, SciPy, and Pandas
provide powerful tools for numerical computing, data manipulation, and statistical analysis.
○ Example: scientific research, engineering simulations, and data visualization tasks.
Computational problems and Algorithms
Computational Problems and Algorithms
A computational problem is a problem that can be solved step-by-step with
computer.

These problems usually have a well-defined input, constraints, and conditions that
the output must satisfy. Some of the computational problems are:

1. A decision problem
2. A search problem
3. Optimization problem
Example of non-computational problems:
Question such as

1. “what is the meaning of life?”


2. “Do I look good in this outfit?”
Finding the maximum value
Find the integer with the maximum value from the list.
4 1 -4 0 9 9 3 5 8

The output should be 9.

(OR)

To add two given numbers 10 and 20.

The Output should be 10 + 20 = 30

Now, you should pause reading and think about how you would solve this step-by-step.
WHAT IS AN ALGORITHM

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


used to solve a specific problem or perform a particular task.
AN ALGORITHM FOR ADDING TWO NUMBERS

Algorithm PSEUDOCODE

BEGIN AddNumbers
step 1 − START a = 10
step 2 − declare three integers boys, b & b = 20
sum SET sum = 0
step 3 − define values of a & b
step 4 − add values of a & b sum = a + b
step 5 − store output of step 4 to sum
step 6 − print sum PRINT sum
END AddNumbers
step 7 − STOP
FLOWCHART
Flowchart to add two numbers
Program Structure
Syntax
Syntax refers to the rules that define the structure of a language. Syntax in computer
programming means the rules that control the structure of the symbols, punctuation, and
words of a programming language.

Without syntax, the meaning or semantics of a language is nearly impossible to


understand.

If the syntax of a language is not followed, the code will not be understood by a compiler
or interpreter.
Python Syntax
A simple python program

boys = 15
girls = 20
total = boys + girls
print (‘Total size of the class: ‘, total)

Fig. Program executed in Google Colab


1. Indentation - indicate a block of code
2. Variables
Variables are the computer memory locations which are used to store values in a computer
program.
It is also called as identifiers.

Eg: num = 5

Note:
1. variables are just names
2. A variable is a reference to the data which is stored in the memory so that you
don’t have to remember the lower level details of memory.
Variables

IN PROGRAMMING:
MATH:
variable is a quantity that can be changed
and is not fixed. A variable is a value that can change,
depending on conditions or on information
passed to the program.

Example: Variables used in our algorithm


are boys, girls and total

Note: variables are always associated with Data Types


Naming variables
Characters that can be used in framing variables
- Alphabet (lower and uppercase)
- Digits (0 through 9)
- underscore ( _ )
Conventions
- Names cannot begin with a digit or special symbols(@,#,etc)
- Keywords cannot be used as identifiers
- Variables can be of any length
- Variables are case sensitive
Multi Words Variable Names

1. Camel Case 3. Snake Case


Each word starts with a capital letter: Each word is separated by an underscore
myVariableName = “John” character:

my_variable_name = “John”
2. Pascal Case
Each word starts with a capital letter:
MyVariableName = “John”
Naming variables
Valid identifiers Invalid identifiers

num 1name

num102 @name

a_b_c_25 Global (keywords)


3. Data types
we often categorize things based on their
characteristics .

Due to the label outside, we know what


is stored inside the box, likewise data
type in programming tells the computer
what kind of data is inside or can be
stored in variable or storage location.
A data type refers to the type of value a variable has and what type of mathematical,
relational or logical operations can be applied.

There are two types of data types:

1. Primitive Data Type


2. Abstract Data Type
Primitive Data Type

It is a basic data type that is directly supported by the programming language.


It is often used for simple tasks like arithmetic and comparison operations.
Primitive Data Types
Data Type Definition Example

Integer (int) Numeric data type for 5, 20, 100 etc


numbers without fractions

Floating Point (float) Numeric data type for 5.6, 35.5, 307.7
numbers with fractions

Character (char) Single letter, digit, A, a, 1


punctuation mark, symbol,
or blank space

String (str or text) Sequence of characters, Hello, +97517000000


digits, or symbols—always
treated as text

Boolean (bool) True or false values 0 (false), 1 (true)


Abstract Data Type
It is a high level description of data structures.
It provides a more complex structure for storing and manipulating data.
The group of primitive data types represents the abstract data type.

Data Type Ordered Mutable Constructor Example

Lists Yes Yes [ ] or list () [5.7, 4, ’yes’, 5.7]

Tuple Yes No ( ) or tuple () (5.7, 4, ‘yes’, 5.7)

Set No Yes { } or set ( ) {5.7, 4, ‘yes’}

Dictionary No Yes { } or dic () {‘Jun’:75,’Jul’:89}


Data Type grouped into Category

Category Data Type

Text Type String

Numeric Int, float, complex

Sequence List, tuple, range

Mapping Type dict

Set Type Set, frozenset

Boolean Type bool

Binary Types Bytes, bytearray, memoryview

None Type NoneType


What are Data Types of the variables we identified before?

PSEUDOCODE
variables: a, b, sum
BEGIN AddNumbers
Data Type: int a = 10
b = 20
SET sum = 0
sum = a + b
Data Types in Python
PRINT sum
END AddNumbers
Constants
Constants are variables that hold a value and cannot be changed.

Python Constants Example

PI = 3.14

GRAVITY = 9.8

Note: Python Constants always use Uppercase


Operators

Operators are special symbols, combinations of symbols, or keywords that


designate some type of computation.
Arithmetic Operators: Arithmetic Operators are used with numeric values to
perform common mathematical operations.

Operator Description Example Result

+ Addition 5+8 13

- Subtraction 90-10 80

* Multiplication 4*7 28

/ Floating-point 7/2 3.5


division

// Integer division 7//2 3


7//2.0 3.0

% Modulus 7%3 1
7.0%3 1.0

** Exponential 3**4 81
3.0**4 81.0
Question
Which operator is used in our algorithm?
PSEUDOCODE
BEGIN AddNumbers
a = 10
b = 20
SET sum = 0
Arithmetic operators

Types of operators: sum = a + b


PRINT sum
END AddNumbers
Comparison Operators: Comparison operators are used to compare two values

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Logical Expression
Logical Operators/Expression

A logical expression is a statement that can either be true or false.

Logical operators are used on conditional statements (either True or False).

Example: 3<5, the result will be True.

Logical operators in Python.


Operator Name Example

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


statements are true

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


statements is true

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

PEDMAS

Parentheses, Exponential, Division/Multiplication, Addition/Subtraction

Operator Description

() Parentheses

** Exponentiation

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


bitwise NOT

* / // % Multiplication, division, floor


division, and modulus

+ - Addition and subtraction


Solve the expressions:

1. 25 + 10 * 20
2. (1+1)**(5-2)
3. 4/(3*(2-1))
Write a program to add two numbers

# Open Google Colab / VS code/ Pycharm /


# Create a file and Name your file as sum.py
A = 5
B = 6
Sum = A + B
print(Sum)
Comments in Python

Comments are short descriptions you can add to your code to increase the readability of your code.

1. Single-line comments

begin with the “#” character.

Eg: # This is a comment

2. Multi-Line Comments

Use either a ‘’ or “” quotation marks three times.

Eg: ‘’’ This program solves problems related to


Data type and functions’’’
Conditional Statement
Conditional statements in Programming, also known as decision-making
statements, allow a program to perform different actions based on whether a
certain condition is true or false.
IF Conditional Statement
The if statement is the most basic form of conditional statement. It checks if a
condition is true. If it is, the program executes a block of code.

a = 33 mark=70
b = 200
If mark>=50:
if b > a: print(“Pass”)
print("b is greater than a")
IF-ELSE Conditional Statement
The IF-Else statement extends the IF statement by adding an else clause. If the condition
is false, the program executes the code in the else block.

a = 200 mark=70
b = 33 If mark>=50:
if b > a:
print(“Pass”)
print("b is greater than a")
Else:
else:
print (“Fail”)
print("b is not greater than a")
IF-ELIF-ELSE Conditional Statement
The IF-ELIF-IF statement allows for multiple conditions to be checked in sequence. If the IF condition is false,
the program checks the next ELSE IF condition, and so on.

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


SWITCH Conditional Statement
The switch statement is used when you need to check a variable against a series of values. It’s often used
as a more readable alternative to a long if-else if chain. In Python 3.10 and after that, Python will support
this by using match in place of switch:
def number_to_string(argument): def game_menu(number):
match argument:
case 0: match number:
return "zero" case 1:
print("Play game")
case 1:
case 2:
return "one" print("Load game")
case 2: case 3:
return "two" print("Play Multi-player game")
case default: Case default:
print(“Bad Choice”)
return "something"
head = number_to_string(2) game_menu(1)
print(head)
Other Conditionals In Python
User Input in python

input ()
This function first takes the input from the user and converts it into a string.
The type of the returned object always will be <class ‘str’>.

Example:
username = input("Enter your username:")
print(username)

username = input("Enter username:")


print("Username is: ", username)
input ()

How do you take inputs of different data types then?


Type Casting
How do you take inputs of different data types then?

format: data_type(input())
Example: int(input())
Example
Example: a=”5.9”
num = int(input("Enter a number: "))
print(num, " ", type(num)) #typecast to float
n=float(a)
floatNum = float(input("Enter a decimal number: ")) print(n)
print(floatNum, " ", type(floatNum))
print(type(n))
Algorithm Python Code to add two given numbers

step 1 − START
step 2 − declare three integers a, b & sum
step 3 − define values of a & b
step 4 − add values of a & b
step 5 − store output of step 4 to sum step
6 − print sum
step 7 − STOP

# variables: a, b, sum
# Data Types: int (integer)
# Constants: 5 & 7
# keyword/inbuilt function: print()
# operator: + (arithmetic operator)
Preprocessing & Compilation

Compilers convert programming languages into binary code that computers can understand. If the syntax
is incorrect, the code will not compile.

Interpreters execute programming languages such as Python at runtime. The incorrect syntax will cause
the code to fail. That’s why it is crucial that a programmer pays close attention to a language’s syntax.

How does your computer run your program?


https://www.youtube.com/watch?v=3wuMRPhSNd0
https://www.youtube.com/watch?v=d7Qs-zHzQhc
Question

1. Write a python program to add two integers and print the result in the screen.
Prompt the user to enter two integer numbers (Accept value at run time).
1. The code begins by prompting the user to enter their name - storing it in the variable
name.
2. It then prompts the user to enter two numbers (num1 and num2) - stores them as
floating-point numbers.
3. The entered numbers (num1 and num2) are used to perform basic arithmetic
operations:
a. addition, subtraction, multiplication, and division.
b. The results of these operations are stored in separate variables (addition_result,
subtraction_result, etc.).
4. The program prints a personalized greeting along with the results using the print()
function. Ensure that the print statements are clear and informative, providing a
user-friendly output.
Thank You

You might also like