0% found this document useful (0 votes)
6 views85 pages

Python Programming

The document provides an overview of Python programming, including its history, characteristics, and major versions. It covers fundamental concepts such as structured and object-oriented programming, data types, control structures, and basic syntax. Additionally, it discusses installation, IDEs, and provides examples of Python code and functions.

Uploaded by

human.kind.9999
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)
6 views85 pages

Python Programming

The document provides an overview of Python programming, including its history, characteristics, and major versions. It covers fundamental concepts such as structured and object-oriented programming, data types, control structures, and basic syntax. Additionally, it discusses installation, IDEs, and provides examples of Python code and functions.

Uploaded by

human.kind.9999
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

Python Programming

History

Who created the language?
– Guido van Rossum (1989)

Why created this language?
– Hobby!!

Why the name is Python?
– The guy was a fan of a British series “Monty Python”

2
Characteristics

Easy to understand (close to plain English)

Open source

Nice performance compared to development time

Huge community

General purpose language

Interactive and script mode

Dynamically typed

Highly extensible

Structured and object-oriented programming (What?)

3
Structured programming

What is structured programming and how it works?

4
Object Oriented programming

What is object-oriented programming?

5
OOP and Structured programming

OOP vs. Structured (Differences):
– Modification
– Communication
– Access Specifiers (private, public, protected)
– Security
– Code Reusability

6
Python programming language

Three major version
– Version 1.x (94-2000)
– Version 2.x (2000-2020)
– Version 3.x (2008-present)

If it was 10 years ago, I would have recommended you to learn
Python 2.x but now it’s useless to learn it.

You can still see some softwares/codes in Python 2.x

7
Installation, IDEs, Editors, Environment...

How to install Python in different OSes?
– [Link]

Which OS I should use?
– Whatever you are more comfortable with (Yes! it’s cross-platform)

But still there should be some preferences in terms of OS, right?
– No, seriously there is no difference

What is my personal preference?
– Linux

8
IDEs, Editors...

The best IDE/Editor for Python is the one that you are
more comfortable with

You still need to know the difference between an IDE and
an editor.

IDE stands for Integrated Development Environment

An editor is just a simple tool for editing text

9
IDEs, Editors

Popular tools for Python development
– Vim
– PyCharm
– Jupyter
– Ipython
– Python IDLE
– VSCode
– ...
– Or just a simple notepad

10
Vim

11
PyCharm

12
VsCode

13
Let’s get our hands dirty!
Smallest code
1. print("Hello World!")

Now let’s run this code both in command-line and python file

Running the code in Ipython

Write the above code in [Link] file and save it.

14
Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, “MyName”, “myname”,
“MYNAME”, and “Myname” are all different identifiers in Python.

Some conventions for programming

Class names start with an uppercase letter. All other identifiers start with a lowercase letter

Starting an identifier with a single leading underscore indicates that the identifier is private.

Starting an identifier with two leading underscores indicates a strongly private identifier.

If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.

Example of variables: firstName, lastName, dbName

Example of classes: MyClass, DBClass, Vehicle

15
Reserved words

Do NOT use these words as variables…
and exec not assert finally or
break for pass class from print
continue global raise def if yield
return del import try elif in
while else is with except lambda

16
Indentation and comments

Python provides no braces to indicate code blocks (unlike C and C++).
Instead, You should use line indentation to show a code block
# All lines start with “#” are comments
# and are not executable by python interpreter
# You can also specify multiline comments using """ and ending with """
# example:
"""
This is the first line of the multiline comment
This is the second line of the multiline comment
"""
myname = “John”

if myvar == “John”:
print(“Hello ” + myname)
else:
print(“Bye “ + myname)
# end if

is four space characters!

17
Multiple statement in one line is valid but sh**t

Example
– import sys; myname=”John”;print(myname)

The above mentioned code works completely fine.
However the problem is that it’s not nice and readible
which is against the design goal of Python!

18
More about variables and data types
today = "2021-12-12"
myage = 36
myname = "John"
fruits = ["apple", "orange", "banana", "strawberry"]
a,b, c = 1, 1.7, "John"

1. All data in Python language is represented by objects and the relationships between
objects.

2. Each object in python has 3 characteristics:


I) object type ii) object value iii) object identity

