0% found this document useful (0 votes)
13 views

Week 2- Introduction to Python #1

Uploaded by

adamchicken9.9.9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Week 2- Introduction to Python #1

Uploaded by

adamchicken9.9.9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

INTRODUCTION TO PYTHON PROGRAMMING

American University of Sharjah

Prepared by Dr. Jamal A. Abdalla, CVE


Revised by Dr. Tamer Shanableh, CSE
Computer Software
2

Operating System - Provides an interface with the user


Unix, Windows, Linux, iOS,..
Software Applications
Word processors (Microsoft Word, ...)
Spreadsheet programs (Excel, ...)
Mathematical computation tools (MATLAB, MathCAD,...)
Computer Languages
Machine language
Assembly language
High level Structured languages (C, Fortran, Basic)
High level Object-Oriented languages (C++, Java, Python)
Internet Browsers
Chrome, Edge, Firefox, ….
Apps
WhatsApp, Instagram, Twitter, …..
Machine Languages
3

Machine Languages (sequence of 1s and 0s)


It is the only language understood directly by computers
Defined by computer’s hardware design
■ Machine-dependent (different languages for Windows, Linus,
Mac,…)
■ Languages specific to particular computers

Difficult to understand for human readers


■ Streams of numbers, ultimately reduced to 0s and 1s (Binary
code)
■ Instruct most elementary of operations (ex. copy a number
from memory to the CPU)
■ Tedious and error-prone
■ Lead to Assembly Languages
Assembly Languages
4

Assembly Languages
English-like abbreviations
■ Represent elementary operations of computer

Translated to machine language before running them


■ Assemblers convert to Assembly language into machine language
■ High-speed conversion

Clearer to human readers than machine language


■ Still tedious to use
■ Many instructions for simple tasks
■ Lead to High-Level Languages

Example
Example Assembly line to copy from Memory@42 to CPU@eax location: mov eax, 42
Same code in machine language: 10111000 00101010 00000000 00000000 00000000
High Level Languages
5

High-Level Languages
Single statements accomplish substantial tasks
(like printing out a variable of type dictionary)

Translated to machine language


■ Compilers convert to assembly then to machine language
■ Conversion takes time

High-level languages has Code Instructions


understandable to humans
■ Looks mostly like everyday English (ex. print([1,2,3,4])
■ Contain common mathematical notation (ex. rst = x / y)
■ Used in development environment (ex. colab)
Compiled versus Interpreted Languages

Compilation vs. Interpretation:


A compiler takes the entire source code of a program and
translates it into machine code all at once.
This machine code is saved as an executable file, and the program
can be run multiple times without recompilation. (Example C++)

An interpreter, on the other hand, processes the source code line


by line or statement by statement at runtime. It translates each
line or statement into machine code and immediately executes it.
(Example Python)
Object-Oriented Programming
7

Object-Oriented Programming (OOP)


Modeled after items in the real world (can create new
variable types like Students, Course,…variables of these
types are called objects)

Uses objects as a reusable software components (we


use Lists without implementing them ourselves)

In OOP, Programs are more understandable by humans


Therefore, programs are easier to correct, modify and
maintain
C, C++, Java, Python
8

C
Developed by Dennis Ritchie at Bell Laboratory (1972)
Gained recognition as language of UNIX
It is a widely used language for developing operating systems
Was used to create Python
Lead to the development of C++

C++
Developed by Bjarne Stroustrup at Bell Laboratory (1980s)
Extension of C with elements from a Simulation programming language (Simula 67)
It is a structured and object-oriented programming language

Java
It is a product of Sun Microsystems corporate research project (1991)
Based on C and C++, but it is OS-independent, so the same code runs on windows,
mac and linux
Intended for intelligent consumer-electronic devices
Gained popularity with the emergence of WWW
Widely used for enhancing functionality of WWW servers
Python
9

Python is a popular structured and object-oriented programming


language. It was created by Guido van Rossum and released in 1991.

It is used for:
• Machine Learning and Data Science
• Software development in general
• Web development (server-side) and web applications
• Performing complex mathematics
• Handling big data
• Rapid prototyping and for production-ready software development
• System scripting (Example: Write code to Automate moving,
copying, renaming, and deleting files and directories).
Why Python?
10

Python has many features that are not available in a single language

• Works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).


