0% found this document useful (0 votes)
3 views

A Short Introduction to Python

This document provides an introduction to Python, covering its installation, basic concepts, and commonly used packages. It highlights Python's characteristics as a high-level, open-source, and object-oriented language, along with its growing popularity. Additionally, it discusses Python's data structures, functions, and the importance of indentation in coding.

Uploaded by

240774
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 views

A Short Introduction to Python

This document provides an introduction to Python, covering its installation, basic concepts, and commonly used packages. It highlights Python's characteristics as a high-level, open-source, and object-oriented language, along with its growing popularity. Additionally, it discusses Python's data structures, functions, and the importance of indentation in coding.

Uploaded by

240774
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/ 37

Introduction to Python

THE RUNDOWN

• Introduction to Python

• Installation – Python and its packages

• Python Basics
THE RUNDOWN

• Introduction to Python

• Installation – Python and its packages

• Python Basics
Introduction to Python

• Python is a high level programming language – similar to C++/Java

• Open Source and has a large community

• Used by a lot of companies around the world

• The popularity of Python has increased significantly in the last


decade
Introduction to Python (Cont’d)

• Interpreted Scripting Language


• Good for writing “quick and dirty” code

• Python is object oriented


• Everything is a Python object

• Different code blocks are grouped together by indentation

• The standard library offers a plethora of very useful functions


THE RUNDOWN

• Introduction to Python

• Installation – Python and its packages

• Python Basics
Installing Python

• The .exe installer can be downloaded from Python’s website:


https://www.python.org/downloads/

• Major releases
• Python 2.x
• Python 3.8.x

• Installing the Python from the above link installs a Python interpreter
along with a (simple) IDE.

• Be sure to check “Add Python to PATH” while installing your preferred


version of Python
Installing Python
A Word about Python IDEs

• There are a few Python IDEs that you can choose from

• Each IDE offers a set of features while some features maybe absent

• Choosing an IDE to work boils down to a matter of personal preference

• Some Python IDEs:


• IDLE
• PyCharm
• Spyder/Anaconda
• Microsoft Visual Studio
Python Packages

• Just like libraries in C++/C#/Java, Python has packages

• Packages have the extension .whl (wheel files)

• Another (easier) way to install Python packages:


• pip
Python Packages (Cont’d)

• Installing a Python package is a matter


of executing a single command in
command prompt (cmd):
• pip install name-of-the-package-you-want-
to-install

• Some packages are used extensively and


even others packages rely on them

This is where “Add Python to PATH” comes in handy


Python Packages (Cont’d)
• There is a package for everything!
Some Commonly Used Python Packages

• NumPy:
• For numerical/mathematical processing pip install numpy
• OpenCV:
• For image processing pip install opencv-python
• Matplotlib:
• For plotting graphs and visualizing data pip install matplotlib
• Pandas:
• For handling/analyzing data pip install pandas
• Scipy:
• For scientific/technical computing pip install scipy
• Scikit-learn:
• For machine learning pip install scikit-learn
Some Commonly Used Python Packages
(Cont’d)
• Some functionality may be replicated across different packages
• Fourier transform present in both OpenCV and NumPy

• Extensive documentation of every class and function in a


package available online
• Code snippets and example code

• Google is your friend


Importing Python Packages

• As discussed earlier, Python packages are akin to C++ libraries

• Allow us to use classes and functions defined in another file

• Three formats of the command:


import somefile #Imports everything from the file
from somefile import * #Imports all the functions. They can be used without the dot
notation
from somefile import className #Imports a specific class and its methods from a file

• We are going to stick with importing everything (import numpy, import


random etc.)
Importing Python Packages

• An alias can be given to a python package while importing it

• The alias acts as a nickname and can be used throughout the code

import numpy as np
import cv2 as opencv
import random as rand
import time
import csv
THE RUNDOWN

• Introduction to Python

• Installation – Python and its packages

• Python Basics
Python Basics

• Indentation controls everything


• A complete lack of braces {} to indicate code blocks
• Instead indentation indicates the start and end of a code
block

• Lines of code that begin a block (often) end in a


colon (:)
• The first line with less indentation is outside the block
• The first line with more indentation is inside the block

• A newline (Return) is used to indicate the end of a


single line of code
Python Basics

• Variables:
• No need to explicitly declare a variable (data type)
• However, variables need to be initialized
Variable1 = 4.5 Variable2 = “Fortis Fortuna Audivat”
Variable3 = True Variable4 = None
• Conditional Statements:
if counter == 10:
…do something…
elif:
…do something else…
else:
…do something else entirely…
Python Basics

• Repetition Structures:
• for and while loops are used most commonly
• The body of the loop is indented one level more the loop control statement
While loop For loop
while (condition): for counter in range (10):
…do something…
…do something…
condition increment/decrement

• Range is a built in function that produces an “iterable” that is used for the
total number of the iterations in for loop.
Python Basics

• Comments:
• Comments are started with #
• Block comments (also known as Documentation Strings) are encased within “““ ”””
• A good practice to give some details of what a particular block of code does using
documentation string
Python Basics: Lists, Tuples and Dictionaries

