Week 2- Introduction to Python #1
Week 2- Introduction to Python #1
Assembly Languages
English-like abbreviations
■ Represent elementary operations of 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
5
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 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
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
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
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.
>>> 1sum = ‘sum of grades of section 1‘ #do not start with a number
SyntaxError: invalid syntax
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
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
x=12345
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)
•()
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
35
== Equal x == y
!= 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
39
Exercise:
q 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.
44
value = L1.pop(index) Removes and returns the element at the specified position
#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
tuple1[0] = 100
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
d1.items() Returns a list containing a tuple for each key value pair
{'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
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
# 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
Constant Description
#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:
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
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
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
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.