• Has a simple syntax that is readable and like the English language.
• Has a compact syntax that allows developers to write shorter programs.
• Runs on an interpreter system for immediate execution and quick
prototyping.
• It is a structured and an object-oriented programming language.
• It is the widely used programming language for Data Science and
Machine Learning
Google Colab Notebook
11

What is Colab?

Colab, or "Colaboratory", allows the user to write


and execute Python programs in the browser, with
zero configuration required.

It gives the user access to GPUs and facilitates


easy sharing.
Google Colab Notebook
12

Cells
A notebook is a list of cells. Cells contain either explanatory text or executable code and its output.

Code cells
Command for the Code cell:
• Type Cmd/Ctrl+Enter to run the cell in place;
• Type Shift+Enter to run the cell and move focus to the next cell (adding one if none exists); or
• Type Alt+Enter to run the cell and insert a new code cell immediately below it.
There are additional options for running some or all cells in the Runtime menu.

Text cells
This is a text cell. You can double-click to edit this cell. Text cells use markdown syntax.

Adding and moving cells


You can add new cells by using the + CODE and +TEXT buttons that show when you hover
between cells.
You can move a cell by selecting it and clicking Cell Up or Cell Down in the top toolbar.
13
The First Program
14

Use Colab to write and execute the following


expressions/statement/programs

print(‘Hello World!’ ) #Print your 1st Python String


counter = 100 # Creates an integer variable
miles = 1000.0 # Creates a floating point variable
name = "Zara Ali" # Creates a string variable
print (counter) Output:
Hello World!
print (miles) 100
1000.0
print (name) Zara Ali
The print() function

#Use single quotation for printing text


print('Welcome to NGN112!')

#may enclose a string in double quotes (")


print("Welcome to NGN112!")
output: Welcome to NGN112!

#Printing a List of Items (comma-separated):


print('Welcome', 'to', 'NGN112!')
output: Welcome to NGN112!

#Printing the Value of an Expression (do not use quotations for expression):
print('Sum = ', 1 + 2)
output: Sum = 3
Variables, Data types, Input and Output
16

Python supports five basic data types and five compound data types.
Each data type has its own operations.

Basic Data Types


Integer (int)
Float (float)
Complex (complex)
Boolean (bool)
String (str)

Compound data Types


List (list)
Tuple (tuple)
Set (set)
Dictionary (dict)
Range (range)
Data Types Description and Examples
17
Python Operations
18

❑ Arithmetic operators (ex. x + y)

❑ Assignment operators (ex. x = y)


❑ Comparison operators (ex. x > y)
❑ Logical operators (ex. x and y)
❑ Identity operators (ex. x is y)
❑ Membership operators (ex. x in y)
❑ Bitwise operators (ex. x & y)
Variable Names Rules
19

• Variable names can be as long as you like.


• They can contain both letters and numbers (ex. fall23).
• They can’t begin with a number. (ex 23fall is not allowed)
• Uppercase letters are not allowed. (ex. Fall23 is not allowed).
• Keywords cannot be used as variable names. (ex. print)
• The underscore character, _, can appear in a variable name. (ex fall_23)

If you give a variable an illegal name, you get a syntax error:

>>> 1sum = ‘sum of grades of section 1‘ #do not start with a number
SyntaxError: invalid syntax

>>> more@ = 1000000 # @ is not allowed


SyntaxError: invalid syntax

>>> class = 'Advanced Theoretical stuff‘ #class is a keyword


SyntaxError: invalid syntax
Assignments
20

An assignment statement creates a new variable and gives it a value:

>>> message = 'And now for something completely different'


>>> n = 17
>>> pi = 3.141592653589793

