KEMBAR78
Chapter 2 Computer | PDF | Python (Programming Language) | Computer Program
0% found this document useful (0 votes)
50 views14 pages

Chapter 2 Computer

Uploaded by

folog85500
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)
50 views14 pages

Chapter 2 Computer

Uploaded by

folog85500
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/ 14

Written By: Wasi Abbas (Aspire College Jhang)

Chapter 2: Python Programming


Language: Language is a source of communication between a user and 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.

Types of Programming Language:


1. High level language: A type of programming that is close to human language and far from computer
hardware is known as high level language. This is English type language and is easy to understand. E.g.
Python, php, C etc.
2. Low level language: A type of programming language that is close to computer hardware and far from
human language is known as low level language. It has further two categories:
a. Machine Language: It is a type of low-level language. It is in the form of binary language (0,1). It is the
fundamental language of computer. It is only language that is directly understood by the computer.
b. Assembly Language: It is a type of low-level language. In assembly language, machine instructions are
replaced with English like words or symbols. Therefore, it is also known as symbolic 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.

Why is it called "Python"?


It’s not named after the snake! Guido was a fan of a British comedy show called “Monty Python’s
Flying Circus,” so he named the language after that.

Python’s growth over time:

• 1991: Python 1.0 was released

• 2000: Python 2.0 came with many new features (like garbage collection)

• 2008: Python 3.0 was released (not backward-compatible with Python 2)

• 2020: Python 2 officially retired

• Today: Python is one of the most popular languages in the world

Key Features of Python

1. Easy to Learn and Use


Python has simple, readable syntax, more like English. Great for beginners!
Written By: Wasi Abbas (Aspire College Jhang)

2. Open Source and Free


Python is completely free to use, for personal, educational, or commercial projects.

3. Huge Community Support


If you ever get stuck, there's a large community, tons of tutorials, and support online.

4. Versatile:

Python is used in:

• Web development
• Data science
• AI & machine learning
• Automation/scripting
• Game development, and more

Understanding Basic Programming Concepts:


Computer is a machine that follows the instructions given to it. All of these instructions are written in
some kind of programming languages like Python. It allows the user to control the behavior of the
computer and solve real life problems. Here are the steps involved in writing program in python.

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.

Basic Python syntax and Structure


Syntax is defined as:

“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.

e.g. print(“I love programming”)

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.

e.g. #This is a single-line comment

print(“I love python programming”)

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.

e.g. “’This is multi-line comment.

It can span on multiple lines.”’

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

print(“My grandfather lives”, age, “years”)

Variable Naming Rules in Python


Here are some of the rules for naming variable names.

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.

Creating Different Types of Variables


Here are different data types or types of variables:
Written By: Wasi Abbas (Aspire College Jhang)

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. name=” Wasi”

4. Boolean (bool): It is used to store two values, True or false.

E.g. is_true=True

Input and output Operations in Python


Input and output operations are performed to interact with the user in python. These operations are
used to receive data from user and then display results on the screen.

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 ().

E.g. name = input(“Enter your name: “)

Output Operation: Used to display output on the screen. Function used for this purpose is print ().

E.g. print(“Hello, +name+ “)

Handling Integer and Float Inputs


To handle numeric inputs, integer and float data types are used in python but these are used for
different purposes.

E.g. age = int(input(“Enter your age: “))

print(“Your age is:” age)

height = float(input(“Enter your height: “))

print(“Your height is:” height)

Operators and Expressions


Operators are the symbols which are used to apply operation on data. Here we have different types of
operators used in python language:

Arithmetic operators

The types of operators which are used to apply basic mathematical operations on data are known as
arithmetic operators.

Operator Name Description


+ Addition Adds Operands
Written By: Wasi Abbas (Aspire College Jhang)

- Subtraction Subtract operands


* Multiplication Multiplies Operands
/ Division Divides first operand with second
// Floor Division Returns integer part of division
% Modulus Returns Remainder
** Exponent Power
Programming Example:
a = 10

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.

Operator Description Example (x =10, y = 5) Result


> Greater than x>y True
< Less than x<y False
== Equal to x==y False
!= Not equal to x!=y True
>= Greater than equal to x>=y True
<= Less than equal to X<=y False
Programming Example:

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.

Here are some of the logical operators used in python:

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.

Programming Example: x = True

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.

Precedence Level Operators


1 (Highest ()
2 **
3 *, /, //, %
4 +, -
5 =
Programming Example: result = 3+2*5

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 )

weight = float(input(“Enter your weight in kg: “ ))

height = float(input(“Enter your height in meter: “))

bmi = weight/(height**2)

print(“Your BMI is:” bmi)

Write a program to take sum of two numbers: Using input

a = 10 a = int(input(“Enter first Number:” ))

b = 15 b = int(input (“Enter second Number:” ))

sum = a+b sum = a+b

print(“The sum is:”, sum) print(“ The sum is:”, sum)

Assignment: Write a program to take the average of five numbers.

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.

Types of control structures:

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:

#code to run if condition is true

Example:

temperature = 45

if temperature > 30:

