Python Basics
Prof. Gheith Abandah
Developing Curricula for Artificial Intelligence and Robotics (DeCAIR)
618535-EPP-1-2020-1-JO-EPPKA2-CBHE-JP
1
Reference
• Wes McKinney, Python for Data Analysis: Data Wrangling
with Pandas, NumPy, and IPython, O’Reilly Media, 3rd
Edition, 2022. https://wesmckinney.com/book/
• Material: https://github.com/wesm/pydata-book
• Vanderplas, Jacob T. A Whirlwind Tour of Python. O'Reilly
Media, 2016.
• Material: https://github.com/jakevdp/WhirlwindTourOfPython/
2
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
3
Quick Python Syntax
• Comments are marked by #.
# Comments
• Quotation marks (" ') can
also be used to enter """
Multi-line comment often
comments. used in documentation
"""
• Use \ to extend a statement
"Single-line Comment"
on the next line.
• Semicolon ; can optionally
terminate a statement.
4
Quick Python Syntax
• In Python, code blocks
are denoted by
indentation.
• Four spaces are usually
used.
• Which code snippet
always prints x?
5
Quick Python Syntax
• Parentheses are for:
• Grouping
• Calling
6
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
7
Variables and Objects
• Python variables are pointers
to objects.
• Variable names can point to
objects of any type.
8
Variables and Objects
• If we have two
variable names
pointing to the
same mutable
object, then
changing one will
change the other
as well!
9
Variables and Objects
• Numbers, strings, and other simple types are immutable.
10
Variables and Objects
• Everything is an object
• Object have attributes and methods
accessible through the dot syntax (.)
11
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
12
Arithmetic Operators
13
Bitwise Operators
14
Comparison Operators
• Return Boolean values True or
False
15
Assignment Operators
• Assignment is evaluated from
right to left.
• There is an augmented
assignment operator
corresponding to each of the
binary arithmetic and bitwise
operators.
16
Boolean Operators
• The Boolean operators
operate on Boolean values:
• and
• or
• not
• Can be used to construct
complex comparisons.
17
Identity and Membership Operators
18
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
19
Python Scalar Types
20
Integers and Floats
• Integers are variable-precision, no overflow is possible.
• The floating-point type can store fractional numbers. They
can be defined either in standard decimal notation or in
exponential notation.
21
Strings
• Strings in Python are created with single or double quotes.
• The built-in function len() returns the string length.
• Any character in the string can be accessed through its index.
22
None and Boolean
• Functions that do not return value return None.
• None variables are evaluated to False.
• The Boolean type is a simple type with two possible values:
True and False.
• Values are evaluated to True unless they are None, zero or
empty.
23
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
24
Built-In Data Structures
• There are four built in Python data structures.
25
Lists
• List are ordered and mutable.
• A list can hold objects of any
type.
• Python uses zero-based
indexing.
• Elements at the end of the list
can be accessed with negative
numbers, starting from -1.
26
Lists
• Slicing is a means of accessing
multiple values in sub-lists.
[start : end+1 : inc]
• Negative step reverses the list.
• Both indexing and slicing can be used
to set elements as well as access
them.
27
Tuples
• Tuples are similar to lists, but are immutable.
• Can be defined with or without parentheses ().
• Functions return multiple values as tuples.
28
Dictionaries
• Dictionaries are flexible mappings of keys to values.
• They can be created via a comma-separated list of
key:value pairs within curly braces.
29
Sets
• Sets are unordered collections of unique items.
• They are defined using curly brackets { }.
• Set operations include union, intersection, difference and
symmetric difference.
30
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
31
Conditional Statements: if, elif, and
else
• if statements in Python have optional elif and else
parts.
32
for Loops
• The for loop is repeated for each index returned by the
iterator after in.
• The range() object is very useful in for loops.
33
for Loops
• The range(start, end+1, inc) has default zero start and
unit increment.
34
while Loops
• The while loop iterates as long as the condition is met.
35
break and continue: Fine-Tuning Your
Loops
• The continue statement skips the remainder of the current
loop, and goes to the next iteration.
Prints odd
numbers
36
break and continue: Fine-Tuning Your
Loops
• The break statement breaks out of the loop entirely.
List all Fibonacci
numbers up to 100.
37
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
38
Defining Functions
• Functions are defined with the def statement.
• The following function returns a list of the first N Fibonacci
numbers.
• Calling it:
39
Default Argument Values
• You can have default values for arguments.
• It can be called with our without the optional args.
40
*args and **kwargs: Flexible Arguments
• Functions can be defined using *args and **kwargs to
capture variable numbers of arguments and keyword
arguments.
Tuple
Dictionary
41
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
42
Objects and Classes
• Python is object-oriented programming language.
• Objects bundle together data and functions.
• Each Python object has a type, or class.
• An object is an instance of a class.
• Accessing instance data:
object.attribute_name
• Accessing instance methods:
object.method_name(parameters)
43
String Objects
• String objects are instances of class str.
name = input("Please enter your name: ")
print("Hello " + name.upper() + ", how are you?")
Please enter your name: Sami
Hello SAMI, how are you?
• String objects have many useful methods
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
44
String Methods
>>> s = " Hi "
>>> s.strip()
'Hi'
>>> 'Age: {0}, Weight: {1}'.format(20, 70)
'Age: 20, Weight: 70'
>>> s = 'This is a string'
>>> s.find('is')
2
>>> s.replace('a', 'the')
'This is the string'
45
String Objects
s = 'The cat\'s tail \n is \t long.'
print(s)
• Accept the escape character
The cat's tail
\. is long.
s = ''بايثون
print(s)
• Unicode encoded. بايثون
s_utf8 = s.encode('utf-8')
print(s_utf8)
b'\xd8\xa8\xd8\xa7\xd9\x8a\xd8\xab\xd9
\x88\xd9\x86'
46
Date and Time Objects
from datetime import datetime, date, time
• The built-in Python dt = datetime(1999, 8, 16, 8, 30, 0)
print(dt.day)
datetime module provides
datetime, date, and time 16
types. dt2 = datetime(2000, 8, 16, 8, 30, 0)
• Such objects can be delta = dt2 - dt
dt3 = dt2 + delta
formatted and accept - and print(dt3.strftime('%d/%m/%Y %H:%M'))
+ operands.
17/08/2001 08:30
47
File Objects
• Files can be opened for read, write or append.
f = open('myfile.txt', 'w')
f.write('Line 1\n')
f.write('Line 2\n')
f.close()
f = open('myfile.txt', 'r')
for line in f:
print(line.strip()) Line 1
Line 2
f.close()
48
Classes
• New class types can be defined using class keyword.
class Animal(object):
def __init__(self, name='Animal'): # Constructor
print('Constructing an animal!')
self.name = name
if name == 'Cat':
self.meows = True # Attribute
else:
self.meows = False
super(Animal, self).__init__()
def does_meow(self): # Method
return self.meows
Constructing an animal!
cat = Animal('Cat') It meows True
print('It meows ', cat.does_meow())
49
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
50
Runtime Errors
1. Referencing an undefined
variable
2. Unsupported operation
3. Division by zero
4. Accessing a sequence element
that doesn’t exist
51
Catching Exceptions: try and except
• Runtime exceptions can be handled using the try…except
clause.
You can catch specific exceptions:
except ZeroDivisionError:
52
try…except…else…finally
• Python also support else and finally
53
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
54
Iterators
• Iterators are used in for loops and can be used using
next()
55
Iterators
• The range iterator
• Iterating over lists
• enumerate iterator
L=[2,4,6,8,10]
list(enumerate(L)
56
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
57
List Comprehensions
• A way to compress a list-building for loop into a single short,
readable line.
• Syntax: [expr for var in iterable]
58
List Comprehensions
• Lists comprehensions can be used to construct sets with no
duplicates.
• Or dictionaries
59
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
60
Generators
• A list is a collection of values, while a generator expression is
a recipe for producing values.
61
Generators
• A generator function uses yield to yield a sequence of
values.
Get a sequence from
the generator
62
Homework 2
• Solve the homework on Python Basic Programming
63
Summary
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
64