• Built-in data structures in Python:


• List
• Tuple
• Dictionary

• Used a lot due to their utility and flexibility

• Built-in methods provide a handy way to perform simple operations quickly


on these data structures
Python Basics: Lists

• Lists, put simply, are like arrays

• The simplest representation of a list can be visualized as a 1-D array


• Represented by brackets
my_list1 = [1,2,3,4,5]
my_list2 = []

• Lists can also be heterogeneous


my_list3= [1,2, “ Today is Saturday”, 3, 4, 5, “6”]
Python Basics: Lists (Cont’d)

• Indexing starts at 0
print(my_list1[0]) #1

• Other lists (sub-lists) can be an element of a list


my_list4 = [[1,2],[3,4],[5,6],[7,8]]
print(my_list4[0]) #[1,2]
print(my_list4[3][0]) #7

• Lists are mutable – meaning that the value of any element (or sub-element)
can be changed at a later stage
• my_list4[3]= [10,12]
• my_list4 = [[1,2],[3,4],[5,6],[10,12]]
Python Basics: Lists (Cont’d)

• List methods provide a handy way to manipulate a list


my_list.append(4) #Adds 4 to the last of the list
my_list.extend([1,2,3,4]) #Adds the list passed to this method to the first list
my_list.insert(2,4) #Inserts 4 at index 2 (Elements after index 2 are pushed
back one index)
my_list.remove(4) #Removes the first occurrence of 4 in the list
my_list.index(4) #Returns the index of the first occurrence of 4 in the list
my_list.sort() #Sorts a list in ascending order
my_list.reverse() #Reverses the order of the elements of the list
Python Basics: Tuples
• A tuple represents a sequence – just like a list
my_tuple1 = (1, 2)
my_tuple2 = (1,2, “Harry Potter”)
my_tuple3 = (4,)
my_tuple4 = ()

• Tuples are immutable – meaning that their value cannot be changed after it
has been declared

• Tuples can be homogenous or heterogeneous

• Tuples have structure, lists have order


Python Basics: Dictionary
• A dictionary in Python stores an element against a particular key

• Dictionaries are unordered and a key is required to retrieve or insert an


element

• Quite similar to hash tables

• Like lists, dictionaries are mutable

• Dictionary keys can only be immutable so that they don’t change over time
Python Basics: Dictionary (Cont’d)
• To declare a dictionary, we use braces
my_dictionary1 = { }
my_dictionary2 = {1 : “Asad”, 2 : “Saad”, 3 : “Sara” } #Each pair is in key : data form
my_dictionary3 = { ‘Batman’ : ‘Bruce Wayne’, ‘Superman’ : ‘Clark Kent’}

• To retrieve some data from a dictionary, we need to use its key


my_dictionary2[1] #Prints Asad

• To add data to a dictionary we need to use the key again


my_dictionary3['Ironman']='Tony Stark‘ #my_dictionary3 = {'Batman': 'Bruce Wayne',
'Superman': 'Clark Kent', 'Ironman': 'Tony Stark'}
Python Basics: Shallow Copy & Deep Copy

• By default, Python makes a shallow copy of a list or a dictionary


nums = [1,2,3,4]
tri = nums

• Any change to nums or tri will change the list that exists in the memory

• Python needs to be told explicitly to create a copy of a list or a dictionary


Python Basics: Shallow Copy & Deep Copy
(Cont’d)
• In order to create a deep copy, we need to rely on a Python package

• my_dictionary5=copy.deepcopy(my_dictionary3)

The above line of code creates a deep copy of my_dictionary3 and stores it in
my_dictionary5

Any changes to either one of the dictionaries defined above with be restricted to those
dictionaries only
Python Basics: Useful In-Built Functions
Python Basics: (Some) Useful In-Built Functions

• len(my_list) #Returns the length of my_list

• range(starting_point,terminating_point,increment/decrement)
• At least, the terminating point needs to be provided
• range produces an open ended interval
• The last element in the list produced by range(10) will be 9

• max(my_list)/min(my_list) #returns the maximum/minimum element in the list

• float(“19”)/int(“19”) #Typecasts a string into float/integer

• sum(my_list) #Sums the whole list together


Python Basics: Indexing and Slicing

• We are already aware that indexing starts at 0 in Python

• A “slice” is a sub-portion of a list or a tuple --- similar to slicing in MATLAB

• A list can be sliced in the following way:


my_list1[0:5] #The first 5 elements (0,1,2,3,4) will be selected
my_list1[0:5:2] #Every second element (0,2,4) will be selected
Python Basics: Functions

• def keyword is used to indicate a function

• The body of a function is indented at one more


level than the function prototype

• Functions in Python can return multiple values


Different Ways, Same Outcome

• Multiple ways to accomplish the same thing in Python

• Keeping with the spirit of “quick and dirty” scripting, the goal is to get
the job done and then worry about optimization
QUESTIONS?

You might also like