* A type could be a number, string, list, tuple

* Object value is a data value that is contained by object

* You can think of object identity as an identity number for that object

19
Mutable vs Immutable

Basic types in Python:
– str, int, float, bool, tuple, set, dict, list, byte array

A mutable object can be changed after it is created

An immutable object can not be changed after creation

We can simple check that using some examples

Before that, let’s see which types are mutable:

Mutable → list, dict, set, byte array

Immutable → int, float, string, tuple, byte

20
Some nice charts

21
Some nice charts

22
Mutable & immutable in action!

23
Mutable & immutable in action!

24
DATA TYPE: STRING

Immutable sequence of Unicode characters

String variables are objects of type str in Python

Therefore, each string variable has a set of methods and properties

Example:
– mystr = “my name is not John Doe”
– len(mystr)→ ?
– [Link]() → ?
– [Link]() → ?
– [Link]() →?
– [Link](n, 0, 10) →?
– [Link](‘oe’) → ?
– [Link](‘My’) → ?

25
DATA TYPE: STRING

Slicing is also possible for strings (in a form of [start:end:step])

Mystr = “My name is not John Doe”

Mystr[0:10] → ?

Mystr[6:10] → ?

Mystr = "abcdefghijklmnopqrstuvwxyz"

Mystr[0::2] → ?

Other methods of strings are (red ones are more important):
find, rfind, isascii, isdecimal, isdigit
islower, isnumeric, isprintable, istitle, isspace
isupper, strip, lstrip, rstrip, replace, rfind, format

26
DATA TYPE: LISTS

Lists are very powerful in Python
– list1 = ['physics', 'chemistry', 1997, 2000];
– list2 = [1, 2, 3, 4, 5 ];
– list3 = ["a", "b", "c", "d"]

Lists are mutable objects (You can change them in-place)

A = [1,2,3,4,5]
A[3] = 7
print(A) → [1,2,3,7,5]

Deleting an element from the list:


a = [1,2,3,4,5]
del a[1]
print(a) → [1,3,4,5]

27
DATA TYPES: LISTS

Lists has lots of functions and methods:
– [Link](obj) → Appends object obj to list
– [Link](obj) → Returns count of how many times obj occurs in list
– [Link](seq) → Appends the contents of seq to list
– [Link](obj) → Returns the lowest index in list that obj appears
– [Link](index, obj) → Inserts object obj into list at offset index (negative and large index!)
– [Link]([i]) → Remove the item at the given position in the list
– [Link]() → Remove all the items from a list
– [Link]() → Reverse the elements of the list in place.

28
IF-ELSE CONDITION

29
Loops (easy version)
1 – While loop
General loops chart 2 – For loop

Loop control statements:


1 – break statement
2 – continue statement
3 – pass statement

30
While loop
while expression:
statement 1
statement 2
.
.
.
statement n

31
For loop
But wait...what is sequence?
Simply, whatever you can iterate is a
sequence (but it’s more than that ).

1 - list is a sequences
2 - range object is also a sequence
3 - tuple is a sequence

Using “in” keyword in a for-loop, we are assigning each element of the fruits to
variable “f” in each iteration.

32
For loop – range function

The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.

Syntax: range(start, stop, step)
– Start: Optional. An integer number specifying at which position to start. Default is 0
– Stop: Required. An integer number specifying at which position to stop (not included).
– Step: Optional. An integer number specifying the incrementation. Default is 1

33
List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list or when you want to do some modification on a data
type that needs a simple if-else expression or a nested for-loop or….

34
List Comprehension

35
List Comprehension

36
List Comprehension
I personally don’t consider
this example as a good
practice but it’s just a
demonstration of list
comprehension!

37
Functions

A function is a block of organized, reusable code that is used to perform a single, related action.

Functions provide better modularity for your application and a high degree of code reusing.

Python gives you many built-in functions like print(), etc. but you can also create your own
functions. These functions are called user-defined functions.

Syntax of a function:


Example:


How to call a function:

38
Assignment

In Math, Greatest Common Divisor (GCD) also known as Highest
Common Factor (HCF) of two integer is the biggest positive integer
that divides each of the integers.

Write a Python3 function that accepts two integers as inputs and
return the HCF.

