Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Mechatronics Engineering and Automation Program

CSE489: Machine Vision


Lab #02: Python Basics

Objectives:
 Introduce the main properties of Python language
 Introduce the basics of Python:
o Variables and datatypes
o Arithmetic Operators
o Loops
o If statement
o Data structures
 List
 Tuples
 Dictionaries
o Function definition
o Class definition
 Extending Python using packages

Python Basics
Python is a high-level, dynamically typed multiparadigm programming language.
Python code is often said to be almost like pseudocode, since it allows you to express
very powerful ideas in very few lines of code while being very readable. This tutorial
gives you an overview of the entire Python world. First you will read a description of the
Python language and its unique characteristics. You’ll see where to start, what an
interpreter is, and how to begin writing the first lines of code in Python. Then you are
presented with some new, more advanced, forms of interactive writing with respect to
the shells, such as IPython and IPython Notebook.
This language can be characterized by a series of adjectives:
 Interpreted
 Portable
 Object-oriented
 Interactive
 Interfaced
 Open source
 Easy to understand and use
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

Interpreter Vs Compiler

Variables and Datatypes


Unlike languages such as C/C++, the datatype of variables in python doesn't need to be
explicitly defined on defining the variable but the python will assign a suitable datatype
for the variable according to its initial value. You can check the datatype for each
variable by using type function:
var1 = 10
var2 = 5.5
var3 = "Hello World!"

print(type(var1))
print(type(var2))
print(type(var3))
<class 'int'>
<class 'float'>
<class 'str'>

Naming and Using Variables


When you’re using variables in Python, you need to adhere to a few rules and
guidelines. Breaking some of these rules will cause errors; other guidelines just help you
write code that’s easier to read and understand. Be sure to keep the following variable
rules in mind:
 Variable names can contain only letters, numbers, and underscores. They can
start with a letter or an underscore, but not with a number. As an example, you
can call a variable user_1 but not 1_user.
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

 Spaces are not allowed in variable names, but underscores can be used to
separate words in variable names. For example, user_name works, but user name
will cause errors.
 Avoid using Python keywords and function names as variable names; that is, do
not use words that Python has reserved for a particular programmatic purpose,
such as the word if.
 Variable names should be short but descriptive. For example, name is better than
n, student_name is better than s_n, and name_length is better than
length_of_persons_name.
 Be careful when using the lowercase letter l and the uppercase letter O because
they could be confused with the numbers 1 and 0.

Arithmetic operations
Common arithmetic operations such as +, -, /, and * can be used as usual in Python.
Other operators such as:
 exponent operator ** performs exponential (power) calculation on operators.
 Modulus operator % divides left hand operand by right hand operand and returns
remainder.
 Floor Division // - The division of operands where the result is the quotient in
which the digits after the decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away from zero (towards negative
infinity)
print(4**3) #Perform power calculation

print(7%3) #Get the remainder of division

