Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python

Uploaded by

nouri ahwaas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python

Uploaded by

nouri ahwaas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

‫الجامعة التقنية الجنوبية‬

‫المعهد التقني القرنـــــة‬


‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)1‬‬


‫‪1‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 A program is a set of instructions that a computer follows to perform a task.

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

 Python is also a powerful language, popular with professional software developers.


‫ حيدر احمد عبدالمحسن‬.‫د‬ 2
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Compilers and Interpreters


 Because the CPU understands only machine language instructions, programs that are written in a high-
level language must be translated into machine language.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 3


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 4


 A(n) __________ program translates a high-level language
program into a separate machine language program.
❑ compiler
❑ interpreter
 Machine language is the only language that a CPU
understands.
❑ True


❑ 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
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Input, Processing, and output


 Computer programs typically perform the following three-step process:

 1. Input is received.

 2. Some process is performed on the input.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 6


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Displaying Output with the print Function


 A function is a piece of prewritten code that performs an operation. Python has numerous built-in
functions that perform various operations.

 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
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪Displaying Output with the print Function‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪8‬‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 9


 Write a statement that displays your name.
 Write a statement that displays the following text:

 Write a statement that displays the following text: Questions

10
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)2‬‬


‫‪11‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 A variable is a name that represents a value in the computer’s 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.

 An assignment statement is written in the following general format:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 12


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Variable Naming Rules


 Although you are allowed to make up your own names for variables, you must follow these rules:

 You cannot use one of Python’s key words as a variable name.

 A variable name cannot contain spaces.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 13


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Displaying Multiple Items with the print Function


 Python allows us to display multiple items with one call to the print function. We simply have to separate
the items with commas as shown in below program.

 Variables are called “variable” because they can reference different values while a program is running.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 14


 What is a variable?

 Which of the following are illegal variable names in


Python, and why?

 Is the variable name Sales the same as sales? Why ?


Questions
 Is the following assignment statement valid or invalid? If
it is invalid, why? 72 = amount

 What will the following code display?

15
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Numeric Data Types and Literals


 Because different types of numbers are stored and manipulated in different ways, Python uses data types
to categorize values in memory. When an integer is stored in memory, it is classified as an int, and when
a real number is stored in memory, it is classified as a float.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 16


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Storing Strings with the str Data Type


 In addition to the int and float data types, Python also has a data type named str, which is used for
storing strings in memory.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 17


 After the following assignment statements execute, what
is the Python data type of the values

Questions
 What will be displayed by the following program?

18
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Reading Input from the Keyboard


 Most of the programs that you will write will need to read input and then perform an operation on that
input. In the course, we use Python’s built-in input function to read input from the keyboard.

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

 When the above statement executes, the following things happen:

 The string 'What is your name? ' is displayed on the screen.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 19


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Reading Input from the Keyboard


 The program below shows a complete program that uses the input function to read two strings as input
from the keyboard.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 20


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Reading Numbers with the input Function


 The input function always returns the user’s input as a string, even if the user enters numeric data.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 21


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Reading Numbers with the input Function


 The program below a complete program that uses the input function to read a string, an int, and a float,
as input from the keyboard.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 22


 You need the user of a program to enter a customer’s last
name. Write a statement that prompts the user to enter
this data and assigns the input to a variable.

 You need the user of a program to enter the amount of


sales for the week. Write a statement that prompts the
Questions
user to enter this data and assigns the input to a
variable.

23
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)3‬‬


‫‪24‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 25


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 26


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Floating-Point and Integer Division


 Notice that Python has two different division operators. The / operator performs floating-point division,
and the // operator performs integer division.

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

 The // operator works like this:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 27


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 The precedence of the math operators, from highest to lowest, are:

 Exponentiation: **

 Multiplication, division, and remainder: * / // %

 Addition and subtraction: + −

 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
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The Augmented Assignment Operators


 Quite often, programs have assignment statements in which the variable that is on the left side of the =
operator also appears on the right side of the = operator. Here are examples: x = x + 1, y = y – 5.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 29


 Complete the following table by writing the value of each
expression in the Value column:

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
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Breaking Long Statements into Multiple Lines


 Python allows you to break too long statement into multiple lines by using the line continuation
character, which is a backslash (\).

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 31


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Suppressing the print Function’s Ending Newline


 The print function normally displays a line of output. For example, the following three statements will
produce three lines of output:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 32


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 33


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 34


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 35


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 You can also use the format function to format integers.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 36


 How do you suppress the print function’s ending newline?

 How can you change the character that is automatically


displayed between multiple items that are passed to the
print function?

 What is the '\n' escape character?

 What does the + operator do when it is used with two


strings?
Questions
 What does the statement print(format(65.4321, '.2f'))
display?

 What does the statement print(format(987654.129, ',.2f'))


display?

37
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)4‬‬


‫‪38‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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)

 In a decision structure’s simplest form, a specific action is performed


only if a certain condition exists. If the condition does not exist, the
action is not performed.

 Programmers call the type of decision structure shown in the Figure


a single alternative decision structure. This is because it provides only
one alternative path of execution.

 If the condition in the diamond symbol is true, we take the alternative