gcd(a, b) → c

Test your function with the following numbers:
gcd(54, 24) → ?
gcd(180, 48) → ?

39
A very naive answer to GCD problem

40
A better version of GCD with list comprehension

1 - Is this the best version?

2 - Can we do better than this?

41
The best version of GCD?

Before implementing some functions in Python, you need to make
sure that there is no ready-to-use code out there. You don’t want to
re-invent the wheel!

Note: Programming languages are just a tool so that you can achieve
your final goal!

Then what is the best version of GCD?

Well, it’s not fair! We don’t know about this “import” term (I will tell them later).

42
DATA TYPE: Dictionaries

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered, changeable and does not allow duplicates.
fruit_color = {
“apple”: “red”,
“banana”: “yellow”,
“blueberry”: “blue We always have keys and values!
}

Or it can be:
fruit_color = {
“red”: [“apple”, “tomato”, “watermelon”, “cherries”],
“yellow”: [“orange”, “lemon”, “apple”, “banana”],
“blue”: [“blueberry”]
}

Accessing dictionary items:
– fruit_color[“red”] →[“apple”, “tomato”, “watermelon”, “cherries”] (example 2)
– fruit_color[“apple”] → “red” (example 1)

43
DATA TYPE: Dictionaries

Length of the dictionary is the length of the keys!

