0% found this document useful (0 votes)
3 views40 pages

2-Introduction To Python

The document provides an introduction to Python programming, highlighting its popularity, ease of learning, and extensive library support, particularly for embedded vision systems. It covers fundamental concepts such as data types, operators, control structures, functions, and file handling, along with practical examples. Additionally, it emphasizes the use of Python 3.x over the obsolete Python 2.x and offers resources for online coding practice.

Uploaded by

ibrbuss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

2-Introduction To Python

The document provides an introduction to Python programming, highlighting its popularity, ease of learning, and extensive library support, particularly for embedded vision systems. It covers fundamental concepts such as data types, operators, control structures, functions, and file handling, along with practical examples. Additionally, it emphasizes the use of Python 3.x over the obsolete Python 2.x and offers resources for online coding practice.

Uploaded by

ibrbuss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

ECCE5293: Embedded Vision Systems

Introduction to ____________
Ahmed Al Maashri, PhD
Department of Electrical & Computer Engineering

Fall 2023
Why Python?
• Python has become one of the most popular programming languages

• The language is easy to learn

• Highly productive

• Has very good support to many libraries, including OpenCV

Ahmed Al Maashri ©2023 2


Python Programming Language
• The current stable version is 3.11.x
• While some developers are still using Python 2.x, this is not recommended
given that many functions are obsolete and may not have any support in
the future.
• Linux Distributions (e.g. Ubuntu) come with Python interpreter already
installed. However, Windows user have to download/install Python
interpreter (https://www.python.org/downloads/windows/). You can also
install Python from Microsoft Store.
• Students will be provided with an Ubuntu Virtual Machine that comes
with Python and other libraries already installed and configured.
Ahmed Al Maashri ©2023 3
Python Online Shell
• There are several websites that offer an online shell where you execute
python commands and run python scripts:

• https://www.python.org/shell/

• https://www.w3schools.com/python/trypython.asp?filename=demo_compiler

• https://pythontutor.com/

• Try these online services! You can execute the commands and scripts
discussed in this lecture.

Ahmed Al Maashri ©2023 4


Basics of Python
• Python is an interpreted language. This means that you do not have to compile
the code before execution (Unlike C/C++). Just CODE and RUN.
• Just like C/C++, Python is a case-sensitive language. Watch out, since this is a
source of many beginner’s bugs!
• Instead of using parenthesis { }, Python uses spaces to structure the code. Here
is an example:
if (X > Y):
if (X > Y) { cout << “True”; }

Python
print (“True”)
C++

else:
else { cout << “False”; }
print (“False”)
• Comments begin with the symbol #

Ahmed Al Maashri ©2023 5


print( )

• The command print() is used to display information on the screen.


This is similar to cout in C++

• Example

X = 4
print(X)

Ahmed Al Maashri ©2023 6


Arithmetic and Logical Operators
• The table shows the arithmetic operators supported by Python:
Operator Function
+ Addition

- Subtraction

* Multiplication

/ Division

% Remainder of division operation

** Exponentiation

// Integer division

• Bitwise Logical operations are also supported (&, |, ^, ~)


Ahmed Al Maashri ©2023 7
Assignment
• In Python, multiple variables can be assigned in a single statement.

• Example:
X = 1 Is equivalent to
Y = 2 X, Y, Z = 1, 2, 3
Z = 3

Ahmed Al Maashri ©2023 8


Data Types
• Commonly used data type:
• Integers (int)
• Floats (float)
• Boolean (bool)
• String (str)
• However, you do not have to explicitly declare the type. Python will
infer the type whenever you assign a value to a new variable
• The command type() can be used to display the data type of a variable
• Examples:
type(1.2) ➔ <class ‘float’>
type(“Hello There”) ➔ <class ‘str’>

Ahmed Al Maashri ©2023 9


Comparisons
• The following table shows the comparison operators. The result of
using these operators is Boolean (i.e. True or False)
Operator Function
< Less than

> Greater than

<= Less than or equal

>= Greater than or equal

== Equal

!= Not Equal

• Comparisons can be combined using “and”, “or”, “not”


Ahmed Al Maashri ©2023 10
Conversion between data types
• You can convert from one type to another using datatype wrapper:
int, float, str, or bool

• Examples:
X = 1.2
print(int(X)) ➔ 1

Y = "2.5"
print(float(Y)*4) ➔ 10.0

Ahmed Al Maashri ©2023 11


Strings
• To concatenate strings, use the + operator
• Example
A = “Hi”
B = “There”
Print(A + “ ” + B) ➔ Hi There

• To know the size of a string, use the len() function


• Example:
Text = “This is a Test Text”
Print(len(Text)) ➔ 19

Ahmed Al Maashri ©2023 12


Strings [cont.]
• Strings have a bunch of other methods (e.g. .count(), .index(),
.find(), .split(), etc.)

• A method is a function that belongs to an object

• Examples:
print(“test text”.count(‘t’)) ➔ 4
print(“test text”.split()) ➔ ['test', 'text’]
print(“test text”.title()) ➔ Test Text
print(“test text”.upper()) ➔ TEST TEXT

Ahmed Al Maashri ©2023 13


Data Structures: Lists
• A list is a collection of elements. These elements do not necessarily
have to be of the same data type
• Examples
List1 = [‘RED’, ‘BLUE’, ‘GREEN’]
List2 = [‘RED’, ‘BLUE’, 5, 10.9]

• The command len() can be used to return the number of elements in


a list
• Example:
print(len(List1)) ➔ 3

Ahmed Al Maashri ©2023 14


Data Structures: Lists [cont.]
• You can access any element by indexing to its location.
• Examples:
Days = ['SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI']
print(Days[0]) ➔ SAT
print(Days[1]) ➔ SUN

print(Days[-1]) ➔ FRI Syntax is


print(Days[-2]) ➔ THU start:stop:step
• Lists can be sliced:
Weekdays = Days[1:6]
print(Weekdays) ➔ ['SUN', 'MON', 'TUE', 'WED', 'THU']
Weekends = Days[::len(Days)-1] ➔ ['SAT', 'FRI']
Ahmed Al Maashri ©2023 15
Data Structures: Lists [cont.]
• You can check if an element exists in a list using the “in” operator
• Examples:
print('SAT' in Days) ➔ True
print('WEEK' in Days) ➔ False
print('WEEK' not in Days) ➔ True

• Lists also have methods (e.g. max(), min(), sorted(), join(), .append())
List1 = ["a", "b", "c"]
print("-".join(List1)) ➔ a-b-c

Ahmed Al Maashri ©2023 16


Data Structures: Tuples
• Tuples are similar to lists. However, once a tuple is created, its content
can’t be modified.

• Examples
Tuple1 = (‘RED’, ‘BLUE’, ‘GREEN’)
Tuple2 = (‘RED’, ‘BLUE’, 5, 10.9)

• The command len() can be used to return the number of elements in


a tuple
• Example:
print(len(Tuple1)) ➔ 3
Ahmed Al Maashri ©2023 17
Data Structures: Dictionary
• Dictionaries store data in key:value pairs. This way, you can index into a value not
using its location but using the key associated with it.

• Examples
Dict1 = {
“ID” : 12345, print (Dict1[“ID”]) ➔ 12345
“Name” : “Ahmed”,
print (Dict1[“Country”]) ➔ OM
“Country” : “OM”
}

• The command len() can be used to return the number of items in a tuple
• Example: print(len(Dict1)) ➔ 3

Ahmed Al Maashri ©2023 18


Conditional (if) Statements
• Syntax:
if condition:
statement1
if condition: statement2
if condition: statement1 ...
statement1 statement2 elif condition:
statement2 ... statement1
… else: statement2
statement1 ...
statement2 else:
... statement1
statement2
...

Ahmed Al Maashri ©2023 19


Loops (for)
• Syntax: for item in list:
statement1
statement2

• Example:
Days = ['SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI']
for Day in Days:
SAT
print(Day) ➔ SUN
MON
TUE
WED
THU
FRI
Ahmed Al Maashri ©2023 20
Loops (for) [cont.]
• You can also specify a range to iterate over using the ‘range’ function
• Syntax: range(start, stop, step)
0
1
• Examples: 2
3
for i in range(8): 4
print(i) 5
2 6
3 7
for i in range(2, 6):
4
print(i) 5

for i in range(0, 8, 2): 0


2
print(i) 4
Ahmed Al Maashri ©2023 6 21
Loops (while)
• Syntax:

while condition_is_true:
statement1
statement2

Ahmed Al Maashri ©2023 22


break and continue statements
• break is used to exit from loop
• Example: for i in range(100):
sum += num * i
if sum > 2500:
break

• continue is used to skip a loop iteration


• Example: for i in range(100):
if i % 2 == 0
continue
sum += num * i
Ahmed Al Maashri ©2023 23
List Comprehension
• Python provides a compact way of handling lists
• Example 1:
Days = ['SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI']
days = [day.lower() for day in Days]
print(days) ➔ ['sat', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri']
• Example 2:
squares = [x**2 for x in range(10) if x%2 == 0]
print(squares) ➔ [0, 4, 16, 36, 64]
• Example 3:
names = ["Hassan Ahmed", "Omar Salem", "Faiza Hamed"]
first_names = [name.split()[0].lower() for name in names]
print(first_names) ➔ ['hassan', ‘omar', 'faiza']
Ahmed Al Maashri ©2023 24
zip
• zip returns an iterator that combines multiple iterables into one
sequence of tuples. Each tuple contains the elements in that position
from all the iterables.
fruits = [‘apples’, ‘oranges', ‘bananas’]
• Example: years = [2020, 2021, 2022]

result = zip(fruits, years)


print(list(result))

[('apples', 2020), ('oranges', 2021), ('bananas', 2022)]


Ahmed Al Maashri ©2023 25
enumerate
• enumerate is a built-in function that returns an iterator of tuples
containing indices and values of a list. You'll often use this when you
want the index along with each element of an iterable in a loop.

• Example:
Letters = [‘a’, ‘b’, ‘c’] 0 a
for i, letter in enumerate(Letters): 1 b
print(i, letter) 2 c

Ahmed Al Maashri ©2023 26


Functions
• The keyword def is used to define functions
• Syntax:

def function_name(arg1, arg2, ...):


statement1
statement2
...
return some_value

Ahmed Al Maashri ©2023 27


Functions [cont.]
• Example 1:
def triangle_area(base, height): # function header
return 0.5 * base * height # function body

print (triangle_area(5, 10)) # function call

• Example 2:
def hello_msg():
print(‘Hello There’)

hello_msg()
Ahmed Al Maashri ©2023 28
Functions [cont.]
• Example 3: Specifying default values for arguments

def triangle_area(base, height=10):


return 0.5 * base * height

print (triangle_area(5)) ➔ 25
print (triangle_area(5, 20)) ➔ 50

Ahmed Al Maashri ©2023 29


Functions [cont.]
• Main function: you can declare a main function that will be invoked
by default if the script is executed.
• The main is denoted by __main__ as shown in the example below:

def main():
statement1
statement2
...

if __name__ == ‘__main__’:
main()

Ahmed Al Maashri ©2023 30


Reading inputs from user
• Consider the case where the script needs to prompt the user for an
input. This is where the command input comes into use.

• Examples:

name = input('Enter a name: ') Enter a name: salim


print ('Hello {}'.format(name.title())) Hello Salim

result = eval(input('Enter an Expression: '))


print(result)

Enter an expression: 5 + 6
11
Ahmed Al Maashri ©2023 31
Catching Exceptions
• Exceptions are run-time errors (errors that occur during the execution
of the program)

• Examples of exceptions are: dividing by zero, opening a non-existing


file, passing a value of wrong data type, etc.

• Use try and except to catch an error and avoid terminating the
program unexpectedly.

Ahmed Al Maashri ©2023 32


Catching Exceptions [cont.]
• Example:

A, B = input('Enter two values A and B, and I will calculate A / B\n').split()

try:
print(float(A)/float(B))
except:
print(‘Division by Zero is not allowed')

Print('Program Completed Successfully')

Ahmed Al Maashri ©2023 33


Accessing Files
• The command open is used to access files for both reading and
writing.

• Examples:
f = open(filename, ‘r’) # open file for reading
file_data = f.read() # store file content in variable
f.close() # close file

f = open(filename, ‘w’) # open file for writing


f.write(“some_text”) # write contents to file
f.close() # close file

Ahmed Al Maashri ©2023 34


Accessing Files [cont.]
• More Examples:
f = open(filename, ‘a’) # Append to existing file
f.write(‘some_text’) # write contents to file
f.close() # close file

• Another way to open a file using ‘with’ statement:

with open(filename, ‘r’) as f:


file_data = f.read()

# file is closed automatically once the code exists the “with” scope

Ahmed Al Maashri ©2023 35


Libraries (Packages)
• The command import is used to include Python scripts, packages,
modules, and functions into the existing script (this is similar to
#include in C/C++)

• Syntax: import package_name


• Example:
# Package: functions.py # Main script
def double(x): import functions
return x*2
print(functions.double(3))

Ahmed Al Maashri ©2023 36


Libraries (Packages) [cont.]
• You can use alias to shorten function calling
• Example:

# Package: functions.py # Main script


def double(x): import functions as fn
return x*2
print(fn.double(3))

• You can also specify a submodule to be imported from a package


from collection import defaultdic

import os.path

Ahmed Al Maashri ©2023 37


Standard Libraries
• Tens of packages can be imported into your script: Check the
following link: https://docs.python.org/3/library/

• Examples

import math

print(math.factorial(4))

Ahmed Al Maashri ©2023 38


3rd Party Packages
• If existing standard packages do not support what you are looking for,
then you can install additional packages using the pip command. This
is the default package manager for Python.

• To install a package: pip install xyz

• Then import package as usual to your script import xyz

Ahmed Al Maashri ©2023 39


References

• Introduction to Python Programming, Udacity [Online]:


https://classroom.udacity.com/courses/ud1110

• Python Programming Language, Doulos Training

• Python Tutorial [Online]: https://www.w3schools.com/python/

Ahmed Al Maashri ©2023 40

You might also like