path. Otherwise, we exit the structure

‫ حيدر احمد عبدالمحسن‬.‫د‬ 39


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Boolean Expressions and Relational Operators


 Tables below show the relational operators that are available in Python and examples of several Boolean
expressions that compare the variables x and y.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 41


 What is a control structure?

 What is a decision structure?

 What is a single alternative decision structure?

 What is a Boolean expression?

Questions
 What types of relationships between values can you test
with relational operators?

 Write an if statement that assigns 0 to x if y is equal to


20.

 Write an if statement that assigns 0.2 to commissionRate


if sales is greater than or equal to 10000.

42
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The if-else Statement


 Now, we will look at the dual alternative decision structure, which has two possible paths of execution—
one path is taken if a condition is true, and the other path is taken if the condition is false.

 In code, we write a dual alternative decision structure as an if-else statement. Here is the general format
of the if-else statement:

‫ حيدر احمد عبدالمحسن‬.‫د‬ 43


 How does a dual alternative decision structure work?

 What statement do you use in Python to write a dual


alternative decision structure?

 When you write an if-else statement, under what Questions


circumstances do the statements that appear after the
else clause execute ?

44
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Nested Decision Structures and the if-elif-else Statement


 To test more than one condition, a decision structure can be nested inside another decision structure.

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

 When the statement executes, condition_1 is tested.


If condition_1 is true, the block of statements that
immediately follow is executed, up to the elif clause.
The rest of the structure is ignored.

 If condition_1 is false, however, the program jumps to


the very next elif clause and tests condition_2.

 This process continues until a condition is found to be

true, or no more elif clauses are left.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 45


 Convert the following code to an if-elif-else statement:

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 47


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 48


 Assume the variables a = 2, b = 4, and c = 6. Circle T or F
for each of the following conditions to indicate whether
its value is true or false.

 Write an if statement that displays the message “The Questions


number is valid” if the value referenced by speed is
within the range 0 through 200.

 Write an if statement that displays the message “The


number is not valid” if the value referenced by speed is
outside the range 0 through 200.
49
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)5‬‬


‫‪50‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Introduction to Repetition Structures


 Programmers commonly have to write code that performs the same task over and over.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 51


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The while Loop: A Condition-Controlled Loop


 The while loop gets its name from the way it works: while a condition is true, do some task.

 The loop has two parts:

 (1) a condition that is tested for a true or false value.

 (2) a statement or set of statements that is repeated as long as the condition is true.

 Here is the general format of the while loop in Python:

 When the while loop executes, the condition is tested. If the

condition is true, the statements that appear in the block

following the while clause are executed, and the loop starts

over. If the condition is false, the program exits the loop.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 52


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The while Loop: A Condition-Controlled Loop

 This program shows how we use a while loop


to write the commission calculating program

‫ حيدر احمد عبدالمحسن‬.‫د‬ 53


 What is a loop iteration?

 Does the while loop test its condition before or after it


performs an iteration?

 How many times will 'Hello World' be printed in the


following program?
Questions

54
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The for Loop: A Count-Controlled Loop


 In Python, the for statement is designed to work with a sequence of data items. When the statement
executes, it iterates once for each item in the sequence. Here is the general format:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 55


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪The for Loop: A Count-Controlled Loop‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪56‬‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Using the range Function with the for Loop


 Python provides a built-in function named range that simplifies the process of writing a count-controlled
for loop.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 57


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪Using the range Function with the for Loop‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪58‬‬


 Rewrite the following code so it calls the range function
instead of using the list

 What will the following code display?

2
Questions
3

59
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)6‬‬


‫‪60‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 61


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Benefits of Modularizing a Program with Functions


 Simpler Code

 Code Reuse

 Better Testing

 Faster Development

 Easier Facilitation of Teamwork

‫ حيدر احمد عبدالمحسن‬.‫د‬ 62


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Void Functions and Value-Returning Functions


 We will learn to write two types of functions: void functions and value returning functions.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 63


 What is a function?
 What is meant by the phrase “divide and conquer”?
 How do functions help you reuse code in a program?
 How can functions make the development of multiple
programs faster? Questions
 How can functions make it easier for programs to be
developed by teams of programmers?

64
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Defining and Calling a Void Function


 To create a function, you write its definition. Here is the general format of a function definition in
Python:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 65


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Defining and Calling a Void Function


 A function definition specifies what a function does, but it does not cause the function to execute. To
execute a function, you must call it. This is how we would call the message function:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 66


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Defining and Calling a Void Function


 The previous program has only one function, but it is possible to define many functions in a program.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 67


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 Blank lines that appear in a block are ignored.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 68


 A function definition has what two parts?
 What does the phrase “calling a function” mean?


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
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)7‬‬


‫‪70‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 71


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Passing Arguments to Functions


 Sometimes it is useful not only to call a function, but also to send one or more pieces of data into the
function. Pieces of data that are sent into a function are known as arguments.

 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
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Passing Multiple Arguments


 Often it’s useful to write functions that can accept multiple arguments.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 73


 What is a local variable? How is access to a local variable