dict_a = {
“name”: “John”,
“lastname”: “Doe”,
“age”: 23

print(len(dict_a)) → ?


Doing for-loops on dictionaries:

for x in dict_a:
print(x)
What does this program print?
# end for


Question?
– dict_a = {"a": 2, "b": 4, "c": 6, "d": 8}
– Print all the values of dict_a using list comprehension (use format and print function). The output should be like this:
a->2
b->4
c->6
d->8

44
DATA TYPE: DICTIONARIES

Add new key-value to the dictionary:
– dict_a = {“a”: 1, “c”: 3, “d”: 4}
– Adding “b” (as key) and 2 (as value) to dict_a:
dict_a[“b”] = 2
print(dict_a) → ?


Accessing dictionary values (2 methods):
– Direct access: dict_a[“a”] → 1
– Using “get” method: dict_a.get(“a”) → 1
– What are the differences???(try to use the documentation to find out the differences)

Removing Items from dictionary:
– We can use “del” keyword:
del dict_a[“a”]
print(dict_a) → ?
– Or we can use “pop” or “popitem” methods (how?)

45
DATA TYPES: DICTIONARY

Other methods of dict which we should know
– clear, copy, keys, items, get, values, pop, popitem

46
Questions

Questions:
– Write a Python script to concatenate following dictionaries to create a new one

Sample dicts:
– dic1={1:10, 2:20} Final answer should be:
– dic2={3:30, 4:40} {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
– Dic3={5:50,6:60}

– Write a Python function to check whether a given key already exists in a dictionary:
def has_key(key, mydict):
result = <write this part>
return result
# end def
– Write a python function which accepts a number “n” as parameter and create a dictionary
with the keys {1,2,3,4,….,n} and values {1^2, 2^2, 3^2,…., n^2}

47
Questions

Write a Python function that accepts a dictionary as input and check if it’s
empty or not (returns True or False)

Write a Python function that accepts a list as input and check if it’s empty or
not (returns True or False)

Write a Python function that accepts a list as an input and remove the
duplicates from the list and return a new list without duplicats:
– list_a = [1, 2, 4, 4, 2, 3, 4, 5, 56, 8, 3]
– list_b = remove_dups(list_a)
– list_b → [1, 2, 4, 3, 5, 56, 8]

Write a python function to return the result of multiplications of all the items in the list
list_a = [1, 2, 3, 4, 5, 6]
result = multiply_me(list_a)
result → 720

48
DATA TYPES: SET

What is Set?
– Sets are used to store multiple items in a single variable.

A set is a collection which is both unordered and unindexed.
fruits = {"apple", "banana", "cherry"}
print(fruits)


Set items are unordered, unchangeable, and do not allow duplicate values.
– Unordered means that the items in a set do not have a defined order.
– Set items can appear in a different order every time you use them, and cannot be referred to by index or key.


Sets are unchangeable, meaning that we cannot change the items after the set has been created.

Duplicates Not Allowed

fruits = {"apple", "banana", "cherry", "apple"}

print(fruits)

49
DATA TYPE: SET

Access items in set
f = {"apple", "banana", "cherry"}
for x in f:
print(x)


Check if an item is in the set
“apple” in f → returns True


Add new item:
[Link](“orange”)

Removing an item from a set
[Link](“banana”)
[Link]()


Clear the set
[Link]()

50
Set vs. Dict

Think of set as the “set” you have in math
– [Link]

Whatever you can do in math, you can also apply it to Python
sets.
– Union, Intersection, difference,….

Sets can only contain hashable datatypes?
– What is hash and hashable?

Now answer this:
– Can I have something like this? (try it in ipython)

A = set( [ [1,2], [3,4] ] ) → ?

If no, why is that?

51
DATA TYPE: TUPLES

What are tuples?
– Consider it as an unchangeable (immutable) list!
– It just has a different syntax!

my_tuple = (“banana”, “orange”, “apple”)
– Can I change the second item of the above tuple? → ?
– If “no”, why?

Tuples are ordered and allow duplicates (just like lists)

Good news:
– You can use a list of tuples in sets (remember that you can not have a list of lists,
do you remember why?)

Access tuple elements:
– Just like lists we can use brackets: my_tuple[0] or my_tuple[2]

52
Imports and Namespaces

Modules in Python
– Built-in (time, os, sys, random, math, ….)
Check the list: [Link]
– External (how to install an external module?)
– Custom modules (how to write a custom modules?)

How to import modules
– import X
– from X import Y
– import X as xx
– from X import Y as z

53
Python Modules

What is a Module?
– Consider a module to be the same as a code library.
– A file containing a set of functions you want to include in your application.

Let’s create a simple module
– Save the following code in a file called [Link]

def print_me(myname):
print(“***************”)
print(“My name is {}”.format(myname))
print(“***************”)


Now create a second file called [Link] with the following code:
import module1

my_name = “John”
module1.print_me(my_name)

Can I just import the function not the whole module or change the name?
from module1 import print_me as print_name
my_name = “John”
print_name(my_name)

54
Exception and Exception handling

What is an exception?
– [Link]

How to deal with it in Python?
– We can use try...except block

Let’s see an example:
try:
# the code you want to control the error
print(no_var)
except:
# what you want to do if you have error in the first part
print(“We got an error!”)

Another version
try:
# the code you want to control the error
print(no_var)
except Exception as e:
# what you want to do if you have error in the first part
print(“We got an error!”)
print(“this is the error: {}”.format(e))

55
Functions (reminder)

A function is a block of organized, reusable code that is used to perform a single, related action.

Functions provide better modularity for your application and a high degree of code reusing.

Python gives you many built-in functions like print(), etc. but you can also create your own
functions. These functions are called user-defined functions.

Syntax of a function:


Example:


How to call a function:

56
Function Parameters

Arbitrary arguments and arbitrary keyword arguments

Assume that we have a following function:
def my_func(name, lastname):
print(“My name is {}”.format(name))
print(“My lastname is {}”.format(lastname))
# end def

What if we are not sure if the user wants to enter the lastname?
def my_func(name, lastname=”Doe”):
print(“My name is {}”.format(name))
print(“My lastname is {}”.format(lastname))
# end def

57
Function Parameters

Now assume that we have a function which allows user to add more
parameters if he/she wants
def my_func(name, lastname=”Doe”, **kwargs):
print(“My name is {}”.format(name))
print(“My lastname is {}”.format(lastname))
for k in kwargs:
print(“My {} is {}”.format(k, kwargs[k])
# end for
# end def

Now call the function like this: (what is the output?)
my_func("John", "Johnson", age=34, favorite_color="red")

58
Function parameters

Let’s write a multiplication function

The following function is able to calculate the multiplication of two numbers:
def multiply_me(a,b):
return a*b
# end def

And then call it like this:
multiply_me(10, 20) → 200

And what if I call it with three params? or four? or five?
multiply_me(10, 20, 30) → ?

TypeError Traceback (most recent call last)


<ipython-input-23-f28d3a11cff8> in <module>
----> 1 multiply_me(10, 20, 30)

TypeError: multiply_me() takes 2 positional arguments but 3 were given

59
Function parameters

So, how can I modify multiply_me to accept arbitrary number of elements?
def multiply_me(*args):
a=1
for x in args:
a *= x
return a
# end def

And now we can call it like:
multiply_me(10, 20) → ?

multiply_me(10, 20, 30) → ?

multiply_me(10, 20, 30, 1, 1, 1, 16, 1, 1, 1) → ?


Now that we know *args and **kwargs, explain the following syntax:

def new_func(name, lastname=”Doe”, *args, **kwars):


pass # This means do nothing
# end def

60
Some useful packages

Let’s see some of the useful packages
– csv: Write and read tabular data to and from delimited files.
– datetime: Basic date and time types.
– hashlib: Secure hash and message digest algorithms.
– itertools: Functions creating iterators for efficient looping.
– json: Encode and decode the JSON format.
– math: Mathematical functions (sin() etc.).
– multiprocessing: Process-based parallelism.
– os: Miscellaneous operating system interfaces.
– pickle: Convert Python objects to streams of bytes and back.
– random: Generate pseudo-random numbers with various common distributions.
– socket: Low-level networking interface.
– time: Time access and conversions.
– uuid: UUID objects (universally unique identifiers) according to RFC 4122

61
Exercise
Write the following function in Python3.x def proof_of_work(val, p):

“””

We show the goal of “proof_of_work” function with an example: val (string): an arbitrary string e.g., your name or your cat’s name!

p (int): an integer >= 1 (try not to use values bigger than 7)

returns (integer >= 0) → nonce

“””
assume that:
# hint: use md5, hexdigest (both from hashlib library)
val=”sourena” and p=4.

“p” shows the number of leading zero(s) when you calculate the MD5 hash of the “val” concatenated by “nonce”:

md5(val+nonce), nonce=241020 → md5(“sourena241020”) → 0000eb52578bff26c29d7a7ac3394898

the task of proof_of_work function is to find the “nonce” value in a way that the MD5 result of the “val+nonce” has “p” leading zeros.

As you can see in the above example, the final MD5 hash has 4 leading zeros!

Since hashing is a one way function (as we explained), it means that there is no way to calculate the “nonce” value directly unless
you brute-force it in a for-loop!

Now you know why we should not choose big values for “p”. any value greater that 7 may takes from few minutes to hundreds of
years to calculate!!

This problem is very interesting if you know where it is used!

Also try to find the use case if you can.

62
Working with files

Files are very easy to work with in python

Open file Read/write file Close file

– First we need to open the file



Either as binary or text file

Either as read mode or write mode or append mode
– Then we can read/write

One (or more) character/byte at a time or the whole file
– We have to close the file.

63
Working with files

Open the file:

F = open(“[Link]”, ‘r’) # open [Link] for reading in text mode


F = open(“[Link]”, ‘rb’) # open [Link] for reading in binary mode
F = open(“[Link]”, “w”) # open [Link] for writing in text mode
F = open(“[Link]”, “wb”) # open [Link] for writing in binary mode

– Remember that now “F” is a handle to the file



Now we can do read/write based on the mode we opened the file

data = [Link](10) # read 10 characters/bytes from the file with handle F


data = [Link]() # read the whole
l = [Link](data) # write data to the file with handle F


And finally you need to close the file.

[Link]()

64
Working with .CSV and .json files

What is CSV?

What are the use cases of .CSV files?

What is json? Why I should use it?

How to use json?

Python provides two convenient packages to work with .csv and
.json data

“csv” package for reading/writing .csv files.

“json” package for reading/writing json files/data.

65
let’s practice

Create a text file with 5 lines (using bash or whatever).

Open the file in python

Read it line by line and print the line in output

Also print the length of the line.


Create a text file in python.

Write your i)name, ii) lastname, iii) age, each in one line