print(9//2) #Floor division (Approximate towards -ve infinity)


print(-9//2)#Floor division (Approximate towards -ve infinity)
64
1
4
-5

Lists
The type list is a data structure that contains a number of objects in a precise order to
form a sequence to which elements can be added and removed. Each item is marked
with a number corresponding to the order of the sequence, called the index.
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

numbers = [1, 2, 3, 4]
print(numbers)
elements= ['chair', 'desk', 'wall']
print(elements)
[1, 2, 3, 4]
['chair', 'desk', 'wall']

If you want to access the individual elements, it is sufficient to specify the index in
square brackets (the first item in the list has 0 as its index):
elements[0]
'chair'

If you are using negative indices instead, this means you are considering the last item in
the list and gradually moving to the first.
numbers[-2]
3

You can create a list of numbers using the range function which take arguments as
(start, end, step)
numbers = list(range(5))
print(numbers)

even_numbers = list(range(2,11,2))
print(even_numbers)

[0, 1, 2, 3, 4]
[2, 4, 6, 8, 10]

Note that the upper limit of the range is not included into the list as the range function
exclude the final element from the list.

Adding and Removing Elements from a List


A new item can be added to the end of the list using the append method.
If you want to add a new item at specific location, you can use insert method and
specify the index of the new item and its value.
numbers.append(5) #Add item of value 5 to the end of the numbers list
print(numbers)

elements.insert(1,"fan")
print(elements)
[0, 1, 2, 3, 4, 5]
['chair', 'fan', 'desk', 'wall']
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

There are many methods to remove items form the list in python, each one has its own
properties.
- You can use del method to delete item from the list if you know its index.
- Another method is pop which removes the item from the list and return it as an output
of the function.
- Function remove is used when you want to remove item using its value not its index.
del numbers[1]
print(numbers)
[0, 2, 3, 4, 5]
last_item = numbers.pop()
print(last_item)
print(numbers)

second_item = numbers.pop(1)
print(second_item)
print(numbers)
5
[0, 2, 3, 4]
2
[0, 3, 4]
print(elements)
elements.remove('chair')
print(elements)
['chair', 'fan', 'desk', 'wall']
['fan', 'desk', 'wall']

Looping through a List in python


animals = ['dog', 'cat', 'turtle']

for i in range(3):
print(animals[i].upper()+ " would make a great pet")

print("All the above animals would make great pets\n")


DOG would make a great pet
CAT would make a great pet
TURTLE would make a great pet
All the above animals would make great pets

Note that the indentation is essential in python code. In Python indentation plays an
integral role in the implementation of the code, by dividing it into logical blocks.
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

animals = ['dog', 'cat', 'turtle']

for i in range(3):
print(animals[i].upper() + " would make a great pet")

print("All the above animals would make great pets\n")


DOG would make a great pet
All the above animals would make great pets

CAT would make a great pet


All the above animals would make great pets

TURTLE would make a great pet


All the above animals would make great pets
animals = ['dog', 'cat', 'turtle']

for animal in animals:


print(animal.title() + " would make a great pet")

print("All the above animals would make great pets")


Dog would make a great pet
Cat would make a great pet
Turtle would make a great pet
All the above animals would make great pets

Functions for Numerical Lists


A few Python functions are specific to lists of numbers. For example, you can easily find
the minimum, maximum, and sum of a list of numbers:
numbers = [88, 12, 27, 100, 10, 5, 90]
print("Minimum: ",min(numbers))
print("Maximum:", max(numbers))
print("Sum: ", sum(numbers))
Minimum: 5
Maximum: 100
Sum: 332
squares=[]
for value in range(1,11):
squares.append(value**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

List Comprehension
A list comprehension allows you to generate this same list in just one line of code. A list
comprehension combines the for loop and the creation of new elements into one line,
and automatically appends each new element.
squares= [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Slicing a List
You can also work with a specific group of items in a list, which Python calls a slice. To
make a slice, you specify the index of the first and last elements you want to work with.
As with the range() function, Python stops one item before the second index you
specify. To output the first three elements in a list, you would request indices 0 through
3, which would return elements 0, 1, and 2.
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[0:3] #Items of index 0 to 2
['cairo', 'rome', 'paris']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[1:4] #Items of index 1 to 3
['rome', 'paris', 'london']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[:4] #Items from the beginning to index 3
['cairo', 'rome', 'paris', 'london']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[2:] #Items from the index 2 to the end of list
['paris', 'london', 'madrid']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[-3:] #Last three items
['paris', 'london', 'madrid']

Tuples
Lists work well for storing sets of items that can change throughout the life of a
program. The ability to modify lists is particularly important when you’re working with
a list of users on a website or a list of characters in a game. However, sometimes you’ll
want to create a list of items that cannot change. Tuples allow you to do just that.
Python refers to values that cannot change as immutable, and an immutable list is
called a tuple.
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

A tuple looks just like a list except you use parentheses instead of square brackets. Once
you define a tuple, you can access individual elements by using each item’s index, just as
you would for a list.
dimensions = (400, 50)
print(dimensions[0])
print(dimensions[1])
400
50
dimensions[0] = 200
--------------------------------------------------------------------------
-

TypeError: Traceback (most recent call last)

<ipython-input-24-dbb7433ce5e9> in <module>
----> 1 dimensions[0] = 200

TypeError: 'tuple' object does not support item assignment

The code tried to change the value of the first dimension, but Python returned a type
error. Basically, because we’re trying to alter a tuple, which can’t be done to that type of
object, Python tells us we can’t assign a new value to an item in a tuple. If you want to
change a value in tuple you have to define a new tuple and assign it to the same variable
as follows:
dimensions = (250,50)
print(dimensions[0])
print(dimensions[1])

If Statement
The following short example shows how if tests let you respond to special situations
correctly. Imagine you have a list of cars and you want to print out the name of each car.
Car names are proper names, so the names of most cars should be printed in title case.
However, the value 'bmw' should be printed in all uppercase. The following code loops
through a list of car names and looks for the value 'bmw'. Whenever the value is 'bmw',
it’s printed in uppercase instead of title case:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for var in cars:
if var == 'bmw':
print(var.upper())
else:
print(var.title())
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

Other numerical comparison operators in python include:


- != Not equal, > Larger than, < Smaller than, >= Larger than or equal
To combine multiple condition in one if statement you can use and, or operators
age = 50
if (age>=13 and age<20):
print("Warning! ")
else:
print("Pass")
Pass
print(age>=13)
True

Check if value in/ Not in a List


In python the operator in can be used to check wheather an element is in the list. The
operator is given the element to search for on the left and the list to search at on the
right. It returns True if the element was found and False otherwise. If we want to check
if the element doesn't_ exist in the list we add the notoperator such that it will be not
in
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
if 'berlin' in cities:
print("Found")
else:
print("City couldn't be found")
City couldn't be found
banned_users = ['hesham', 'mohamed', 'ali', 'mark', 'aya']
user = 'yehia'
if user not in banned_users:
print("Access granted!")
else:
print("You are banned! ")
Access granted!

else if statements
age = 20
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
Your admission cost is $10.
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

Dictionaries
The type dictionary, defined also as dicts, is a data structure in which each particular
value is associated with a particular label, called a key. A dictionary in Python is a
collection of key-value pairs. Each key is connected to a value, and you can use a key to
access the value associated with that key. A key’s value can be a number, a string, a list,
or even another dictionary. In fact, you can use any object that you can create in Python
as a value in a dictionary.
In Python, a dictionary is wrapped in braces, {}, with a series of key-value pairs inside
the braces, Every key is connected to its value by a colon, and individual key-value pairs
are separated by commas. You can store as many key-value pairs as you want in a
dictionary.
user = {'name':'William', 'age':25, 'city':'London'}
user['name']
'William'

You can add or modify an item to the dictionary:


user['points'] = 1000
print(user)
{'name': 'William', 'age': 25, 'city': 'London', 'points': 1000}
user['age'] = 30
print(user)
{'name': 'William', 'age': 30, 'city': 'London', 'points': 1000}

The previous example involved storing different kinds of information about one object.
You can also use a dictionary to store one kind of information about many objects. For
example, say you want to poll a number of people and ask them what their favorite
color is. A dictionary is useful for storing the results of a simple poll, like this:
favorite_colors = {
'Mohamed': 'blue',
'Sarah': 'orange',
'Ali': 'green',
'Ahmed': 'blue',
}
print(favorite_colors)
{'Mohamed': 'blue', 'Sarah': 'orange', 'Ali': 'green', 'Ahmed': 'blue'}

Looping through dictionaries


To write a for loop for a dictionary, you create names for the two variables that will hold
the key and value in each key-value pair. You can choose any names you want for these
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

two variables. This code would work just as well if you had used abbreviations for the
variable names, like this:
for key,value in favorite_colors.items():
print(key + "'s favorite color is " +value)
Mohamed's favorite color is blue
Sarah's favorite color is orange
Ali's favorite color is green
Ahmed's favorite color is blue

Looping through keys or Values


The keys() method is useful when you don’t need to work with all of the values in a
dictionary. Let’s loop through the favorite_colors dictionary and print the names of
everyone who took the poll:
for name in favorite_colors.keys():
print(name)
Mohamed
Sarah
Ali
Ahmed

The same can be done to loop through dictionary values when keys are not needed:
for color in favorite_colors.values():
print(color)
blue
orange
green
blue

More complex data structures


We can use lists and dictionaries to create more complex datastructures as list of
dictionaries, dictionary inside dictionary, or list inside dictionaries. The following
example shows a list of dictionaries and how to access each element of it.
user_1 = {'name':'William', 'age':25, 'city':'London'}
user_2 = {'name':'Mark', 'age':30, 'city':'New York'}

users_list = [user_1, user_2]

print(users_list[0]['name']) #access the name of the first user in the


list.
print(users_list[1]['name']) #access the name of the second user in the
list.
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

William
Mark

Function definition
def greet_user(username):
"""Display a simple greeting."""
print("Hello, " + username.title() + "!")

greet_user('jesse')
Hello, Jesse!
def average(x):
return sum(x)/len(x)

average([1, 2, 3, 4])
2.5

Arguments' default values


def hello(name, loud=False):

if loud:
print('HELLO, {}'.format(name.upper()))
else:
print('Hello, {}!'.format(name))

hello('Bob')
hello('Fred', loud=True)
Hello, Bob!
HELLO, FRED

Class definition
class Greeter:

# Constructor
def __init__(self, name):
self.name = name # Create an instance variable

# Instance method
def greet(self, loud=False):
if loud:
print('HELLO, {}!'.format(self.name.upper()))
else:
print('Hello, {}'.format(self.name))
Mechatronics Engineering and Automation Program
CSE489: Machine Vision
Lab #02: Python Basics

g = Greeter('Fred') # Construct an instance of the Greeter class


g.greet() # Call an instance method; prints "Hello, Fred"
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
Hello, Fred
HELLO, FRED!

Extending Python using packages


SciPy
Scipy is a set of open-source Python libraries specialized for scientific computing.
Together they constitute a set of tools for calculating and displaying data. It has little to
envy from other specialized environments for calculation and data analysis (such as R
or MATLAB). Among the libraries that are part of the SciPy group, there are three in
particular that will be discussed in the following chapters: - NumPy - matplotlib -
Pandas

NumPy
This library, whose name means numerical Python, constitutes the core of many other
Python libraries that have originated from it. Indeed, NumPy is the foundation library
for scientific computing in Python since it provides data structures and high-performing
functions that the basic package of the Python cannot provide. In fact, NumPy defines a
specific data structure that is an N-dimensional array defined as ndarray. This package
provides some features that will be added to the standard Python: - Ndarray: A
multidimensional array much faster and more efficient than those provided by the basic
package of Python. - Element-wise computation: A set of functions for performing this
type of calculation with arrays and mathematical operations between arrays. - Reading-
writing datasets: A set of tools for reading and writing data stored in the hard disk. -
Integration with other languages such as C, C++, and FORTRAN: A set of tools to
integrate code developed with these programming languages.

Pandas
This package provides complex data structures and functions specifically designed to
make the work on them easy, fast, and effective. This package is the core of data analysis
in Python. The fundamental concept of this package is the DataFrame, a two-
dimensional tabular data structure with row and column labels.

matplotlib
This package is the Python library that is currently most popular for producing plots
and other data visualizations in 2D. Since data analysis requires visualization tools, this
is the library that best suits this purpose.

You might also like