restricted?

 What is a variable’s scope?

 Is it permissible for a local variable in one function to


have the same name as a local variable in a different
function?
Questions
 What are the pieces of data that are passed into a
function called?

 What are the variables that receive pieces of data in a


function called?

74
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Global Variables and Global Constants


 When a variable is created by an assignment statement that is written outside all the functions in a
program file, the variable is global. A global variable can be accessed by any statement in the program
file, including the statements in any function.

 A global constant is a global name that references a value that cannot be changed.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 75


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Introduction to Value-Returning Functions


 You have learned about void functions. A void function is a group of statements that exist within a
program for the purpose of performing a specific task. When the function is finished, control of the
program returns to the statement appearing immediately after the function call.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 76


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Standard Library Functions and the import Statement


 In fact, you have already used several of Python’s library functions. Some of the functions that you have
used are print, input, and range. Python has many other library functions.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 77


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Generating Random Numbers


 Random numbers are useful for lots of different programming tasks. Python provides several library
functions for working with random numbers. These functions are stored in a module named random.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 78


 What is the scope of a global variable?
 How does a value-returning function differ from the void
functions?
 What is a library function?
 Why are library functions like “black boxes”?
 What does the following statement do?
Questions
 What does the following statement do?

79
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)8‬‬


‫‪80‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Writing Your Own Value-Returning Functions


 You write a value-returning function in the same way that you write a void function, with one exception:
a value-returning function must have a return statement.

 Here is the general format of a value-returning function definition:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 81


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪Writing Your Own Value-Returning Functions‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪82‬‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Returning Strings and Boolean Values


 So far, you’ve seen examples of functions that return numbers. You can also write functions that return
strings. For example, the following function prompts the user to enter his or her name, then returns the
string that the user entered.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 83


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Returning Multiple Values


 The examples of value-returning functions that we have looked at so far return a single value. In Python,
however, you are not limited to returning only one value.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 84


 What is the purpose of the return statement in a
function?
 Look at the following function definition:


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
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The math Module


 The math module in the Python standard library contains several functions that are useful for performing
mathematical operations. Table below lists many of the functions in the math module.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 86


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪The math Module‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪87‬‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

The math Module


 These functions typically accept one or more values as arguments, perform a mathematical operation
using the arguments, and return the result.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 88


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪The math Module‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪89‬‬


 What import statement do you need to write in a
program that uses the math module?

 Write a statement that uses a math module function to


get the square root of 100 and assigns it to a variable.

Write a statement that uses a math module function to


Questions
convert 45 degrees to radians and assigns the value to a
variable.

90
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)9‬‬


‫‪91‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 Here is a statement that creates a list of integers:

 The items that are enclosed in brackets and separated by commas are the list elements.

 A list can hold items of different types, as shown here:

 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 and len Function


 You learned in Week 3 that the * symbol multiplies two numbers. However, when the operand on the left
side of the * symbol is a sequence (such as a list) and the operand on the right side is an integer, it
becomes the repetition operator.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 94


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 For example, the following statement creates a list with 4 elements:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 95


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Changing Lists and Concatenating Lists


 Lists in Python are mutable, which means their elements can be changed. Consequently, an expression in
the form list[index] can appear on the left side of an assignment operator.

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 96


 What will the following code display?

4
Questions
5

 How do you find the number of elements in a list?

97
‫ حيدر احمد عبدالمحسن‬.‫د‬
 What will the following code display?

2 Questions

98
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫الجامعة التقنية الجنوبية‬
‫المعهد التقني القرنـــــة‬
‫قسم تقنيات انظمة الحاسوب‬

‫البرمجة بلغة بايثون‬


‫‪Python Programming‬‬

‫محاضرة رقم (‪)10‬‬


‫‪99‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

 To get a slice of a list, you write an expression in the following format:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 100


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 101


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

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.

‫ حيدر احمد عبدالمحسن‬.‫د‬ 102


 What will the following code display?

Questions
3

103
‫ حيدر احمد عبدالمحسن‬.‫د‬
‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

Finding Items in Lists with the in Operator


 In Python, you can use the in operator to determine whether an item is contained in a list. Here is the
format of an expression written with the in operator to search for an item in a list:

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

‫ حيدر احمد عبدالمحسن‬.‫د‬ 104


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

List Methods and Useful Built-in Functions


 Lists have numerous
methods that allow
you to add elements,
remove elements,
change the ordering
of elements, and so
forth. We will look at
a few of these
methods, which are
listed in next Table .

‫ حيدر احمد عبدالمحسن‬.‫د‬ 105


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪The insert Method‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪106‬‬


‫قسم تقنيات انظمة الحاسوب‬ ‫البرمجة بلغة بايثون‬ ‫المعهد التقني القرنة‬

‫‪The index Method‬‬

‫د‪ .‬حيدر احمد عبدالمحسن‬ ‫‪107‬‬


 What will the following code display?

 Assume the following statement appears in a program:

Which of the following statements would you use to add the


Questions
string ‘Wendy’ to the list at index 0? Why would you select
this statement instead of the other?

108
‫ حيدر احمد عبدالمحسن‬.‫د‬

You might also like