Close the file in python

Now open the file in bash (or whatever) to see if it works.

66
Python packages

Package: os
– Methods: listdir, getcwd, rmdir, chdir, cpu_count
getuid, mkdir, getpid, curdir, [Link]


Package: sys
– Methods: exit, …
– Properties: argv, path, version, ….

Package: csv
– Modules: [Link], [Link]

Package: json
– Function: loads, dumps, load, dump,….

Package: hashlib
– Methods: md5, hexdigest, sha1, sha256, sha512, ….

Package: time
– Methods: gmtime, mktime, time, sleep, strftime, strptime, …..

Package: math
– Methods: log, log10, pi, tan, sin, cos,….

67
More packages

Package: random

Package: subprocess
– The subprocess module allows us to:

spawn new processes

connect to their input/output/error pipes

obtain their return codes
– It replaces the modules and functions like [Link], [Link]*(), [Link]*()

let’s test it!
– Create a bash file you want to call from your python code
– Add some “sleep” and “ls” function in your bash file
– Save the bash and call it with [Link] and don’t forget to pipe the output.

68
OOP in Python 3.x

What is Object-oriented programming?

Why we should use it?

How it can be done in Python?

69
OOP in Python3.x

Let’s say you have a list of persons who all
have some specific features but the values are
different.

