Python
Python
Introduction
Computers can perform such a wide variety of tasks because they can be programmed. This means that
computers are not designed to do just one job, but to do any job that their programs tell them to do.
Programs are commonly referred to as software. Software is essential to a computer because it controls
everything the computer does.
This course introduces you to the fundamental concepts of computer programming using the Python
language. The Python language is a good choice for beginners because it is easy to learn, and programs
can be written quickly using it.
Python is a general-purpose language created in the early 1990s. It has become popular in business and
academic applications.
Depending on the language in which a program has been written, the programmer will use either a
compiler or an interpreter to make the translation.
A compiler is a program that translates a high-level language program into a separate machine language
program. The machine language program can then be executed any time it is needed.
The Python language uses an interpreter, which is a program that both translates and executes the
instructions in a high-level language program.
As the interpreter reads each individual instruction in the program, it converts it to machine language
instructions then immediately executes them. Because interpreters combine translation and execution,
they typically do not create separate machine language programs.
Using Python
Before write any programs of your own, you need to make sure that Python is installed on your computer
and properly configured.
When you install the Python language on your computer, one of the items that is installed is the Python
interpreter.
The Python interpreter is a program that can read Python programming statements and execute them.
You can use the interpreter in two modes: interactive mode and script mode. In interactive mode, the
interpreter waits for you to type Python statements on the keyboard. Once you type a statement, the
interpreter executes it and then waits for you to type another statement.
In script mode, the interpreter reads the contents of a file that contains Python statements. Such a file is
known as a Python program or a Python script.
❑ False
What is the difference between a compiler and an
interpreter?
Questions
An interpreter is a program that both translates and
executes the instructions in a high-level language
program.
❑ True
❑ False
5
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
1. Input is received.
3. Output is produced.
Input is any data that the program receives while it is running. One common form of input is data that is
typed on the keyboard. Once input is received, some process, such as a mathematical calculation, is
usually performed on it. The results of the process are then sent out of the program as output.
Perhaps the most fundamental built-in function is the print function, which displays output on the
screen.
When you call the print function, you type the word print, followed by a set of parentheses. Inside the
parentheses, you type an argument, which is the data that you want displayed on the screen.
In programming terms, a sequence of characters that is used as data is called a string. When a string
appears in the actual code of a program, it is called a string literal.
In Python, you can enclose string literals in a set of single-quote marks (') or double-quote marks (").
If you want a string literal to contain either a single-quote or an apostrophe as part of the string, you can
enclose the string literal in double-quote marks.
حيدر احمد عبدالمحسن.د 7
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
Comments
Comments are short notes placed in different parts of a program, explaining how those parts of the
program work. Although comments are a critical part of a program, they are ignored by the Python
interpreter.
Comments are intended for any person reading a program’s code, not the computer.
In Python, you begin a comment with the # character. When the Python interpreter sees a # character, it
ignores everything from that character to the end of the line.
10
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
Variables
Programs usually store data in the computer’s memory and perform operations on that data.
Programs use variables to access and manipulate data that is stored in memory.
You use an assignment statement to create a variable and make it reference a piece of data.
After the above statement executes, a variable named age will be created, and it will reference the
value 25.
The equal sign (=) is known as the assignment operator. In the general format, variable is the name of a
variable and expression is a value, or any piece of code that results in a value.
The first character must be one of the letters a through z, A through Z, or an underscore character (_).
After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or
underscores.
Uppercase and lowercase characters are distinct. This means the variable name ItemsOrdered is not the same as
itemsordered.
In addition to following these rules, you should always choose names for your variables that give an
indication of what they are used for. For example, a variable that holds the temperature might be named
temperature, and a variable that holds a car’s speed might be named speed.
Variables are called “variable” because they can reference different values while a program is running.
15
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
A number that is written into a program’s code is called a numeric literal. When the Python interpreter
reads a numeric literal in a program’s code, it determines its data type according to the following rules:
A numeric literal that is written as a whole number with no decimal point is considered an int. Examples are 7,
124, and −9.
A numeric literal that is written with a decimal point is considered a float. Examples are 1.5, 3.14159, and 5.0.
When you store an item in memory, it is important for you to be aware of the item’s data type. As you
will see, some operations behave differently depending on the type of data involved, and some
operations can only be performed on values of a specific data type.
A variable in Python can refer to items of any type. After a variable has been assigned an item of one
type, it can be reassigned an item of a different type.
Questions
What will be displayed by the following program?
18
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
The input function reads a piece of data that has been entered at the keyboard and returns that piece of
data, as a string, back to the program.
You normally use the input function in an assignment statement that follows this general format:
The program pauses and waits for the user to type something on the keyboard and then to press the Enter key.
When the Enter key is pressed, the data that was typed is returned as a string and assigned to the name variable.
This can be a problem if you want to use the value in a math operation. Math operations can be
performed only on numeric values, not strings.
Fortunately, Python has built-in functions that you can use to convert a string to a numeric type. Table
below summarizes two of these functions.
23
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
Performing Calculations
Most real-world algorithms require calculations to be performed. A programmer’s tools for performing
calculations are math operators.
Table below lists the math operators that are provided by the Python language.
Performing Calculations
When we use a math expression to calculate a value, normally we want to save that value in memory so
we can use it again in the program. We do this with an assignment statement. Program 2-14 shows an
example.
Both operators divide one number by another. The difference between them is that the / operator gives
the result as a floating-point value, and the // operator gives the result as a whole number.
When the result is positive, it is truncated, which means that its fractional part is thrown away.
When the result is negative, it is rounded away from zero to the nearest integer.
Operator Precedence
First, operations that are enclosed in parentheses are performed first. Then, when two operators share
an operand, the operator with the higher precedence is applied first.
Exponentiation: **
Notice the multiplication (*), floating-point division (/), integer division (//), and remainder (%) operators
have the same precedence. The addition (+) and subtraction (−) operators also have the same
precedence.
When two operators with the same precedence share an operand, the operators execute from left to
right.
حيدر احمد عبدالمحسن.د 28
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
On the right side of the assignment operator, 1 is added to x. The result is then assigned to x, replacing
the value that x previously referenced. Effectively, this statement adds 1 to x.
These types of operations are common in programming. For convenience, Python offers a special set of
operators designed specifically for these jobs. Table below shows the augmented assignment operators.
Questions
What value will be assigned to result after the following
statement executes? result = 9 // 2
What value will be assigned to result after the following
statement executes? result = 9 % 2
30
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
You simply type the backslash character at the point you want to break the statement, then press the
Enter key.
Python also allows you to break any part of a statement that is enclosed in parentheses into multiple lines
without using the line continuation character.
Each of the statements shown here displays a string and then prints a newline character. It causes the
output to advance to the next line.
If you do not want the print function to start a new line of output when it finishes displaying its output,
you can pass the special argument end= ' ' to the function, as shown in the following code:
Sometimes, you might not want the print function to print anything at the end of its output, not even a
space. If that is the case, you can pass the argument end='' to the print function.
Escape Characters
An escape character is a special character that is preceded with a backslash (\), appearing inside a string
literal.
When a string literal that contains escape characters is printed, the escape characters are treated as
special commands that are embedded in the string.
Python recognizes several escape characters, some of which are listed in Table below.
Escape Characters
You saw that the + operator is used to add two numbers. When the + operator is used with two strings,
however, it performs string concatenation. This means that it appends one string to another.
Formatting Numbers
When a floating-point number is displayed by the print function, it can appear with up to 12 significant
digits.
Sometimes, it would be nice to see that amount rounded to two decimal places. Fortunately, Python gives
us a way to do just that, and more, with the built-in format function.
When you call the built-in format function, you pass two arguments to the function: a numeric value and
a format specifier. The format specifier is a string that contains special characters specifying how the
numeric value should be formatted.
The f specifies that the data type of the number we are formatting is a floating-point number.
Formatting Numbers
If you prefer to display floating-point numbers in scientific notation, you can use the letter e or the letter
E instead of f.
If you want the number to be formatted with comma separators, you can insert a comma into the format
specifier.
Instead of using f as the type designator, you can use the % symbol to format a floating-point number as a
percentage.
37
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
Decision Structure
A control structure is a logical design that controls the order in which a set of statements execute.
Some programs require a different type of control structure: one that can execute a set of statements
only under certain circumstances. This is accomplished with a decision structure (selection structure)
The if Statement
In Python, we use the if statement to write a single alternative decision structure. Here is the general
format of the if statement:
When the if statement executes, the condition is tested. If the condition is true, the statements that
appear in the block following the if clause are executed. If the condition is false, the statements in the
block are skipped.
The expressions that are tested by the if statement are called Boolean expressions. Typically, the Boolean
expression that is tested by an if statement is formed with a relational operator.
A relational operator determines whether a specific relationship exists between two values. For example,
the greater than operator (>) determines whether one value is greater than another.
حيدر احمد عبدالمحسن.د 40
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
Two of the operators, >= and <=, test for more than one relationship. They determine whether the
operand on its left is greater than (less than) or equal to the operand on its right.
Questions
What types of relationships between values can you test
with relational operators?
42
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
In code, we write a dual alternative decision structure as an if-else statement. Here is the general format
of the if-else statement:
44
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
Python provides a special version of the decision structure known as the if-elif-else statement, which
makes programs with many conditions simpler to write.
Questions
46
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
Logical Operators
Python provides a set of operators known as logical operators, which you can use to create complex
Boolean expressions. Table below describes these operators.
Boolean Variables
So far, we have worked with int, float, and str (string) variables. In addition to these data types, Python
also provides a bool data type.
The bool data type allows you to create variables that may reference one of two possible values: True or
False. Here are examples of how we assign values to a bool variable:
Boolean variables are most commonly used as flags. A flag is a variable that signals when some condition
exists in the program. When the flag variable is set to False, it indicates the condition does not exist.
When the flag variable is set to True, it means the condition does exist.
Instead of writing the same sequence of statements over and over, a better way to repeatedly perform an
operation is to write the code for the operation once, then place that code in a structure that makes the
computer repeat it as many times as necessary.
This can be done with a repetition structure, which is more commonly known as a loop.
In this course, we will look at two broad categories of loops: condition-controlled and count-controlled.
A condition-controlled loop uses a true/false condition to control the number of times that it repeats. A
count-controlled loop repeats a specific number of times.
In Python, you use the while statement to write a condition-controlled loop, and you use the for
statement to write a count-controlled loop.
(2) a statement or set of statements that is repeated as long as the condition is true.
following the while clause are executed, and the loop starts
54
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
The for statement executes in the following manner: The variable is assigned the first value in the list,
then the statements that appear in the block are executed. Then, variable is assigned the next value in
the list, and the statements in the block are executed again.
This continues until variable has been assigned the last value in the list.
Python programmers commonly refer to the variable that is used in the for clause as the target variable
because it is the target of an assignment at the beginning of each loop iteration.
The range function creates a type of object known as an iterable. An iterable is an object that is similar
to a list. It contains a sequence of values that can be iterated over with something like a loop.
In the below statement, the range function will generate an iterable sequence of integers in the range of
0 up to (but not including) 5.
If you pass two arguments to the range function, the first argument is used as the starting value of the
sequence, and the second argument is used as the ending limit.
If you pass a third argument to the range function, that argument is used as step value.
2
Questions
3
59
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
Introduction to Functions
Most programs perform tasks that are large enough to be broken down into several subtasks. For this
reason, programmers usually break down their programs into small manageable pieces known as
functions.
A function is a group of statements that exist within a program for the purpose of performing a specific
task.
Instead of writing a large program as one long sequence of statements, it can be written as several small
functions, each one performing a specific part of the task.
These small functions can then be executed in the desired order to perform the overall task.
This approach is sometimes called divide and conquer because a large task is divided into several smaller
tasks that are easily performed.
Code Reuse
Better Testing
Faster Development
When you call a void function, it simply executes the statements it contains and then terminates.
When you call a value-returning function, it executes the statements that it contains, then returns a
value back to the statement that called it.
The input function is an example of a value-returning function. When you call the input function, it gets
the data that the user types on the keyboard and returns that data as a string.
The int and float functions are also examples of value-returning functions. You pass an argument to the
int function, and it returns that argument’s value converted to an integer.
The first type of function that you will learn to write is the void function.
64
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
The first line is known as the function header. It marks the beginning of the function definition. The
function header begins with the key word def, followed by the name of the function, followed by a set of
parentheses, followed by a colon.
Beginning at the next line is a set of statements known as a block. A block is simply a set of statements
that belong together as a group. These statements are performed any time the function is executed.
Notice in the general format that all of the statements in the block are indented.
When a function is called, the interpreter jumps to that function and executes its block.
Then, when the end of the block is reached, the interpreter jumps back to the part of the program that
called the function, and the program resumes execution at that point. When this happens, we say that
the function returns.
In fact, it is common for a program to have a main function that is called when the program starts. The
main function then calls other functions in the program as they are needed.
Indentation in Python
In Python, each line in a block must be indented. As shown in Figure below, the last indented line after a
function header is the last line in the function’s block.
When you indent the lines in a block, make sure each line begins with the same number of spaces.
Otherwise, an error will occur.
When a function is executing, what happens when the
end of the function’s block is reached?
Why must you indent the statements in a block?
Questions
69
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
Local Variables
Anytime you assign a value to a variable inside a function, you create a local variable.
A local variable belongs to the function in which it is created, and only statements inside that function
can access the variable.
An error occurs if a statement
in one function tries to access
a local variable that belongs to
another function.
A variable’s scope is the part of
a program in which the variable
may be accessed.
If you want a function to receive arguments when it is called, you must equip the function with one or
more parameter variables. A parameter variable, often simply called a parameter, is a special variable
that is assigned the value of an argument when a function is called.
A variable’s scope is the part of a program in which the variable may be accessed. A parameter variable’s
scope is the function in which the parameter is used.
All of the statements inside the function can access the parameter variable, but no statement outside the
function can access it.
حيدر احمد عبدالمحسن.د 72
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
Program below shows a function named show_sum, that accepts two arguments. The function adds the
two arguments and displays their sum.
The arguments, 12 and 45, are passed by position to the parameter variables in the function.
74
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
A global constant is a global name that references a value that cannot be changed.
A value-returning function is a special type of function. It is a group of statements that perform a specific
task. When you want to execute the function, you call it.
When a value-returning function finishes, however, it returns a value back to the part of the program
that called it. The value that is returned from a function can be used like any other value.
Python, as well as most programming languages, comes with a standard library of functions that have
already been written for you.
These functions, known as library functions, make a programmer’s job easier because they perform many
of the tasks that programmers commonly need to perform.
Some of Python’s library functions are built into the Python interpreter. This is the case with the print,
input, range, and other functions about which you have already learned.
Many of the functions in the standard library, however, are stored in files that are known as modules.
These modules help organize the standard library functions. For example, functions for performing math
operations are stored together in a module, functions for working with files are stored together in
another module, and so on.
In order to call a function that is stored in a module, you have to write an import statement at the top of
your program. An import statement tells the interpreter the name of the module that contains the
function.
To use these functions, you first need to write import random statement at the top of your program.
The first random-number generating function that we will discuss is named randint.
79
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
The value of the expression that follows the key word return will be sent back to the part of the program
that called the function. This can be any value, variable, or expression that has a value.
Python allows you to write Boolean functions, which return either True or False. For example, suppose
you are designing a program that will ask the user to enter a number, then determine whether that
number is even or odd.
You can specify multiple expressions separated by commas after the return statement, as shown in this
general format:
As an example, look at the following definition for a function named get_name. The function prompts the
user to enter his or her first and last names. These names are stored in two local variables: first and last.
The return statement returns both variables.
a. What is the name of the function?
b. What does the function do?
Questions
c. Given the function definition, what will the following
statement display? print(do_something(10))
85
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
All of the functions listed in the previous Table return a float value, except the ceil and floor functions,
which return int values.
For example, one of the functions is named sqrt. The sqrt function accepts an argument and returns the
square root of the argument.
The math module defines two variables, pi and e, which are assigned mathematical values for pi and e.
You can use these variables in equations that require their values. For example, the following statement,
which calculates the area of a circle, uses pi.
get the square root of 100 and assigns it to a variable.
90
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
Sequences
A sequence is an object that contains multiple items of data. The items that are in a sequence are stored
one after the other.
Python provides various ways to perform operations on the items that are stored in a sequence. You can
perform operations on a sequence to examine and manipulate the items stored in it.
There are several different types of sequence objects in Python. In this course, we will look at two of the
fundamental sequence types: lists and tuples.
Both lists and tuples are sequences that can hold various types of data.
The difference between lists and tuples is simple: a list is mutable, which means that a program can
change its contents, but a tuple is immutable, which means that once it is created, its contents cannot be
changed.
We will explore some of the operations that you may perform on these sequences.
حيدر احمد عبدالمحسن.د 92
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
Introduction to Lists
A list is an object that contains multiple data items. Each item that is stored in a list is called an element.
The items that are enclosed in brackets and separated by commas are the list elements.
You can use the print function to display an entire list, as shown here:
Python also has a built-in list() function that can convert certain types of objects to lists.
Here is an example:
Recall from Week 5 that when you pass three arguments to the range function, the first argument is the
starting value, the second argument is the ending limit, and the third argument is the step value.
This statement will assign the list [1, 3, 5, 7, 9] to the numbers variable.
حيدر احمد عبدالمحسن.د 93
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
The repetition operator makes multiple copies of a list and joins them all together.
You can iterate over a list with the for loop. Also, Python has a built-in function named len that returns
the length of a sequence, such as a list.
Indexing
Another way that you can access the individual elements in a list is with an index. Each element in a list
has an index that specifies its position in the list.
Indexing starts at 0, so the index of the first element is 0, the index of the second element is 1, and so
forth. The index of the last element in a list is 1 less than the number of elements in the list.
The indexes of the elements in this list are 0, 1, 2, and 3. We can print the elements of the list with the
following statement:
You can also use negative indexes with lists to identify element positions relative to the end of the list.
The index −1 identifies the last element in a list, −2 identifies the next to last element, and so forth.
To concatenate means to join two things together. You can use the + operator to concatenate two lists.
Below is an example:
You can also use the += augmented assignment operator to concatenate one list to another. Below is an
example:
4
Questions
5
97
حيدر احمد عبدالمحسن.د
What will the following code display?
2 Questions
98
حيدر احمد عبدالمحسن.د
الجامعة التقنية الجنوبية
المعهد التقني القرنـــــة
قسم تقنيات انظمة الحاسوب
List Slicing
You have seen how indexing allows you to select a specific element in a sequence.
Sometimes you want to select more than one element from a sequence. In Python, you can write
expressions that select subsections of a sequence, known as slices.
A slice is a span of items that are taken from a sequence. When you take a slice from a list, you get a
span of elements from within the list.
In the format, start is the index of the first element in the slice, and end is the index marking the end of
the slice. The expression returns a list containing a copy of the elements from start up to (but not
including) end.
List Slicing
If you leave out the start index in a slicing expression, Python uses 0 as the starting index.
If you leave out the end index in a slicing expression, Python uses the length of the list as the end index.
If you leave out both the start and end index in a slicing expression, you get a copy of the entire list.
List Slicing
The slicing examples we have seen so far get slices of consecutive elements from lists.
Slicing expressions can also have step value, which can cause elements to be skipped in the list.
The following interactive mode session shows an example of a slicing expression with a step value:
You can also use negative numbers as indexes in slicing expressions to reference positions relative to the
end of the list. Python adds a negative index to the length of a list to get the position referenced by that
index.
Questions
3
103
حيدر احمد عبدالمحسن.د
قسم تقنيات انظمة الحاسوب البرمجة بلغة بايثون المعهد التقني القرنة
In the general format, item is the item for which you are searching, and list is a list. The expression
returns true if item is found in the list, or false otherwise.
108
حيدر احمد عبدالمحسن.د