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

2 Introduction to Python Part 1 2

This document serves as an introduction to Python programming, covering essential topics such as computer software, programming languages, and the fundamentals of Python including data types and operations. It emphasizes Python's versatility and popularity in various fields like data science and web development. The document also includes practical examples and instructions for using Google Colab to execute Python code.

Uploaded by

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

2 Introduction to Python Part 1 2

This document serves as an introduction to Python programming, covering essential topics such as computer software, programming languages, and the fundamentals of Python including data types and operations. It emphasizes Python's versatility and popularity in various fields like data science and web development. The document also includes practical examples and instructions for using Google Colab to execute Python code.

Uploaded by

Yusra Eltilib
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Introduction to Python Programming – Part 1

Intro to AI and Data Science


NGN 112 – Fall 2024

Ammar Hasan
Department of Electrical Engineering
College of Engineering

American University of Sharjah

Prepared by Dr. Jamal A. Abdalla, CVE


Revised by Dr. Tamer Shanableh, CSE

Last Updated on: 22nd of August 2024


Table of Content
2

Computer Software and Programming Languages

Introduction to Python

Variables and Data Types

Python Operations
Computer Software
3

◻ 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, …..
High Level Languages
4
Programming Languages
5

Source: https://www.educba.com/types-of-computer-language/
Machine Languages
6

◻ 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 (e.g. copy a number
from memory to the CPU)
■ Tedious and error-prone
■ Lead to Assembly Languages
Assembly Languages
7

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

❖ Translated to machine language before running them


■ Assemblers convert 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
8

◻ 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 have Code Instructions


understandable to humans
■ Looks mostly like everyday English (e.g. print([1,2,3,4])
■ Contain common mathematical notation (e.g. rst = x / y)
■ Used in a development environment (e.g. 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)
Compiled versus Interpreted Languages
Object-Oriented Programming
11

◻ 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 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
Object-Oriented Programming
12
C, C++, Java, Python
13

◻ C
❖ Developed by Dennis Ritchie at Bell Laboratory (1972)
❖ Gained recognition as the 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 the functionality of WWW servers
14

Introduction to Python
Python
15

◻ 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?
16
Why Python?
17

◻ 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 object-oriented programming language.
• It is the widely used programming language for Data Science and Machine
Learning
• One of the top programming languages required by employers:
https://spectrum.ieee.org/the-top-programming-languages-2023
Google Colab Notebook
18

◻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
19
Google Colab Notebook (1/2)
20

◻ 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.
Google Colab Notebook (2/2)
21
The First Program
22

◻ 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)
print (miles)
print (name)
Output:
Hello World!
100
1000.0
Zara Ali
The print() function
23

#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
24

Variables and Data Types


Variables, Data types, Input and Output
25

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)
Dictionary (dict)
Set (set)
Range (range)
Variables
26
Data Types Description and Examples
27
Python Operations
28

❑ Arithmetic operators (e.g. x + y)


❑ Assignment operators (e.g. x = y)
❑ Comparison operators (e.g. x > y)
❑ Logical operators (e.g. x and y)
❑ Identity operators (e.g. x is y)
❑ Membership operators (e.g. x in y)
❑ Bitwise operators (e.g. x & y)
Variable Names Rules
29

❑ Variable names can be as long as you like.