People all have names, lastnames, age, color,
sex, …..

Employees are who have all the features of
people but they also have employee number.
People ? Employee
- name - everything people have
- lastname - employee_number
- age
- color
- sex Do you see the connection here?

70
OOP in Python3.x

We define the class with the keyword “class”
class People():
def __init__(self):
# specify attribute of the instances of the class
pass
# end def

def method1(self):
pass
# end def

def method2(self):
pass
# end def
# end class

71
OOP in Python3.x

Now let’s define two classes:
– People class
– Employee class

Can we do it in a more efficient way?
– Yes! Inheritance

Then let’s do it
– First we define “People” class
– Then the “employee” class inherit everything from People class!

72
Package: Numpy, matplotlib

NumPy is the fundamental package for scientific computing in Python

It is a Python library that provides a multidimensional array object, various derived objects (such as
masked arrays and matrices), and an assortment of routines for fast operations on arrays, including
mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic
linear algebra, basic statistical operations, random simulation and much more.

You can do whatever kind of matrix/vector manipulation with this library.

pre-compiled C code (very fast)

Matplotlib is a library for plotting.
– Developed by John D. Hunter1
– Matplotlib was originally conceived to visualize electrocorticography (ECoG) data
– The author died from cancer treatment complications on August 28, 2012

[1] [Link]

73
Numpy: basics

NumPy’s main object is the homogeneous multidimensional array. It is a
table of elements (usually numbers), all of the same type, indexed by a tuple
of non-negative integers. In NumPy dimensions are called axes.

Importing the library:
– import numpy as np

Method: arange([start,] stop[, step,], dtype=None)
[Link](0,10,2) →array([0, 2, 4, 6, 8])
[Link](0,10) → array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

[Link](0,10, dtype=np.float32) → array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)

74
Array characteristics

Each numpy array/vector has several basic characteristics
– [Link]: the number of axes (dimensions) of the array
– [Link]: the dimensions of the array
– [Link]: the total number of elements of the array
– [Link]: an object describing the type of the elements in the array
– [Link]: the size in bytes of each element of the array

Examples:

import numpy as np
a = [Link](15)
[Link] → ?
[Link] → ?
[Link] → ?
[Link] → ?
[Link] → ?

75
Numpy: Array Creation

There are several ways to create arrays.

you can create an array from a regular Python list or tuple using the array function

The type of the resulting array is deduced from the type of the elements in the sequences

import numpy as np
a = [Link]([2, 3, 4])
[Link] → ?
b = [Link]([1.2, 3.5, 5.1])
[Link] → ?
# What is the difference between ‘a’ and ‘b’ variables?

array transforms sequences of sequences into two-dimensional arrays, sequences of
sequences of sequences into three-dimensional arrays, and so on.

import numpy as np
b = [Link]([(1.5, 2, 3), (4, 5, 6)])
# Try to print b to see how it looks like

76
Numpy: arrays

Let’s do some complex type
import numpy as np
b = [Link]([[1, 2], [3, 4]], dtype=complex)
# Try to print ‘b’ to see the result

create arrays with initial placeholder content
import numpy as np
b = [Link]((3, 4))
# print ‘b’
# also look at [Link], [Link], [Link]

