2 Introduction To Python Basics
2 Introduction To Python Basics
Introduction to Python
Python Operations
Learning Outcomes
3
◻ 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
7
◻ 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., Google Colab)
Compiled versus Interpreted Languages
8
◻ 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
Common High-Level Language: Python
11
◻ 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.
❖ It is the widely used programming language for Data Science and Machine
Learning
◻What is Colab?
◻ Cells
A notebook is a list of cells. Cells contain either explanatory text (Text Cells) or executable code
(Code Cells) and their output.
◻ Code cells
The following are some keyboard shortcuts for the code cells:
❖ 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)
❖ 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
❖ A text cell can be edited by double-clicking it. 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)
15
Text Cell
Code Cell
#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
18
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
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
25
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
26
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
(integer division)
x // y
Precedence of Arithmetic Operations
31
• Paratheses ( )
• Exponentiation: **
• Unary operators: + – # e.g. -x or +x
• Arithmetic: * / %
• 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)
•()
rst = 2 * 32 + 49 % 10 • Exponentiation: **
• Unary operators: + –
• Arithmetic: * / %
rst = 2 * (9) + 49 % 10 • 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
37
!= 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: + –
• Arithmetic: * / %
rst = True and (10!=-10) or not False • 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)
41
Exercise:
❑ 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.
47
Idx=[Link](value) Returns the index of the first element with the specified value
[Link](index, value) Adds an element at the specified position
value = [Link](index) Removes and returns the element at the specified position
[Link]() Sorts the list (all items need to be either strings or numbers)
Examples of list Function Calls
48
#pop(index) example
l = [1,2,3,4]
value = [Link](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
49
tuple1[0] = 100
◻ 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
53
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]}
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
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable
Constant Description
#Ex1 #Ex3
import math
x=2.5
import math
y=5 r=3.4
rst = [Link](x,y) area = [Link] * [Link](r,2)
print('x^y = ', rst)
print('area = ', area)
#Ex2
import math
z = 100
rst = [Link](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()
V
complex() P
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.
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 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