2 Introduction to Python Part 1 2
2 Introduction to Python Part 1 2
Ammar Hasan
Department of Electrical Engineering
College of Engineering
Introduction to Python
Python Operations
Computer Software
3
Source: https://www.educba.com/types-of-computer-language/
Machine Languages
6
◻ Assembly Languages
❖ English-like abbreviations
■ Represent elementary operations of the computer
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)
◻ 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
◻ 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
◻What is Colab?
◻ 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.
#Printing the Value of an Expression (do not use quotations for expression):
print('Sum = ', 1 + 2)
output: Sum = 3
24
Python supports five basic data types and five compound data types.
Each data type has its own operations.
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
x=12345
Arithmetic operators are used with numeric values to perform common mathematical operations.
+ 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
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 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)
•()
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
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
!= Not equal x != y
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
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[0]: H
var2[1:5]: ytho
str Type and its Operations (3/3)
51
Exercise:
Python supports five basic data types and five compound data types.
Each data type has its own operations.
❑ List items are indexed, the first item has index [0], the second
item has index [1], …….
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[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
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.sort() Sorts the list (all items need to be either strings or numbers)
Examples of list Function Calls
61
#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
tuple1[0] = 100
difference
dict Type and its Operations
68
◻ 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
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'])
{'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
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
# 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
Python Operations
Keywords and Built-in Functions
Python Keywords
83
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
Constant Description
#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.
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