2 مختبر اساسيات الحاسوب
1. Introduction to Python
Python is a popular programming language created by Guido van Rossum
and released in 1991.
❖ Main Uses
• Web development (server-side)
• Software development
• Mathematics
• System scripting
❖ Applications of Python
• Create web applications on a server.
• Build software and manage workflows.
• Connect to databases and read/modify files.
• Handle big data and perform complex mathematics.
• Develop prototypes quickly or build production-ready programs.
❖ Setting Up Python Environment
Installing Python
Option A: Online (Recommended for beginners):
• Go to [Link] or [Link].
• Create free account and start new Python project.
Option B: Local Installation:
Download Python from [Link].
• Install Python 3.8 or newer.
• Use IDLE or install VS Code.
1
2 مختبر اساسيات الحاسوب
❖ First Program
Task 1: Run your first program and modify it to print your favorite subject.
2
2 مختبر اساسيات الحاسوب
2. Variables and Data Types
❖ Variables
Variables are containers for storing data values.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
3
2 مختبر اساسيات الحاسوب
❖ Data Types
Python has the following data types built-in by default, in these categories:
Category Data Type Example
Text Str x = "Hello World"
int x = 20
Numeric float x = 20.5
complex x = 1j
list x = ["apple", "banana", "cherry"]
Sequence tuple x = ("apple", "banana", "cherry")
range x = range(6)
Mapping dict x = {"name" : "John", "age" : 36}
set x = {"apple", "banana", "cherry"}
Set
frozenset x = frozenset({"apple", "banana", "cherry"})
Boolean bool x = True
bytes x = b"Hello"
Binary bytearray x = bytearray(5)
memoryview x = memoryview(bytes(5))
None NoneType x = None
4
مختبر اساسيات الحاسوب 2
❖ Examples
5
مختبر اساسيات الحاسوب 2
6
2 مختبر اساسيات الحاسوب
❖ Python Operators
Operators are used to perform operations on variables and values.
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x**y
// Floor division x//y
❖ Examples
7
2 مختبر اساسيات الحاسوب
Task 3: Calculate the average of your last 4 exam scores.
8
2 مختبر اساسيات الحاسوب
3. Python Conditions and Loops
Python supports the usual logical conditions from mathematics:
Condition Example
Equals a==b
Not Equals a!=b
Less than a<b
Less than or equal to a <= b
Greater than a>b
Greater than or equal to a >= b
These conditions can be used in several ways, most commonly in "if statements"
and loops.
❖ Making Decisions (If Statements)
9
مختبر اساسيات الحاسوب 2
10
2 مختبر اساسيات الحاسوب
Task 4: Write a program that determines if a student passes (grade >= 60)
or fails.
❖ Loops (Repetition)
Python has two primitive loop commands:
• for loops
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.
11
مختبر اساسيات الحاسوب 2
12
2 مختبر اساسيات الحاسوب
• while loops
With the while loop we can execute a set of statements as long as a
condition is true.
13
2 مختبر اساسيات الحاسوب
Task 5: Create a list of 5 countries and print "I want to visit [country]" for
each one.
14
2 مختبر اساسيات الحاسوب
4. Matplotlib Plotting
• Plotting x and y points.
• The plot() function is used to draw points (markers) in a diagram.
• By default, the plot() function draws a line from point to point.
• The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
Example
Draw a line in a diagram from position (1, 3) to position (8, 10):
Result:
15
2 مختبر اساسيات الحاسوب
❖ Plotting Without Line
To plot only the markers, you can use shortcut string notation parameter
'o', which means 'rings'.
Example
Draw two points in the diagram, one at position (1, 3) and one in position
(8, 10):
Result:
❖ Multiple Points
You can plot as many points as you like, just make sure you have the same
number of points in both axis.
16
2 مختبر اساسيات الحاسوب
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and
finally to position (8, 10):
Result:
17
2 مختبر اساسيات الحاسوب
5. Python Function
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
❖ Creating a Function
In Python a function is defined using the def keyword:
Example
❖ Calling a Function
Example
To call a function, use the function name followed by parenthesis:
❖ Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:
18
2 مختبر اساسيات الحاسوب
Example
❖ Number of Arguments
By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you have to
call the function with 2 arguments, not more, and not less.
Example
19
2 مختبر اساسيات الحاسوب
6. Linear Regression
The term regression is used when you try to find the relationship between
variables.
In Machine Learning, and in statistical modeling, that relationship is used to
predict the outcome of future events.
❖ Linear Regression
Linear regression uses the relationship between the data-points to draw a
straight line through all them.
This line can be used to predict future values.
• How Does it Work?
Python has methods for finding a relationship between data-points and
to draw a line of linear regression. We will show you how to use these
methods instead of going through the mathematic formula.
In the example below, the x-axis represents age, and the y-axis
represents speed. We have registered the age and speed of 13 cars as
20
2 مختبر اساسيات الحاسوب
they were passing a tollbooth. Let us see if the data we collected could
be used in a linear regression:
Example
Start by drawing a scatter plot:
Result:
Example
Import scipy and draw the line of Linear Regression:
21
2 مختبر اساسيات الحاسوب
Result:
• Example Explained
Import the modules you need.
22
2 مختبر اساسيات الحاسوب
Create the arrays that represent the values of the x and y axis:
Execute a method that returns some important key values of Linear
Regression:
Create a function that uses the slope and intercept values to return a new
value. This new value represents where on the y-axis the corresponding x
value will be placed:
Run each value of the x array through the function. This will result in a new
array with new values for the y-axis:
Draw the original scatter plot:
23
2 مختبر اساسيات الحاسوب
Draw the line of linear regression:
Display the diagram:
24
2 مختبر اساسيات الحاسوب
7. Machine Learning - K-means
❖ K-means
K-means is an unsupervised learning method for clustering data points.
The algorithm iteratively divides data points into K clusters by minimizing
the variance in each cluster.
Here, we will show you how to estimate the best value for K using the
elbow method, then use K-means clustering to group the data points into
clusters.
❖ How does it work?
First, each data point is randomly assigned to one of the K clusters. Then,
we compute the centroid (functionally the center) of each cluster, and
reassign each data point to the cluster with the closest centroid. We repeat
this process until the cluster assignments for each data point are no longer
changing.
K-means clustering requires us to select K, the number of clusters we want
to group the data into. The elbow method lets us graph the inertia (a
distance-based metric) and visualize the point at which it starts decreasing
linearly. This point is referred to as the "elbow" and is a good estimate for
the best value for K based on our data.
Example
25
مختبر اساسيات الحاسوب 2
Result
26
مختبر اساسيات الحاسوب 2
27
2 مختبر اساسيات الحاسوب
8. Scatter Plot
A scatter plot is a diagram where each value in the data set is represented by
a dot.
The Matplotlib module has a method for drawing scatter plots, it needs two
arrays of the same length, one for the values of the x-axis, and one for the
values of the y-axis:
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
The x array represents the age of each car.
The y array represents the speed of each car.
Example
Use the scatter() method to draw a scatter plot diagram:
28
2 مختبر اساسيات الحاسوب
Result:
• Scatter Plot Explained
The x-axis represents ages, and the y-axis represents speeds.
What we can read from the diagram is that the two fastest cars were both 2
years old, and the slowest car was 12 years old.
Note: It seems that the newer the car, the faster it drives, but that could be a
coincidence, after all we only registered 13 cars.
29
2 مختبر اساسيات الحاسوب
9. Machine Learning - Train/Test
❖ Evaluate Your Model
In Machine Learning we create models to predict the outcome of certain
events, like in the previous chapter where we predicted the CO2 emission
of a car when we knew the weight and engine size.
To measure if the model is good enough, we can use a method called
Train/Test.
❖ What is Train/Test
Train/Test is a method to measure the accuracy of your model.
It is called Train/Test because you split the data set into two sets: a training
set and a testing set.
❖ Start With a Data Set
Start with a data set you want to test.
Our data set illustrates 100 customers in a shop, and their shopping habits.
Example
❖ Split Into Train/Test
The training set should be a random selection of 80% of the original data.
30
2 مختبر اساسيات الحاسوب
The testing set should be the remaining 20%.
❖ Fit the Data Set
What does the data set look like? In my opinion I think the best fit would
be a polynomial regression, so let us draw a line of polynomial regression.
To draw a line through the data points, we use the plot() method of the
matplotlib module:
Example
31
مختبر اساسيات الحاسوب 2
Result:
32
2 مختبر اساسيات الحاسوب
10. K-nearest neighbors (KNN)
KNN is a simple, supervised machine learning (ML) algorithm that can be
used for classification or regression tasks - and is also frequently used in
missing value imputation. It is based on the idea that the observations closest
to a given data point are the most "similar" observations in a data set, and we
can therefore classify unforeseen points based on the values of the closest
existing points. By choosing K, the user can select the number of nearby
observations to use in the algorithm.
• How does it work?
K is the number of nearest neighbors to use. For classification, a majority
vote is used to determined which class a new observation should fall into.
Larger values of K are often more robust to outliers and produce more stable
decision boundaries than very small values (K=3 would be better than K=1,
which might produce undesirable results.
Example
Start by visualizing some data points:
33
2 مختبر اساسيات الحاسوب
Result:
Now we fit the KNN algorithm with K=1:
And use it to classify a new data point:
Example
34
2 مختبر اساسيات الحاسوب
Result:
Now we do the same thing, but with a higher K value which changes the
prediction:
Example
Result:
35
2 مختبر اساسيات الحاسوب
• Example Explained
Import the modules you need.
scikit-learn is a popular library for machine learning in Python.
Create arrays that resemble variables in a dataset. We have two input
features (x and y) and then a target class (class). The input features that are
pre-labeled with our target class will be used to predict the class of new
data. Note that while we only use two input features here, this method will
work with any number of variables:
Turn the input features into a set of points:
36
2 مختبر اساسيات الحاسوب
Result:
Using the input features and target class, we fit a KNN model on the model
using 1 nearest neighbor:
Then, we can use the same KNN object to predict the class of new,
unforeseen data points. First we create new x and y features, and then
call [Link]() on the new data point to get a class of 0 or 1:
Result:
When we plot all the data along with the new point and class, we can see it's
been labeled blue with the 1 class. The text annotation is just to highlight
the location of the new point:
37
2 مختبر اساسيات الحاسوب
Result:
However, when we changes the number of neighbors to 5, the number of
points used to classify our new point changes. As a result, so does the
classification of the new point:
Result:
38
مختبر اساسيات الحاسوب 2
© 39