This example makes three assignments.


The first assigns a string (str) to a new variable named message.
The second gives the integer (int) 17 to n.
The third assigns a float value which is the (approximate) value of π to pi.

Ref. Allen B. Downey, Think Python


Expression and Statement
21

An expression is a combination of values, variables, and operators. A value all by


itself is considered an expression, and so is a variable, so the following are all
legal expressions:

>>> n = 17 # assignment operator


>>> n + 25 # arithmetic operator
>>> 42 # a single value
>>> n # a variable

When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression. In this example, n has the value
17 and

n + 25 has the value 42.


Expression and Statement, cont.
22

A statement is a unit of code that has an effect, like creating a variable


or displaying a value.
>>> n = 17
>>> print(n)

The first line is an assignment statement that gives a value to n.


The second line is a print statement that displays the value of n.

When you type a statement, the interpreter executes it, which means
that it does whatever the statement says. In general, statements don’t
have values.
int type and its Operations
23

Type int represents integers (whole number) positive


or negative
Example: x=–100, x=–50, x=0, x=1, x=1000, …(no commas or
periods)
Integer numbers (literals) look like this:
1, 82, 256 (no commas or periods)
Integer operations: +, –, *, //, %, **, unary –
x+y
x-y
x*y
x//y # divide x/y and round down the answer
x**y #to the power of
-x
int type and its Operations
24

Operations on int values must yield an int