import numpy as np
a = [Link]((2, 3, 4), dtype=np.int16)
# print ‘a’
# also look at [Link], [Link], [Link]
import numpy as np
c = [Link]((2, 3))
# print ‘c’. What are the values of the ‘c’ variable? Are they random?
# also look at [Link], [Link], [Link]

77
Numpy: arrays

[Link]: Return evenly spaced numbers over a specified interval

import numpy as np
a = [Link](0, 2, 9)
# print the result and see the difference between arange and linspace


Let’s draw y = sin(x) in [0, 2π)

from numpy import pi


import math
import numpy as np
from matplotlib import pyplot as plt
x = [Link](0, 2 * pi, 100)
y = [Link]([[Link](i) for i in x])
[Link](x, y)
[Link]()

78
Numpy: Operations

Adding, removing, and sorting elements

[Link](): returns a sorted copy of the array

[Link](): Returns the indices that would sort an array

arr = [Link]([2, 1, 5, 3, 7, 4, 6, 8])


[Link](arr) → ?
[Link](arr) → ?
# What is the difference between sort and argsort?

Concatenating two arrays: [Link]()
a = [Link]([1, 2, 3, 4])
b = [Link]([5, 6, 7, 8])
[Link]((a, b)) → ?
# now let’s see this one
x = [Link]([[1, 2], [3, 4]])
y = [Link]([[5, 6], [7, 8]])
[Link]((x, y), axis=0) → ?
# What is this ‘axis’ argument?
# What if we do something like this?
[Link]((x, y), axis=1) → ?

79
Numpy: Methods

Can we reshape an array?
– Yes, we can

a = [Link](6)
[Link]((2,3))
# print ‘a’ variable to see the result
b = [Link]((2,3))
a[0] = 12
# Now print ‘a’, ‘b’ to see what happened?


Can we reshape an array? (another version)

a = [Link](6)
b = [Link](a, (2,3))
# print ‘a’ variable to see the result (and do the same for ‘b’)
b = [Link](a, (2,3))
a[0] = 12
# Now print ‘a’, ‘b’ to see what happened?

80
Numpy: reshape

Let’s do reshape again
– But first let’s take a look at the documentation
[Link](a, newshape, order='C')

Gives a new shape to an array without changing its data.


The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of
that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and
remaining dimensions.
order{‘C’, ‘F’, ‘A’}, optional

Read the elements of a using this index order, and place the elements into the reshaped array using this
index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index
changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements
using Fortran-like index order, with the first index changing fastest, and the last index changing slowest.
Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only
refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is
Fortran contiguous in memory, C-like order otherwise.

Returns: reshaped_array: ndarray

81
Numpy: reshape

Let’s do reshape again
– Try this
a = [Link](6)
b = [Link](a, newshape=(2, 3), order='C')
c = [Link](a, newshape=(2, 3), order='F')
# print both ‘b’ and ‘c’. What is the difference?

82
Numpy: Indexing and slicing

You can index and slice NumPy arrays in the same ways you can slice Python lists
– Bad news: this means that if you don’t know indexing in python lists, you need to go back and review the slides.
– Good news: If you know python indexing, here is the same as before.

83
Numpy: Indexing and slicing

Slicing base on conditions
a = [Link]([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
b=a<5
c = (a < 9) & (a > 4)
print(b) → ?
print(c) → ?
# Now let’s replace based on some conditions
a[a<5] = -1
print(a) → ?

What if we just want the index of the elements for an specific condition
a = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
c = (a < 9) & (a > 4)
b = [Link](c)
print(b) → ?
# Try to interpret the result (this is very important)

But this is ugly. I want a nicer version of the index
list_of_coordinates= list(zip(b[0], b[1]))
# print ‘list_of_coordinates

84
Numpy: (h/v)stack

create an array from existing data
Import numpy as np
a1 = [Link]([[1, 1], [2, 2]])
a2 = [Link]([[3, 3], [4, 4]])
[Link]((a1, a2)) → ?
[Link]((a1, a2)) → ?


This is interesting (consider an image as a 2D matrix)
Final image
Image 1 Image 2

My-first-name My-Last-name My-first-name


My-Last-name
vstack


And this is your next assignment:
– Create two images of (128, 256) in MS-Paint or Kolourpaint or whatever paint software.
– Stack them like the above example so that the result is one image with both your first ans last name.

85

You might also like