❑ They can contain both letters and numbers (e.g. fall23).
❑ They can’t begin with a number. (e.g. 23fall is not allowed)
❑ Uppercase letters are not allowed. (e.g. Fall23 is not allowed) – correct for old
versions of Python
❑ Keywords cannot be used as variable names. (e.g. 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
30

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 (1/2)
31

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 (2/2)
32

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
33

◻ 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
34

◻ 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


int Type Operator examples (1/2)
35

x=12345

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


print(x%100) #remainder of division by 100 = 45
print(x%1000) #remainder 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
int Type Operator examples (1/2)

#access one digit at a time


x=12345
print(x%10) #remainder 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
37

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
38

Arithmetic operators are used with numeric values to perform common mathematical operations.

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
39

•()
• Exponentiation: **
• Unary operators: + – # e.g. -x or +x
• Binary arithmetic: * / %
• Binary arithmetic: + – # e.g. x-y
• Comparisons: < > <= >=
• Equality relations: == != # (x==y) means is x equal to y
• Logical not # found=false | e.g. !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/2)
40

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-1
41

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/2)
42

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
43

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 (e.g. (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
44

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

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
46

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
47

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


String Data Type
str Type and its Operations (1/3)
49

Type string or str represents text


Values: any sequence of characters
Operation(s): + (catenation, or concatenation) e.g. 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 (2/3)
50

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 (3/3)
51

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


Type Conversion, Casting, and Input function
Types Conversion and Casting
53

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 (1/2)
54

◻ Python allows for users to input values for their


variables, which means we can ask the user for
input.
◻ This can be done using the input() function.
◻ By default, the input() function returns a string;
however, we can cast the output of the input
function to an integer or a float using int() or
float() functions, respectively.
The input() function (2/2)
55

# The input function returns a string


x = input("Enter a value for x: ") #
enter 100
# The input function returns a string y = input("Enter a value for y: ") #
name = input('Enter a name: ') enter 200
print('The name is: ', name) # here x and y are treated as strings
# hence the output is x+y is string
concatenation
print ('x + y = ', x+y) # prints 100200

# The input function returns a # The input function returns a string |


string | Then cast to int Then cast to float
x = int(input("Enter an int value f1 = float(input("Enter a float value
for x: ")) # enter 100 for f1: "))# enter 100.5
y = int(input("Enter an int value f2 = float(input("Enter a float value
for y: ")) # enter 200 for f2: "))# enter 200.5
# here x and y are treated as ints # here f1 and f2 are treated as floats
# hence the output is x+y is 300 # hence the output is f1+f2 is 301
print ('x + y = ', x+y) print ('f1 + f2 = ', f1+f2)
Compound Data Types
Compound Data Types
57

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)
list Type and its Operations
58

❑ Type list represents a sequence that stores a collection of


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

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


allowed.

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

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


list Type and its Operations
59

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

Method (Assume you have Description


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 (all items need to be either strings or numbers)
Examples of list Function Calls
61

#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)
List vs Tuple
62

difference
tuple Type and its Operations
63

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
64

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
65

Method (assume you have a Description


tuple called myTuple)

Returns the number of times a specified value occurs


cnt=myTuple.count(value) in a tuple

Searches the tuple for a specified value and returns


idx=myTuple.index(value) the position of where it was found
Lists vs Dictionaries
66
Lists vs Tuple vs Dictionaries
67

difference
dict Type and its Operations
68

◻ 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 key 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
69

dict values can be lists or tuples, like:


#key: student name, value: grade list
grade_book = {
Outputs:
'Ali': [92, 85, 100],
{'Ali': [92, 85, 100], 'Layla': [83, 95, 79], 'Hassan': [91, 89, 82],
'Layla': [83, 95, 79], 'Huda': [97, 91, 92]}
'Hassan': [91, 89, 82],
'Huda': [97, 91, 92]
}
print(grade_book)
#key: student name, value: grade tuple Outputs:
grade_book = { {'Ali': (92, 85, 100), 'Layla': (83, 95, 79), 'Hassan': (91, 89, 82),
'Huda': (97, 91, 92)}
'Ali': (92, 85, 100),
'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
70

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 | e.g. d2=d1.copy()
fromkeys() Returns a dictionary with the specified keys and value
d1.get(key) Returns the value of the specified key
e.g. 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


e.g. 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
e.g. d1.update({‘Hassan’: [100,100,100] }

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


e.g. dict_values = d1.values()
Dictionary update and insert Functions
71

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]}
List vs Set
72

difference
set Type and its Operations
73

◻ Type set represents a set of variables

◻ set is created using square curl parenthesis { }.

◻ setitems 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
74

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_upd inserts the symmetric differences from this set and another
ate()
union() Return a set containing the union of sets

update() Update the set with another set, or any other iterable
Comparison
75

*
Identity and Membership
Identity Operators
77

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 x is y
are the same object
is not Returns True if both variables x is not y
are not the same object

*Objects exclude integers and strings


Identity Operators: Examples
78

# 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
79

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
80

# 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)
81

Python Operations
Keywords and Built-in Functions
Python Keywords
83

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
Python Built-in Functions
84

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()
V
complex() P
I vars()
pow()
id()
D print()
input() Z
delattr() property()
int() zip()
dict()
isinstance()
dir()
issubclass() _
divmod()
iter() __import__()
Math Module
Math math Module
86

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
87

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
88

#Ex1 #Ex3
import math
x=2.5
import math
y=5 r=3.4
rst = math.pow(x,y) area = math.pi * math.pow(r,2)
print('x^y = ', rst)
print('area = ', area)
#Ex2
import math
z = 100
rst = math.sqrt(z)
print('sqrt(z) = ', rst)
Comments, Errors, and Debugging
Comments
90

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
91

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
92

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 exception errors because they usually indicate that something
exceptional (and bad) has happened.
• Runtime errors are rare in 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
93

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
94

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