print(“It is hot day”

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

it is a type of selection structure. It is also known as if statement with two alternatives. It is


used to execute one block of code if the condition is true and other block when the condition is
false.

Syntax:

if condition:

#code to run if the condition is true

else:

#code to run is the condition is false


Written By: Wasi Abbas (Aspire College Jhang)

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

It is a type of decision-making structure. It is also known as if statement with multiple


conditions. It is used when we have many conditions to check. It allows the program to run
different blocks of code depending on which conditions is true.

Syntax:

if condition1

#code to run if condition1 s true

elif condition2:

#code to run id condition2 is true

else:

#code to run is none of the condition is true


Write a program that inputs a numbers and checks Write a program that inputs marks and prints grades
whether the number is positive, negative or zero: using criteria:
marks = int(input(“Enter your marks:” ))
num = int(input(“Enter your number”)) if marks >= 80:
if num > 0: print(“A grade”)
print(“Number is positive”) elif marks >= 60:
elif num < 0: print(“B grade”)
print(“Number is negative”) elif marks >= 50:
else: print(“C grade”)
print(“Number is zero”) elif marks >=33:
print(“D grade”)
else:
print(“F grade”)
Write a program to check if a person is a child, Write a program to find the largest of three numbers:
teenager, or adult: a = int(input("Enter first number: "))
age = int(input("Enter your age: ")) b = int(input("Enter second number: "))
if age < 13: c = int(input("Enter third number: "))
print("You are a child.") if a >= b and a >= c:
elif age < 20: print("The largest number is", a)
print("You are a teenager.") elif b >= a and b >= c:
else: print("The largest number is", b)
print("You are an adult.") else:
Written By: Wasi Abbas (Aspire College Jhang)

print("The largest number is", c)


Assignment: Make a simple arithmetic calculator is python.

d. Shorthand if-else statement

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:

value_if_true if condition else value_if_false

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:

#code to run while the condition is true

Condition: It is a statement that can either be true or false.

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

Print numbers from 1 to 5 Print even numbers from 2 to 10

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

num = 5 num = int(input("Enter a number to print its


factorial = 1 table: "))
i=1
while num > 0:
factorial *= num while i <= 10:
num -= 1 print(f"{num} x {i} = {num * i}")
i += 1
print("Factorial is:", factorial)
Assignment: Write a program that inputs a number from user and prints its factorial.

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

for variable in sequence:

# code block (indented)

Example:

for i in range(5):

print("Hy Wasi Abbas")

Print numbers from 1 to 5 Print all items in a list

for i in range(1, 6): fruits = ["apple", "banana", "cherry"]


print(i) for fruit in fruits:
print(fruit)
Sum of numbers from 1 to 10 Even numbers from 2 to 10

total = 0 for num in range(2, 11, 2):


for i in range(1, 11): print(num)
total += i • range(2, 11, 2) starts at 2, goes up to 10 (because 11
print("Sum:", total) is excluded), and steps by 2 each time.
• This gives all even numbers between 2 and 10.

Print first 10 multiples of 3 Table by taking input from user

for i in range(1, 11): num = int(input("Enter a number: "))


Written By: Wasi Abbas (Aspire College Jhang)

print(3 * i) for i in range(1, 11):


print(f"{num} x {i} = {num * i}")

Print a message multiple times Print even numbers up to a user-entered limit


n = int(input("How many times do you want limit = int(input("Enter the maximum number: "))
to print the message? "))
for num in range(2, limit + 1, 2):
for i in range(n): print(num)
print("Hello!")
Python Modules and Built-in Data Structures

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

# Code block (function body)

return result

Example 1: Function with no parameters

def greet():

print("Hello, world!")

greet() # Output: Hello, world!

Example 2: Function with parameters

Functions can take multiple parameters and returns values as shown in the example.

def add(a, b):

return a + b

result = add(5, 3)

print(result) # Output: 8

Example 3: Function with default parameters

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("Alice") # Output: Hello, Alice!


Written By: Wasi Abbas (Aspire College Jhang)

greet()

Advantages of Using Functions:

1. Code Reusability
2. Easy to read and manage
3. Avoid repetition
4. Makes testing and debugging easier
5. Modularity

Using Libraries and Modules

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

Library A collection of modules that provide useful functionality.

Package A directory containing multiple modules (and possibly sub-packages) with an __init__.py file.

Example: Using the math Library

Import the Library

import math

Use Functions from the Library

# Find square root of 25

print(math.sqrt(25)) # Output: 5.0

# Get the value of pi

print(math.pi) # Output: 3.141592653589793

# Calculate cosine of 0

print(math.cos(0)) # Output: 1.0

Example: Using random Library

Import

import random

Use a Function

# Generate a random number between 1 and 10

num = random.randint(1, 10)


Written By: Wasi Abbas (Aspire College Jhang)

print("Random number:", num)

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():

return[“Laptop”, “Mobile”, “Tablet”]

in main script

from ecommerce import products

available_products = products.list_products()

print(available_products)

Built-In Data Structures

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:

names = [Ali, Abbas, Burhan, Razzaq]

Print(names)

2. Accessing List Items

We can access each item in the list with the help of index number (starting from 0).

names = [“Ali”, “Abbas”, "Razzaq”]

print(names[1])

You might also like