Chapter 2 Computer
Chapter 2 Computer
Program: A well-defined set of instructions given to computer is known as program. Different programs are
used for different problems.
Software: A set of instructions given to computer to solve a problem is called software. Program is a smaller
portion of a software.
Programming Language: A set of words and symbols used to write a computer program is known as
programming language.
Python
It is a type of high-level language that given instructions to computer hardware to solve any problem.
Python was created by a Dutch programmer named Guido van Rossum in the late 1980s. He started
working on it in 1989 and released the first version in 1991.
• 2000: Python 2.0 came with many new features (like garbage collection)
4. Versatile:
• Web development
• Data science
• AI & machine learning
• Automation/scripting
• Game development, and more
1. Write Code: First of all, the programmer has to write the instructions or code in any of the
programming language like python.
2. Compile/Interpret: In this step, the code is converted into language that is understandable by
the computer. The process of converting source code into object code is called compiling.
Interpreter is used in python language for this purpose.
3. Execute: The process of running the computer program is called executing. It is done after
compiling of the computer program.
4. Output: In this step, the result is displayed on the computer screen.
“The set of rules that define how programs are written in the programming
language”.
The syntax of the python language is very easy and understandable especially for the beginners.
In this example, the string I love programing will be displayed on the computer screen. There is no
need to place semicolon or any type of terminator at the end of the statement because syntax of this
language is straightforward.
Python Comments
Written By: Wasi Abbas (Aspire College Jhang)
Comments are the lines in the programming which are not executed. These are used in the program to
increase the readability of the program. These are helpful to programmers as well as other people to
understand the program late.
Types of Comments:
1. Single-line Comments
The type of comment which are used to comment a single line is called single-line comment. These are
placed using # symbol at the start of the line. Ideal for brief explanation of single line.
2. Multi-line Comments
The type of comments which are used to comment multiple lines at once are known as multi-line
comments. There are placed using “’ at the start and placing ‘’’ at the end of the comment. These are
best for longer explanation.
Variable
Variable is a named memory location or memory cell. It is used to store program’s input data and its
computational results during program execution. The name of the variable is not changed but its value
is changed during program execution.
Variables are created in RAM, therefore, the these are destroyed from the memory when program is
terminated. These are used to store values temporarily.
e.g. age=70
1. A variable may contain letter, number or underscore. But the first character must be a letter or
underscore.
2. Blank spaces are not allowed in variable name.
3. Variable names are case sensitive. This means age and AGE are different in python.
4. Keywords are not used as variable name like if, class etc.
5. Special symbols are not used in variable name like @age etc.
1. Integer (int): It is used to store all the number without decimal points.
E.g. age=70
2. Floating Point (float): It is used to store all the number with decimal point.
E.g. price=19.99
3. String (str): It is used to store text and characters enclosed in quotation marks.
E.g. is_true=True
Input Operation: Used to take input from the user during the execution of the program. It waits for
the user to type something and press Enter. Function used for this purpose is input ().
Output Operation: Used to display output on the screen. Function used for this purpose is print ().
Arithmetic operators
The types of operators which are used to apply basic mathematical operations on data are known as
arithmetic operators.
b=3
print(“a+b”, a+b)
print(“a-b”, a-b)
print(“a*b”, a*b)
print(“a/b”, a/b)
print(“a//b”, a//b)
print(“a%b”, a%b)
print(“a**b”, a**b)
Comparison Operators:
The type of operators which are used to compare two values are known as comparison operators.
These are also used to check the relationship between the values. Comparison operators returns the
values in the form of True and False.
x = 10
y=5
print(x>y) #True
print(x<y) #False
print(x==y) #False
print(x!=y) #True
print(x>=y) #True
Written By: Wasi Abbas (Aspire College Jhang)
print(x<=y) #False
Assignment Operators:
The type of operators which are used to assign values to variables are known as assignment operators.
The sign used to for this operator is =. This is also used with the combination of arithmetic operators.
In this operator, value is written on the right side and variable is written on the left side of the
assignment operator. Some operators are =, +=, -=, *=, /=, %= and **=.
Examples:
a = 10
b=5
a+=b
print(a)
a-=b
print(a)
Logical Operators:
The type of operators which are used to perform logical operation on data is called logical operators.
These are also used to solve compound conditions or multiple conditions. These are mostly used in
decision making structures like if, while etc.
and or
x y x and y x y x or y
T T T T T T
T F F T F T
F T F F T T
F F F F F F
and Operators Statement: and operators given us true value only when all the given inputs are true.
or operator statement: or operator gives us false value only when all the given inputs are false.
y = False
logical_and = x and y
print(logical_and) #False
Expression: An expression is a statement that consist of variable and values and provides single
answer. An expression has two parts: Operand and Operator. E.g. 3+4 = 7, a+b = ?
Written By: Wasi Abbas (Aspire College Jhang)
Programming Example: a = 10
b=5
sum = a+b
print(sum)
Operator Precedence:
The order in which different operators in an expression are evaluated is known as Operator
Precedence. Just like in mathematics we follow DMAS rule to solve any expression, we also some of
the rules to solve any expression in python. The operator with highest precedence will be solved prior
to the operator having less precedence.
Print(result) #13
result = (3+2) * 5
print(result) #25
Activity 1: Write a program to calculate Body Mass Index (BMI). (BMI = weight/height 2 )
bmi = weight/(height**2)
Control Structures
Written By: Wasi Abbas (Aspire College Jhang)
Def: Control structures are used to control the flow of execution in the program. We can say, these are
used to control the behavior of the program.
1. Decision Making
The type of control structure that is used to select a statement or set of statement on the basis
of condition is called decision making structure. It is also called selection structure.
Types of Decision Making:
a. if statement
It is a type of decision-making structure that is used to check the condition. If the condition
is true, a block of code will be executed and if the condition is false nothing will happen.
Syntax:
if condition:
Example:
temperature = 45
Programs
Write a program that inputs marks of the student Write a program that inputs two numbers and
and print congratulations if marks are greater than checks the numbers are equal.
or equal to 40:
a = int(input(“Enter first number”))
marks = int(input(“Enter your marks”)) b = int(input(“Enter second number”))
if marks >= 40: if a ==b:
print(“Congratulation! You are pass”) print(“Numbers are equal”)
Assignment:
Write a program that inputs a number and checks the number is even
b. if-else statement
Syntax:
if condition:
else:
Write a program that inputs a number and Write a program that inputs two numbers and
checks the number is even or odd: checks number are equal or not:
num = int(input(“Enter your number”)) num1 = int(input(“Enter first number”))
if num%2==0: num2 = int(input(“Enter second number”))
print(“Number is even”) if num1 == num2:
else: print(“Numbers are equal”)
print(“Number is odd”) else:
print(“Numbers are not equal”)
Write a program that inputs a number and Write a program that input year and checks the
checks the number is positive or negative: year is leap or not:
num = int(input(“Enter your number”)) year = int(input(“Enter year number”))
if num >=0: if year % 4==0:
print(“Number is positive”) print(“year is leap”)
else: else:
print(“Number is negative”) print(“year is not leap”)
c. if-elif-else
Syntax:
if condition1
elif condition2:
else:
A shorthand if-else statement is a compact way to write a simple if-else condition in one line.
These are much useful when condition and actions are simple. This is also called a ternary
conditional expression.
Syntax:
num = 5 a = 10
result = "Even" if num % 2 == 0 else "Odd" b = 20
print(result) greater = a if a > b else b
print("Greater number is:", greater)
Loops
It is a type of control structure that is used to repeat a statement or set of statement for specific
number of times. We use loops to perform repetitive tasks. We have two types of loops: while and for.
1. while loop
It is a type of loop that is used to repeat a statement or set of statements as long as condition
remains true. It is used to repeat a statement or set of statement for specific number of times. It is
also known as conditional loop.
Syntax
while condition:
Working: First of all, the condition will be checked. If the condition is true, then, all the statements
in the body of while loop will be executed. It will execute it again and again till the condition
remains true. But, if the condition will be false, the loop will be ended.
Programs
num = 1 n=2
while num <= 5: while n <= 10:
print(num) print(n)
num += 1 n += 2
Sum of first 5 natural numbers Table
num = 1 num = 5
Written By: Wasi Abbas (Aspire College Jhang)
total = 0 i=1
while num <= 5:
total += num while i <= 10:
num += 1 print(f"{num} x {i} = {num * i}")
print("Sum is:", total) i += 1
Note: Here f in print is formatted string literal",
also known as an f-string.
Factorial Table by taking input from user
For loop
It is a type of loops that is used to repeat a statement or set of statements for specific number of
times. We use this loop when we know the number of iterations in advance.
Syntax
Example:
for i in range(5):
Function: In Python, a function is a block of reusable code that performs a specific task. Functions help
make your code more organized, readable, and easier to maintain.
Defining a function: You define a function using the def keyword, followed by the function name,
parentheses () (which may include parameters), and a colon:. The body of the function is indented.
Syntax:
def function_name(parameters):
return result
def greet():
print("Hello, world!")
Functions can take multiple parameters and returns values as shown in the example.
return a + b
result = add(5, 3)
print(result) # Output: 8
Function can have default parameter values, which are used if no argument is provided during function
call:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
1. Code Reusability
2. Easy to read and manage
3. Avoid repetition
4. Makes testing and debugging easier
5. Modularity
Using libraries and modules in Python allows you to take advantage of pre-written code so you don't
have to "reinvent the wheel." It helps you write more efficient, readable, and powerful programs.
Term Description
Module A single .py file that contains Python code (functions, variables, classes).
Package A directory containing multiple modules (and possibly sub-packages) with an __init__.py file.
import math
# Calculate cosine of 0
Import
import random
Use a Function
Package Structure
A package in Python is a way to organize related modules into a single directory structure. It makes
your code more modular and reusable, especially for larger projects. E.g. if you are building an e-
commerce platform, you can create a package named ec0mmerce with the modules like products.py,
customer.py and order.py.
Example: in ecommerce/products.py
def list_products():
in main script
available_products = products.list_products()
print(available_products)
Python provides many built-in data structures which are used to organize and modify data efficiently.
Here we have some of the data structures:
Lists
A list is collection of different items written in the square brackets []. Every item in the bracket is
separated with the coma. Lists are very much flexible so it allows the user to add, change or remove
the item very easily. A list may have every kind of data.
1. Creating a list
We can create a list by placing the items inside the square brackets:
Print(names)
We can access each item in the list with the help of index number (starting from 0).
print(names[1])