Integer Division (//): 1 // 2 rounds result down to 0 and 7 // 2 is 3


Remainder (%): (% companion operation to //)
5 % 2 evaluates to 1, remainder when dividing 5 by 2
8 % 3 evaluates to 2 and 10 % 5 evaluates to 0

Operator / is not an int operation in Python 3, it generates fractions


Operator examples - 1

x=12345

print(x%10) #reminder of division by 10 = 5


print(x%100) #reminder of division by 100 = 45
print(x%1000) #reminder of division by 100 = 345

print(x / 10) # regular division = 1234.5


print(x // 10) # floor division = 1234

print(x / 100) # regular division = 123.45


print(x // 100) # floor division = 123
Operator examples - 2

#access one digit at a time


x=12345
print(x%10) #reminder of division by 10 = 5
x = x // 10 #12345 // 10 = 1234 (floor division)
print(x%10) # = 4
x = x // 10 # = 123
print(x%10) # = 3
x = x // 10 # = 12
print(x%10) # = 2
x = x // 10 # = 1
print(x%10) # = 1
#Find if a number is odd or even
x = 101
if x%2==0:
print('x = ', x, ' is even')
else:
print('x = ', x, ' is odd')
float type and its Operations
27

Type float (floating point) represents real numbers

Values: distinguished from integers by decimal points


• In Python a number with a “.” is a float literal (e.g. 12.0)
• Without a decimal a number is an int literal (e.g. 12)

Operations: +, –, *, /,**, unary –


• Notice that float has a different division operator
• Example: 5.0/2.0 evaluates to 2.5
• Exponent notation which is used for large (or small) values
24.3e5 is 24.3 *105 or 2430000
48.62e–3 is 48.62*10–3 or 0.04862
Arithmetic Operations for int and float
Arithmetic operators are used with numeric values to perform common mathematical operations
28

Operator Name Example

Addition x+y
+
- Subtraction x-y

Multiplication x*y
*
Division x/y
/
Modulus x%y
%
** Exponentiation x ** y

// Floor division
(a.k.a. int division)
x // y
Precedence of Arithmetic Operations
29

•()
• Exponentiation: **
• Unary operators: + – # ex. -x or +x
• Binary arithmetic: * / %
• Binary arithmetic: + – # ex. x-y
• Comparisons: < > <= >=
• Equality relations: == != # (x==y) means is x equal to y
• Logical not # found=false | ex. !found means NOT found
• Logical and # found=true and first=false | ex . (found and first) is false
• Logical or # found=true and first=false | ex . (found or first) is true
• Precedence goes downwards
• The operations in the same have the same precedence, left first
Example: 6/2*3 is (6/2)*3 Example:
Example: 4+6*5 = 4+(6*5) = 34 3*(2+4) =
3*2 + 4 =
Example of Arithmetic precedence-1
30

Step 1.
y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10 (Leftmost multiplication)

Step 2.
y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50 (Leftmost multiplication)

Step 3.
y = 50 + 3 * 5 + 7;
3 * 5 is 15 (Multiplication before addition)

Step 4.
y = 50 + 15 + 7;
50 + 15 is 65 (Leftmost addition)

Step 5.
y = 65 + 7;
65 + 7 is 72 (Last addition)

Step 6. y = 72; (Last operation—place 72 into y)


Example of Arithmetic precedence-2
31

What is the value of this expression? Precedence:

•()
rst = 2 * 32 + 49 % 10 • Exponentiation: **
• Unary operators: + –
• Binary arithmetic: * / %
rst = 2 * (9) + 49 % 10 • Binary arithmetic: + –
• Comparisons: < > <= >=
• Equality relations: == !=
rst = 2 * 9 + 49 % 10 • Logical not
• Logical and
• Logical or
rst = (18) + 49 % 10

rst = 18 + (9) = 27

Write it in Python and evaluate it to verify your answer


bool type and its Operations
32

Type boolean or bool represents logical statements


Values: True, False
• Boolean literals are just True and False (have to be capitalized)
Operations: logical operators: not, and, or
• not b: True if b is false and False if b is true
• b and c: True if both b and c are true; False otherwise
• b or c: True if b is true or c is true; False otherwise
• Often come from comparing int or float values (ex. (x>y) )
Comparison operators: i < j, i <= j, i >= j, i > j
Equality/inequality operators: i == j, i != j
Important note:
x=y is called assignment
x==y is called equality, you are asking if they are equal
bool type and its Operations
33

Logical operators are used to combine conditional statements

Operator Description Example


and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of x < 5 or x < 4
the statements is true
not Reverse the result, not(x < 5 and x < 10)
returns False if the
result is true and
returns True if the
result is false
Summary of Logical Operators (and, or, not)
34

A B A and B
True True True
True False False
False True False
False False False
A B A or B
True True True
True False True
False True True
False False False

A not A
True False
False True
bool type Equality and Comparison Operators
35

Equality and comparison operators are used to compare two values

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Evaluate Boolean expressions

Precedence:
rst = 22>-1 and 10!=(-10) or not 5<=0
rst = (22>-1) and 10!=-10 or not (5<=0) •()
• Exponentiation: **
rst = (True) and 10!=-10 or not (False) • Unary operators: + –
• Binary arithmetic: * / %
rst = True and (10!=-10) or not False • Binary arithmetic: + –
rst = True and (True) or not False • Comparisons: < > <= >=
• Equality relations: == !=
rst = True and True or (not False) • Logical not
• Logical and
rst = True and True or (True) • Logical or
rst = (True and True) or True
rst = True or True
rst = True

Try it in Python code as well


str type and its Operations
37

Type String or str represents text


Values: any sequence of characters
Operation(s): + (catenation, or concatenation) ex. str3 = str1+str2
• String literal: sequence of characters in quotes

Double quotes: str = " abcex3$g<&" or str = "Hello World!"


Single quotes: str = 'Hello World! '

• Operations: + concatenation can only apply to strings.

'ab' + 'cd' evaluates to 'abcd'


'ab' + 2 produces an error (cannot contact a string with a numeric value)
str type and its Operations
38

String content are indexed, the first character has index [0], the second character
has index [1], …….we use [ ] to access a string at a given index

var1 = 'Hello World!'


var2 = "Python Programming"

print ("var1[0]: ", var1[0]) # character at index 0


print ("var2[1:5]: ", var2[1:5]) # range of characters from index 1 to (5-1)

When the above code is executed, it produces the following result:

var1[0]: H
var2[1:5]: ytho
str type and its Operations
39

Exercise:

var1 = 'Hello World!'


print(“Updated String :-”, var1[:6] + “Python”) #[:6] is the same as [0:6]

When the above code is executed, What is the output ?

Updated String :- Hello Python


Types conversion and casting
40

To find the type of a variable use the type function:


x = 1.5
print('Type of x is:’, type(x))

Result: Type of x is: <class 'float'>

int(15.3) converts value 15.3 to type integer (value now 15)


float(8) converts value 8 to type float (value now 8.0)
Explicit conversion is also called “casting”
Example: 5/2.0 evaluates to 2.5 (automatically casts 5 to float prior to division)
Example: float(int(12.6)) evaluates to 12.0
The input() function

User Input: # The input function returns a string


name = input('Enter a name: ')
print('The name is: ', name)
Python allows
for users to # The input function returns a string
input values for x = input("Enter a value for x: ") # enter 100
their variables y = input("Enter a value for y: ") # enter 200
# here x and y are treated as strings
That means we # hence the output is x+y is string concatenation
can ask the print ('x + y = ', x+y) # prints 100200
user for input # The input function returns a string | Then cast to int
x = int(input("Enter an int value for x: ")) # enter 100
By default the y = int(input("Enter an int value for y: ")) # enter 200
input() function # here x and y are treated as ints
returns a string # hence the output is x+y is 300
print ('x + y = ', x+y)
However, we
# The input function returns a string | Then cast to float
can cast that to
f1 = float(input("Enter a float value for f1: "))# enter 100.5
int() or f2 = float(input("Enter a float value for f2: "))# enter 200.5
float(),… # here f1 and f2 are treated as floats
# hence the output is f1+f2 is 301
41 print ('f1 + f2 = ', f1+f2)
list type and its Operations
42

q Type list represents a sequence that stores a collection of data


values.
q list is created using square brackets [ ].
q There are many operations for a list:

q List items are ordered, changeable, and duplicate values are


allowed.

q List items are indexed, the first item has index [0], the second
item has index [1], …….

q Example: List1 = [8, 3, 5, 5, 10, 6, 24]


list type and its Operations
43

Accessing Values in Lists

To access values in lists, use the square brackets [ ] for slicing along with
the index or indices to obtain value(s) available at that index or indices.

For example:

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];

print ("list1[0]: ", list1[0])


print ("list2[1:5]: ", list2[1:5]) # from item at index 1 to 5-1

When the above code is executed, it produces the following results:

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
list type and its Operations
Python has a set of built-in methods for manipulation of Lists and their elements.
44

Method (Assume you Description


have a list called L1)
L1.append(value) Adds an element at the end of the list
L1.clear() Removes all the elements from the list
L2=L1.copy() Returns a copy of the list
rst=L1.count(value) Returns the number of elements with the specified value
L1.extend(anotherList) Add the elements of a list (or any iterable), to the end of the current
list
Idx=L1.index(value) Returns the index of the first element with the specified value
L1.insert(index, value) Adds an element at the specified position

value = L1.pop(index) Removes and returns the element at the specified position

L1.remove(value) Removes the first item with the specified value

L1.reverse() Reverses the order of the list

L1.sort() Sorts the list


Examples of list function calls

#extend(list example) #append(value) example


L1 = [1, 2, 3] L1 = [1, 2, 3, 1, 2, 1, 2]
L2 = [4,5,6] x = 100
L1.extend(L2) L1.append(x)
print(L1) print('After adding 100:', L1)

#count(value) example #remove(index) example


L1 = [1, 2, 3, 1, 2, 1, 2] L1.remove(2) #removes @index 2
count = L1.count(2) and does not return the removed
print('2 appeared : ',count,' times') value
print('After removing 2: ',L1)

#index(value) example – first occurrence - L1.sort() #now the list is sorted


L1 = [1, 20, 3, 1, 2, 1, 20] print('After sorting',L1)
loc = L1.index(20)
print('found at index: ', loc) L1.clear() #now list is empty
print('After clear(): ',L1)

#pop(index) example
l = [1,2,3,4]
value = l.pop(1) #removes @index 1 and returns the removed value
print('value: ',value,'at index: ',1,' is returned and removed from list: ',l)
tuple type and its Operations
46

Type tuple represents a collection of variables


tuple is created using parenthesis ( )
(unlike lists which are created using [ ])
Tuple items are ordered, unchangeable, and allow duplicate
values.
Example:
fruit = ("Orange", "banana", "orange")
You can access elements of a tuple by using [] like lists:
Print(fruit[1]) # prints banana
Unchangeable Tuples

Tuples are unchangeable

Tuple individual variables cannot be modified, so this code results in


error:

tuple1[0] = 100

Error: 'tuple' object does not support item assignment


tuple type and its Operations
48

Method (assume you have Description


a tuple called myTuple)

Returns the number of times a specified value


cnt=myTuple.count(value) occurs in a tuple

Searches the tuple for a specified value and


idx=myTuple.index(value) returns the position of where it was found
dict type and its Operations
49

Type dict (dictionary) represents dictionary of variables


(A dictionary associates keys with values)

dict is created using square curl parenthesis { }.

dict items are ordered, changeable, and do not allow duplicate values.

Example:
roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X': 100}
print(roman_numerals['V']) #prints 5

Notice that we always use [] to access elements (in lists, tuples and
dict)
However, In dict type, to access a 'value' you use roman_numerals[key]
not roman_numerals[index]
So to print the key 1 you used roman_numerals['I'] not roman_numerals[0]
dict values can be lists/tuples

dict values can be lists or tuples, like:


#key: student name, value: grade list
grade_book = {
'Ali': [92, 85, 100], Outputs: {'Ali': [92, 85, 100], 'Layla': [83, 95, 79],
'Layla': [83, 95, 79], 'Hassan': [91, 89, 82], 'Huda': [97, 91, 92]}
'Hassan': [91, 89, 82],
'Huda': [97, 91, 92]
}
print(grade_book)
#key: student name, value: grade tuple
grade_book = {
'Ali': (92, 85, 100), Outputs: {'Ali': (92, 85, 100), 'Layla': (83, 95, 79),
'Hassan': (91, 89, 82), 'Huda': (97, 91, 92)}
'Layla': (83, 95, 79),
'Hassan': (91, 89, 82),
'Huda': (97, 91, 92) #access elements by []
print(grade_book['Hassan'])
} Output: (91, 89, 82)
print(grade_book)
dict type and its Operations
51

Method (assume you have a dict called d1) Description

d1.clear() Removes all the elements from the dictionary


d1.copy() Returns a copy of the dictionary | Ex. d2=d1.copy()
fromkeys() Returns a dictionary with the specified keys and value
d1.get(key) Returns the value of the specified key
Ex. value=d1.get(‘Hassan’)

d1.items() Returns a list containing a tuple for each key value pair

d1.keys() Returns a dict-keys containing the dictionary's keys


Ex. dict_keys=d1.keys()

value = d1.pop(key) Removes the element with the specified key


d1.popitem() Removes the last inserted key-value pair
d1.setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
d1.update({key: value}) Updates the dictionary with the specified key-value pairs
Ex. d1.update({‘Hassan’: [100,100,100] }

d1.values() Returns a dict-values of all the values in the dictionary


Ex. dict_values = d1.values()
Dictionary update and insert
grade_book = {
'Ali': [92, 85, 100],
'Layla': [83, 95, 79],
'Hassan': [91, 89, 82],
'Huda': [97, 91, 92]
}
print("Update Hassan's grades...")
grade_book.update( {'Hassan': [100, 99, 99]})
print("Hassan's grades are: ", grade_book['Hassan'])

print() #an empty line


print('If you update a non-existing key then a new record is added...')
grade_book.update( {'Tuffaha': [65, 67, 72]})
print(grade_book)

Update Hassan's grades... Hassan's grades are: [100, 99, 99]

If you update a non-existing key then a new record is added...

{'Ali': [92, 85, 100], 'Layla': [83, 95, 79], 'Hassan': [100, 99, 99],
'Huda': [97, 91, 92], 'Tuffaha': [65, 67, 72]}
set type and its Operations
53

Type set represents a set of variables

set is created using square curl parenthesis { }.

set items are unordered (unindexed), mutable (add or remove


elements), and do not allow duplicate values. The element
values are unchangeable.

Example: x = {"cat", "dog", "horse"}


Set items are unindexed, so print(x[0]) will
generate the error:
TypeError: 'set' object is not subscriptable
set type and its Operations
54 Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
intersection_update() Removes the items in this set that are not present in other, specified
set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_up inserts the symmetric differences from this set and another
date()
union() Return a set containing the union of sets

update() Update the set with another set, or any other iterable
Identity Operators
55

Identity operators are used to compare the objects if they are the same
object with the same memory location

Operator Description Example

is Returns True if both variables are x is y


the same object

is not Returns True if both variables are x is not y


not the same object
Identity Operators: Examples
56

# Create two variables with the same value


x = [1, 2, 3]
y = [1, 2, 3]

# Using the identity operator "is" to compare the variables


print(x is y) # Output: False (x and y are two different objects in memory, yet with the same content)
print(x is not y) # Output: True (x and y are not the same object in memory)

# Create another variable referencing the same object as x (now we have 2 variables referring to the
same list, think of x as a name and z as a nickname, the list now has 2 names)
z=x

# Using the identity operator "is" to compare z with x and y


print(x is z) # Output: True (x and z are the same object in memory)
print(y is z) # Output: False (y and z are different objects in memory)
Membership Operators
57

Operator Description Example


in Returns True if a value is present in a x in y
collection of values, otherwise it returns
False
not in Returns True if a value is NOT present in a x not in y
collection of values, otherwise it returns
False

Collections include lists, tuples, strings, sets, and dictionaries.


Membership Operators
58

# Example with a list


fruits = ['apple', 'banana', 'orange', 'grape']

print('apple' in fruits) # Output: True (since 'apple' is in the list)


print('kiwi' in fruits) # Output: False (since 'kiwi' is not in the list)
print('pear' not in fruits) # Output: True (since 'pear' is not in the list)

# Example with a string


message = "Hello, World!"

print('Hello' in message) # Output: True (since 'Hello' is in the string)


print('Python' in message) # Output: False (since 'Python' is not in the string)
print('World' not in message) # Output: False (since 'World' is in the string)

# Example with dict


grade_book = {
'Ali': [92, 85, 100],
'Layla': [83, 95, 79],
'Hassan': [91, 89, 82],
'Huda': [97, 91, 92]
}
print('Sarah' in grade_book)#Output: False (the key Sarah is not in the dict
Python Keywords
59

Python has 35 keywords (reserved words) that cannot be used as variable


names, function names or identifier names. All the keywords except True, False
and None are in lowercase and they must be written as they are.

False def if raise


None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not await
class form or async
continue global pass
Math math Module
60

Python has a built-in module for mathematical operations


The math module has a set of methods and constants. You need to import the
math library in python, just type: import math

Function or Method Description

math.ceil(num) Rounds a number up to the next (larger) integer

math.sin(num) Returns the sine of a number

math.cos(num) Returns the cosine of a number

math.tan(num) Returns the tangent of a number

math.exp(x) Returns E raised to the power of x

math.pow(x,y) Returns the value of x to the power of y

math.sqrt(num) Returns the square root of a number

math.degrees(angle) Converts an angle from radians to degrees

math.radians(degree) Converts a degree value into radians


Variables, Data types, Input and Output
61

Constant Description

math.e Returns Euler's number (2.7182...)

math.inf Returns a floating-point positive infinity

math.nan Returns a floating-point NaN (Not a Number) value

math.pi Returns PI (3.1415...)

math.tau Returns tau (6.2831...)


math examples

#Ex1 #Ex3
import math import math
x=2.5 r=3.4
y=5 area = math.pi * math.pow(r,2)
rst = math.pow(x,y) print('area = ', area)
print('x^y = ', rst)

#Ex2
import math
z = 100
rst = math.sqrt(z)
print('sqrt(z) = ', rst)
Python Built-in Functions
63

Built-in Functions
E R
A L
enumerate() range()
abs() len()
eval() repr()
aiter() list()
exec() reversed()
all() locals()
round()
any()
F
anext() M
filter() S
ascii() map()
float() set()
max()
format() setattr()
B memoryview()
frozenset() slice()
bin() min()
sorted()
bool()
G staticmethod()
breakpoint() N
getattr() str()
bytearray() next()
globals() sum()
bytes()
O super()
H
C object()
hasattr() T
callable() oct()
hash() tuple()
chr() open()
help() type()
classmethod() ord()
hex()
compile()
P V
complex()
I vars()
pow()
id()
D print()
input() Z
delattr() property()
int() zip()
dict()
isinstance()
dir()
issubclass() _
divmod()
iter() __import__()
Comments
64

As programs get bigger and more complicated, they get more difficult to
read and comprehend. For this reason, it is a good idea to add notes to
your programs to explain in natural language what the program is doing.
These notes are called comments, and they start with the # symbol:

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put
comments at the end of a line:
percentage = (minute*100)/60 # percentage of an hour

''' Text that span more than line


can be made a comment by inclosing in
between two sets of triple quotes '''
Types of Error and Debugging
65

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors. It is useful to distinguish between them in order to track them down more quickly.

Syntax error:
“Syntax” refers to the structure of a program and the rules about that structure.
For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but
8) is a syntax error.
If there is a syntax error anywhere in your program, Python displays an error
message and quits, and you will not be able to run the program.

#Example of a syntax error


mylist = [10,20,30]
print ('This will cause a syntax error: ')
avg = sum(mylist) divideBy 3 #Python does not understand 'divideBy' use / instead
print('avg = ', avg)

File "<ipython-input-6-9171592268fc>",
line 3 avg = sum(mylist) divideBy 3 ^
SyntaxError: invalid syntax
Types of Error and Debugging
66

Runtime error:
The second type of error is a runtime error, so called because the error does not
appear until after the program has started running.
These errors are also called exceptions error because they usually indicate that something exceptional
(and bad) as happened.
Runtime errors are rare in the simple programs.
#Example, divide by zero causes a runtime error…
mylist = [10,20,30]
print ('This will cause a runtime error: ')
avg = sum(mylist) / 0
print('avg = ', avg)
#output: notice that the first print ran THEN the runtime error occurred

This will cause a runtime error:


---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-5-5073f2b1f31b> in <cell line: 3>()
1 mylist = [10,20,30]
2 print ('This will cause a rutime error: ')
----> 3 avg = sum(mylist) / 0
4 print('avg = ', avg)
ZeroDivisionError: division by zero
Types of Error and Debugging
67

Semantic error (also known as logical error):


The third type of error is “semantic”, which means related to meaning. If there is
a semantic error in your program, it will run without generating error messages,
but it will not do the right thing, it will do something else.

Identifying semantic errors can be tricky because it requires you to work backward
by looking at the output of the program and trying to figure out what it is doing.

Example, find the average of a list:


mylist = [10,20,30]
avg = sum(mylist) / 2 # should be 3 or len(mylist)
print('avg = ', avg) # prints 30, it is a semantic error
Learning Outcomes
68

Upon completion of the course, students will be able to:


1. Identify the importance of AI and Data Science for society
2. Perform data loading, preprocessing, summarization and
visualization
3. Apply machine learning methods to solve basic regression
and classification problems
4. Apply artificial neural networks to solve simple engineering
problems
5. Implement basic data science and machine learning tasks
using programming tools

You might also like