Introduction to Python Programming

Sachin Joshi

Research Computing

Basics of Python Programming

  • Brief Introduction
  • Variables
  • Data Types
    • Strings
    • Lists
    • Dictionaries
    • Tuples
  • Operators and Operands
    • Arithmetic
    • Comparison
    • Logical
  • Conditonal Execution
  • Looping Statements
    • for
    • while
  • Control Statements
    • break
    • continue
    • pass
  • Functions
  • File Handling
  • Numpy Arrays

Python - The new generation Language

  • A general-purpose programming language (1980) by Guido van Rossum
  • Emphasis on code readability, shorter codes, ease of writing
  • Dynamically typed - No need to declare anything
  • Automatic memory management
  • Interpreted - There are no separate compilation and execution steps like C and C++.
  • Free (developed under an OSI-approved open-source license) and portable

Python - Fastest Growing Programming Language

  • Presence of third-party modules
  • Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) and frameworks
  • Open source and supportive community development
  • Easy to learn and User-friendly data structures
  • Widely used in Big Data and Machine Learning
  • Web Development(Full stack framworks - Django, Pyramid, TurboGears, etc)

Why Python Best-Suited for Machine Learning?

  • According to Forbes, Machine learning patents grew at a 34% rate between 2013 and 2017
  • And Python is the primary programming language used for much of the research and development in Machine Learning

  • Python has multiple Libraries and Frameworks
    • Keras is an open-source library that is particularly focused on experimentation with deep neural networks.
    • TensorFlow is a free software library that is used for many machine learning applications like neural networks.
    • Scikit-learn is a free software library for Machine Learning that various classification, regression and clustering algorithms.

Python vs Other language

Python Java
Interpreted Language Compiled Language
Slower, type of data is determined at runtime Faster, less time to execute the code
Concise Verbose
Uses Identation for structuring code Uses braces for code structuring
Best for AI, ML IoT Embedded and cross-platform applications

Installing Python

  • Many PCs and Macs will have python already installed.
  • To check if you have python installed:
    • Open Command Line (cmd.exe) on Windows
    • Open Terminal on Linux or Mac
  • and run the following command
    • python --version
  • If you find that you do not have python installed on your computer, then you can download it for free from the following website: https://www.python.org/

Anaconda Python Distribution

  • Anaconda Python distribution is the most popular platform for Python
  • It provides

    • a convenient install procedure for over 1400 Data Science libraries for Python and R
    • conda to manage your packages, dependencies, and environments
    • anaconda navigator: a desktop portal to install and launch applications and editors including Jupyter, RStudio, Visual Studio Code, and Spyder
  • Visit https://go.lehigh.edu/linux to use Anaconda (and other Linux software) installed and maintained by the Research Computing group on your local Linux laptop or workstation

Variables and Types

  • A variable is a name that refers to a value.
  • An assignment statement creates new variables and gives them values
In [1]:
message = 'And now for something completely different'
n = 17
pi = 3.1415926535897931
  • The first assigns a string to a new variable named message
  • the second gives the integer 17 to n
  • the third assigns the (approximate) value of $\pi$ to pi

  • To display the value of a variable, you can use a print function

Printing to screen

  • Python has a built-in function, print to write output to standard output or screen
In [127]:
print("Hello World!")
print(message)
Hello World!
And now for something completely different
  • The type of a variable is the type of the value it refers to.
In [3]:
type(message)
Out[3]:
str
In [4]:
type(n)
Out[4]:
int
In [5]:
type(pi)
Out[5]:
float

Reading from screen

  • Python has a built-in function, input to read input from standard input or screen
In [6]:
input('What is your name: ')
What is your name: Sachin Joshi
Out[6]:
'Sachin Joshi'

Variable names

  • Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter.
  • The underscore character (_) can appear in a name.
    • It is often used in names with multiple words, such as my_name
  • If you give a variable an illegal name, you get a syntax error
In [8]:
76trombones = 'big parade'
  File "<ipython-input-8-ee59a172c534>", line 1
    76trombones = 'big parade'
              ^
SyntaxError: invalid syntax
In [9]:
class = 'Advanced Theoretical Zymurgy'
  File "<ipython-input-9-73fc4ce1a15a>", line 1
    class = 'Advanced Theoretical Zymurgy'
          ^
SyntaxError: invalid syntax

Reserved Words

  • Python has 31 keywords or reserved words that cannot be used for variable names.
and del for is raise
as elif from lambda return
assert else global not try
break except if or while
class exec import pass with
continue finally in print yield
def
  • Use an editor that has syntax highlighting, wherein python functions have a different color
    • See previous slides, variable names are in the normal color i.e. black while reserved keywords, for e.g. class, are in green

Python Data Types

  • Data types are the classification or categorization of data items.
  • It represents the kind of value that tells what operations can be performed on a particular data.
  • Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
  • Following are the standard or built-in data type of python:

    • Numeric
    • Sequence Type
    • Boolean
    • Set
    • Dictionary

Strings

  • In Python, Strings are arrays of bytes representing Unicode characters.
  • A string is a collection of one or more characters put in a single quote, double-quote or triple quote.
  • In python there is no character data type, a character is a string of length one.
  • It is represented by str class.
In [10]:
# Creating a String with single Quotes  

String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")  
print(String1)  
String with the use of Single Quotes: 
Welcome to the Geeks World
In [12]:
# Creating a String with double Quotes  

String1 = "I'm a Geek"
print("String with the use of Double Quotes: ")  
print(String1)  
print(type(String1)) 
String with the use of Double Quotes: 
I'm a Geek
<class 'str'>
In [13]:
# Creating String with triple Quotes 
# allows multiple lines  

String1 = '''Geeks  
            For  
            Life'''
print("Creating a multiline String: ")  
print(String1) 
Creating a multiline String: 
Geeks  
            For  
            Life
  • If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type.
    • If a string is to contain a single quote, delimit it with double quotes and vice versa
In [14]:
print("This string contains a single quote (') character.")
print('This string contains a double quote (") character.')
This string contains a single quote (') character.
This string contains a double quote (") character.
  • Alternatively, escape the quote character using a backslash

Escape Sequencing in Python

  • While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these.
  • Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print such Strings.
  • Escape sequences start with a backslash and can be interpreted differently.
  • If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and same is done for Double Quotes.
Escape Sequence Escaped Interpretation
\' Literal single quote (') character
\" Literal double quote (") character
\newline Newline is ignored
\\ Literal backslash () character
\n ASCII Linefeed (LF) character
\r ASCII Carriage Return (CR) character
\t ASCII Horizontal Tab (TAB) character
\v ASCII Vertical Tab (VT) character
In [15]:
print('This string contains a single quote (\') character.')
print("This string contains a double quote (\") character.")
This string contains a single quote (') character.
This string contains a double quote (") character.

String Operations

  • Python strings are immutable i.e. elements of a String cannot be changed once it has been assigned.
  • Only new strings can be reassigned to the same name.
  • Every element of a string can be referenced by their index (first index is 0)
In [16]:
str1="Hello"
str2="Hello"
print(id(str1),id(str2))
1495599709240 1495599709240
  • str1 and str2 both refer to the same memory location
  • If you modify str1, it creates a new object at a different memory location
In [17]:
str1+=", Welcome to LTS Seminars"
print(str1, "\n", id(str1), "\n", id(str2))
Hello, Welcome to LTS Seminars 
 1495599788080 
 1495599709240
In [18]:
# Printing First character  

print("\nFirst character of String is: ")  
print(str1[0]) 
First character of String is: 
H
In [19]:
# Printing Last character  

print("\nLast character of String is: ")  
print(str1[-1])  
Last character of String is: 
s
  • + operator is used to concatenate string and * operator is a repetition operator for string.
In [20]:
s = "So, you want to learn Python? " * 4
print(s)
So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? 
  • You can take subset of string from original string by using [ ] operator, also known as slicing operator.
  • s[start:end] will return part of the string starting from index start to index end - 1
In [21]:
s[3:15]
Out[21]:
' you want to'
  • start index and end index are optional.
  • default value of start index is 0
  • default value of end is the last index of the string
In [22]:
s[:3]
Out[22]:
'So,'
In [23]:
s[15:]
Out[23]:
' learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '
In [24]:
s[:]
Out[24]:
'So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '

String functions

  • ord(): returns the ASCII code of the character.
  • chr(): function returns character represented by a ASCII number.
  • len(): returns length of the string
  • max(): returns character having highest ASCII value
  • min(): returns character having lowest ASCII value
In [25]:
len(s)
Out[25]:
120

Lists

  • Lists are just like the arrays, declared in other languages.
  • Lists need not be homogeneous always which makes it the most powerful tool in Python.
  • A single list may contain DataTypes like Integers, Strings, as well as Objects.
  • Lists are mutable, and hence, they can be altered even after their creation.
  • List in Python are ordered and have a definite count.
  • Indexing of a list is done with 0 being the first index.
  • Allows duplicating of elements in the list.
  • It is represented by list class.
  • Lists in Python can be created by just placing the sequence inside the square brackets [ ]
In [26]:
# Creating a List  
List = []  
print("Intial blank List: ")  
print(List)  
Intial blank List: 
[]
In [27]:
# Creating a List with the use of multiple values  
List = [10, 20, 30, 40]  
print("List containing multiple values: ")
print(List)
print("Fist Element", List[0])   
print("Third Element", List[2]) 
List containing multiple values: 
[10, 20, 30, 40]
Fist Element 10
Third Element 30
In [28]:
# Creating a Multi-Dimensional List  
# (By Nesting a list inside a List)  
List = ['spam', 2.0, 5, [10, 20]]  
print("Multi-Dimensional List: ")  
print(List)  
Multi-Dimensional List: 
['spam', 2.0, 5, [10, 20]]

List Operations

Adding Elements to a List

  • Elements can be added to the List by using built-in append() function.
  • Only one element at a time can be added to the list by using append() method.
  • insert(): this method is used for addition of element at the desired position.
  • extend(): this method is used to add multiple elements at the same time at the end of the list.
In [29]:
List = [5, 10, 15]  
print("Initial List: ")  
print(List)  
Initial List: 
[5, 10, 15]
In [30]:
# Addition of Elements in the List  
List.append(20)  
List.append(25)  
List.append(15)  
print("List after Addition of Three elements: ")  
print(List)  
List after Addition of Three elements: 
[5, 10, 15, 20, 25, 15]
In [31]:
# Addition of Element at specific Position (using Insert Method)  
List.insert(3, 12)  
List.insert(0, 'Geeks')  
print("List after performing Insert Operation: ")  
print(List)  
List after performing Insert Operation: 
['Geeks', 5, 10, 15, 12, 20, 25, 15]
In [32]:
# Addition of multiple elements to the List at the end (using Extend Method)  
List.extend([8, 'Geeks', 'Always'])  
print("List after performing Extend Operation: ")  
print(List)  
List after performing Extend Operation: 
['Geeks', 5, 10, 15, 12, 20, 25, 15, 8, 'Geeks', 'Always']
In [33]:
# You can reference a section of the list using a slice operator
List[3:7]
Out[33]:
[15, 12, 20, 25]

Removing Elements from the List

  • Elements can be removed from the List by using built-in remove() function but an Error arises if element doesn’t exist in the set.
  • Pop() function can also be used to remove and return an element from the set, but by default it removes only the last element of the set, to remove element from a specific position of the List, index of the element is passed as an argument to the pop() method.
In [34]:
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]  
print("Intial List: ")  
print(List)  
Intial List: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
In [35]:
# Removing elements from List using Remove() method  
List.remove(5)  
List.remove(6)  
print("List after Removal of two elements: ")  
print(List) 
List after Removal of two elements: 
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
In [36]:
x = List.pop()  
print("List after popping an element: ")  
print(List)  
List after popping an element: 
[1, 2, 3, 4, 7, 8, 9, 10, 11]
In [37]:
print(x)
12
In [38]:
# Removing element at a specific location from the Set using the pop() method  
y = List.pop(2)  
print("List after popping a specific element: ")  
print(List) 
List after popping a specific element: 
[1, 2, 4, 7, 8, 9, 10, 11]
In [39]:
print(y)
3
In [40]:
# Use del if you do not need the removed value
del List[1]
print(List)
[1, 4, 7, 8, 9, 10, 11]
In [41]:
# To remove more than one element, you can use del with a slice index
del List[1:4]
print("List after deleting more than 1 element:")
print(List)
List after deleting more than 1 element:
[1, 9, 10, 11]

Lists and Strings

  • A string is a sequence of characters and a list is a sequence of values
  • list of characters is not the same as a string.
  • To convert from a string to a list of characters, you can use list
In [42]:
s = 'spam'
t = list(s)
print(t)
['s', 'p', 'a', 'm']
  • The list function breaks a string into individual letters.
  • If you want to break a string into words, you can use the split method
In [43]:
s = 'pining for the fjords'
t = s.split()
print(t)
['pining', 'for', 'the', 'fjords']
In [44]:
# An optional argument called a delimiter specifies which characters to use as word boundaries

s = 'spam-spam-spam'
delimiter = '-'
s.split(delimiter)
Out[44]:
['spam', 'spam', 'spam']
  • join is the inverse of split.
  • It takes a list of strings and concatenates the elements.
  • join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter
In [45]:
t = ['pining', 'for', 'the', 'fjords']
delimiter = ':'
delimiter.join(t)
Out[45]:
'pining:for:the:fjords'

Dictionaries

  • Dictionary in Python is an unordered collection of data values, used to store data values like a map.
  • Dictionary holds key:value pair.
  • Key-value is provided in the dictionary to make it more optimized.
  • Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
  • Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
  • Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
  • Dictionary can also be created by the built-in function dict().
  • In Python, a Dictionary can be created by placing a sequence of elements within curly { } braces, separated by ‘comma’.
In [46]:
# Creating an empty Dictionary  
Dict = {}  
print("Empty Dictionary: ")  
print(Dict) 
Empty Dictionary: 
{}
In [48]:
# Creating a Dictionary with Integer Keys  
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}  
print("Dictionary with the use of Integer Keys: ")  
print(Dict)  
Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
In [49]:
# Creating a Dictionary with dict() method  
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})  
print("Dictionary with the use of dict(): ")  
print(Dict) 
Dictionary with the use of dict(): 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
In [50]:
# Creating a Dictionary with each item as a Pair  
Dict = dict([(1, 'Geeks'), (2, 'For')])  
print("Dictionary with each item as a pair: ")  
print(Dict) 
Dictionary with each item as a pair: 
{1: 'Geeks', 2: 'For'}
In [51]:
# Creating a Dictionary with Mixed keys  
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}  
print("Dictionary with the use of Mixed Keys: ")  
print(Dict) 
Dictionary with the use of Mixed Keys: 
{'Name': 'Geeks', 1: [1, 2, 3, 4]}

Dictionary Operations

Adding Elements to a Dictionary

  • One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
  • Updating an existing value in a Dictionary can be done by using the built-in update() method.
  • While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.
In [52]:
# Creating an empty Dictionary  
Dict = {}  
print("Empty Dictionary: ")  
print(Dict)  
Empty Dictionary: 
{}
In [53]:
# Adding elements one at a time  
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("Dictionary after adding 3 elements: ")  
print(Dict) 
Dictionary after adding 3 elements: 
{0: 'Geeks', 2: 'For', 3: 1}
In [54]:
# Updating existing Key's Value  
Dict[2] = 'Welcome'
print("Updated key value: ")  
print(Dict)
Updated key value: 
{0: 'Geeks', 2: 'Welcome', 3: 1}

Accessing Elements from a Dictionary

  • In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
  • There is also a method called get() that will also help in accessing the element from a dictionary.
In [55]:
# Creating a Dictionary   
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}  
    
# accessing a element using key  
print("Accessing a element using key:")  
print(Dict['name'])
Accessing a element using key:
For
In [56]:
# accessing a element using get() method  
print("Accessing a element using get:")  
print(Dict.get(3)) 
Accessing a element using get:
Geeks
In [57]:
# The len function returns the number of key-value pairs
len(Dict)
Out[57]:
3

Removing Elements from Dictionary

  • In Python Dictionary, deletion of keys can be done by using the del keyword.
  • Using del keyword, specific values from a dictionary as well as whole dictionary can be deleted.
  • Other functions like pop() and popitem() can also be used for deleting specific values and arbitrary values from a Dictionary.
  • All the items from a dictionary can be deleted at once by using clear() method.
In [58]:
# Initial Dictionary  
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',  
        'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},  
        'B' : {1 : 'Geeks', 2 : 'Life'}}  
print("Initial Dictionary: ")  
print(Dict)  
Initial Dictionary: 
{5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
In [59]:
# Deleting a Key value  
del Dict[6]  
print("Deleting a specific key: ")  
print(Dict)  
Deleting a specific key: 
{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
In [60]:
# Deleting a Key using pop()  
x = Dict.pop(5)  
print("Popping specific element: ")  
print(Dict) 
Popping specific element: 
{7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
In [61]:
print(x)
Welcome
In [62]:
# Deleting an arbitrary Key-value pair using popitem()  
y = Dict.popitem()  
print("Pops an arbitrary key-value pair: ")  
print(Dict)  
Pops an arbitrary key-value pair: 
{7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}}
In [63]:
print(y)
('B', {1: 'Geeks', 2: 'Life'})
In [64]:
# Deleting entire Dictionary  
Dict.clear()  
print("Deleting Entire Dictionary: ")  
print(Dict)  
Deleting Entire Dictionary: 
{}
In [65]:
# You can loop through keys or values by using the keys and values functions

eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

print("Looping through the Keys:")
for keys in eng2sp.keys():
    print(keys)

print("\n")    
print("Looping through the Values:")
for vals in eng2sp.values():
    print(vals)
Looping through the Keys:
one
two
three


Looping through the Values:
uno
dos
tres

Tuple

  • Tuple is an ordered collection of Python objects much like a list.
  • The sequence of values stored in a tuple can be of any type, and they are indexed by integers.
  • The important difference between a list and a tuple is that tuples are immutable.
  • Also, Tuples are hashable whereas lists are not.
  • It is represented by tuple class.
  • In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence.
  • Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
In [66]:
# Creating an empty tuple  
Tuple1 = ()  
print("Initial empty Tuple: ")  
print (Tuple1)  
Initial empty Tuple: 
()
In [67]:
# Creating a Tuple with the use of Strings  
Tuple1 = ('Geeks', 'For')  
print("Tuple with the use of String: ")  
print(Tuple1)
Tuple with the use of String: 
('Geeks', 'For')
In [68]:
# Creating a Tuple with the use of list  
list1 = [1, 2, 4, 5, 6]  
print("Tuple using List: ")  
print(tuple(list1))  
Tuple using List: 
(1, 2, 4, 5, 6)
In [69]:
# Creating a Tuple with the use of built-in function  
Tuple1 = tuple('Geeks')  
print("Tuple with the use of function: ")  
print(Tuple1) 
Tuple with the use of function: 
('G', 'e', 'e', 'k', 's')
In [70]:
# Creating a Tuple with nested tuples  
Tuple1 = (0, 1, 2, 3)  
Tuple2 = ('python', 'geek')  
Tuple3 = (Tuple1, Tuple2)  
print("Tuple with nested tuples: ")  
print(Tuple3) 
Tuple with nested tuples: 
((0, 1, 2, 3), ('python', 'geek'))

Accessing Elements of a Tuple

  • In order to access the tuple items refer to the index number.
  • Use the index operator [ ] to access an item in a tuple.
  • The index must be an integer.
  • Nested tuple are accessed using nested indexing.
In [71]:
tuple1 = tuple([1, 2, 3, 4, 5]) 
  
# Accessing element using indexing 
print("Frist element of tuple") 
print(tuple1[0]) 
Frist element of tuple
1
In [72]:
# Accessing element from last (negative indexing) 
print("Last element of tuple") 
print(tuple1[-1]) 
  
print("Third last element of tuple") 
print(tuple1[-3]) 
Last element of tuple
5
Third last element of tuple
3

Deleting/Updating Elements of Tuple

  • In python, deletion or Updation of a tuple is not allowed.
  • This will cause an error because updating or deleting from a tuple is not supported.
  • This is because tuples are immutable, hence elements of a tuple cannot be changed once it has been assigned.
  • Only new tuples can be reassigned to the same name.
In [73]:
tuple1 = tuple([1, 2, 3, 4, 5]) 
print("Initial tuple") 
print(tuple1)
Initial tuple
(1, 2, 3, 4, 5)
In [74]:
# Updating an element of a tuple 
tuple1[0] = -1
print(tuple1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-74-50fd515ea2c7> in <module>()
      1 # Updating an element of a tuple
----> 2 tuple1[0] = -1
      3 print(tuple1)

TypeError: 'tuple' object does not support item assignment
In [75]:
# Deleting an element from a tuple 
del tuple1[2] 
print(tuple1) 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-75-e2d0b616135c> in <module>()
      1 # Deleting an element from a tuple
----> 2 del tuple1[2]
      3 print(tuple1)

TypeError: 'tuple' object doesn't support item deletion
In [76]:
# You can’t modify the elements of a tuple, but you can replace one tuple with another

tuple1 = ('A',) + tuple1[0:]
print(tuple1)
('A', 1, 2, 3, 4, 5)

Operators and Operands

  • Operators are special symbols that represent computations like addition and multiplication.
  • The values the operator is applied to are called operands.

Arithmetic Operators

Operator Meaning Example
+ (unary) Unary Positive +a
+ (binary) Addition a + b
- (unary) Unary Negation -a
- (binary) Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus a % b
// Floor Division (also called Integer Divison a // b
** Exponentiation a ** b
In [77]:
a = 4
b = 3

print(a * b)
print(a / b)
print(3 * a // b)
print(2 * a % b)
print(a ** b)
12
1.3333333333333333
4
2
64

Comparison Operators

  • Can be used for both numbers and strings
  • Python compares string lexicographically i.e using ASCII value of the characters
Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
< Less than a < b
<= Less than or equal to a <= b
> Greater than a > b
>= Greater than or equal to a >= b
In [78]:
a = 10
b = 20
print(a == b)
False
In [79]:
c = 'Hi'
d = 'hi'
print(c == d)
print( c < d)
print(ord('H'),ord('h'),ord('i'))
False
True
72 104 105
  • Consider two strings 'Hi' and 'HI' for comparison.
  • The first two characters ( H and H ) are compared.
  • Since 'i' has a greater ASCII value (105) than 'I' with ASCII value (73), 'Hi' is greater than 'HI'
In [80]:
'HI' < 'Hi'
Out[80]:
True

Logical Operators

Operator Example Meaning
not not x True if x is False
False if x is True
(Logically reverses the sense of x)
or x or y True if either x or y is True
False otherwise
and x and y True if both x and y are True
False otherwise
In [81]:
x = 5
y = 10

print(x > 6 or y < 15)
print(x < 10 and y > 5)
True
True

Conditional Execution

  • Conditional Statements gives the programmer an ability to check conditions and change the behavior of the program accordingly.
  • The simplest form is the if statement:

Image Not Found

Syntax: if condition: statements

  • There may be a situation where you want to execute a series of statements if the condition is false
  • Python provides an if ... else ... conditional
  • Syntax if condition: statments_1 else: statements_2
In [82]:
x = 13

if x % 2 == 0:
    print('x is even')
else:
    print('x is odd')
x is odd
  • Sometimes there are more than two possibilities and we need more than two branches.
  • Python provides a if ... elif ... else conditional
  • Syntax if condition1: statements_1 elif condition2: statements_2 else statements_3
In [83]:
y = 10
if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')
x is greater than y
In [84]:
if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')
x is greater than y
In [85]:
# Nested If

if 0 < x:
    if x < 10:
        print('x is a positive single-digit number.')
    else:
        print('x is not a positive single-digit number.')
        
x is not a positive single-digit number.

Loopoing Statements

  • There may be a situation when you need to execute a block of code a number of times.

  • A loop statement allows us to execute a statement or group of statements multiple times.

Image Not Found

for loops

  • The for statement has the ability to iterate over the items of any sequence, such as a list or a string
  • If a sequence contains an expression list, it is evaluated first.
  • Then, the first item in the sequence is assigned to the iterating variable iterating_var.
  • Next, the statements block is executed.
  • Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.

for iterating_var in sequence: statements(s)

In [86]:
fruits = ['banana', 'apple',  'mango']
for fruit in fruits: 
   print ('Current fruit :', fruit)
Current fruit : banana
Current fruit : apple
Current fruit : mango
In [87]:
for letter in 'Hola': 
   print('Current Letter :', letter)
Current Letter : H
Current Letter : o
Current Letter : l
Current Letter : a

range function

  • The built-in function range() iterates over a sequence of numbers.
In [88]:
range(5)
Out[88]:
range(0, 5)
In [89]:
list(range(5))
Out[89]:
[0, 1, 2, 3, 4]
In [90]:
for var in list(range(5)):
    print(var)
0
1
2
3
4
In [91]:
for index in range(len(fruits)):
   print ('Current fruit :', fruits[index])
Current fruit : banana
Current fruit : apple
Current fruit : mango

while loop

  • A while loop statement repeatedly executes a target statement as long as a given condition is true.
  • Here, statement(s) may be a single statement or a block of statements with uniform indent.
  • The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
  • When the condition becomes false, program control passes to the line immediately following the loop.

while expression: statement(s)

In [92]:
number = int(input('Enter any integer: '))

fact = count = 1
while (count <= number ):
    fact = count * fact
    count += 1
print('Factorial of %d is %d' % (number, fact))
Enter any integer: 6
Factorial of 6 is 720
In [93]:
count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")
0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5

Control Statements

  • Using loops in Python automates and repeats the tasks in an efficient manner.
  • But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition.
  • These can be done by loop control statements. Loop control statements change execution from its normal sequence.
  • Python supports the following control statements.

    • Break statement
    • Continue statement
    • Pass statement

Break Statement

  • The break statement is used to terminate the loop or statement in which it is present.
  • After that, the control will pass to the statements that are present after the break statement, if available.
  • If the break statement is present in the nested loop, then it terminates only those loops which contains break statement.

Flow Chart - Break

In [94]:
s = 'geeksforgeeks'
# Using for loop  
for letter in s:  
    print(letter)  
    # break the loop as soon it sees 'e' or 's'  
    if letter == 'e' or letter == 's':  
        break
    
print("Out of for loop")  
g
e
Out of for loop

Continue Statement

  • continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
  • As the name suggests the continue statement forces the loop to continue or execute the next iteration.
  • When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.

Flow Chart - Continue

In [95]:
for i in range(1, 11):  
    
    # If i is equals to 6, continue to next iteration without printing   
    if i == 6:  
        continue
    else:  
        # otherwise print the value of i  
        print(i) 
1
2
3
4
5
7
8
9
10

Pass Statement

  • As the name suggests pass statement simply does nothing.
  • The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
  • It is like null operation, as nothing will happen is it is executed.
  • Pass statement can also be used for writing empty loops.
  • Pass is also used for empty control statement, function and classes.
In [97]:
for letter in 'geeksforgeeks': 
    pass
print ('Last Letter :', letter) 
Last Letter : s

Functions in Python

  • Function is a set of statements that take inputs, do some specific computation and produces output.
  • The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
  • Python provides built-in functions like print(), etc. but we can also create your own functions.
In [98]:
x = 10
print(x)
10

Built-in Type Conversion Functions

Function Description
ascii() Returns a string containing a printable representation of an object
bin() Converts an integer to a binary string
bool() Converts an argument to a Boolean value
callable() Returns whether the object is callable (i.e., some kind of function)
chr() Returns string representation of character given by integer argument
complex() Returns a complex number constructed from arguments
float() Returns a floating-point object constructed from a number or string
hex() Converts an integer to a hexadecimal string
int() Returns an integer object constructed from a number or string
oct() Converts an integer to an octal string
ord() Returns integer representation of a character
repr() Returns a string containing a printable representation of an object
str() Returns a string version of an object
type() Returns the type of an object or creates a new type object

Math

  • Python has a math module that provides most of the familiar mathematical functions
Function Description
abs() Returns absolute value of a number
divmod() Returns quotient and remainder of integer division
max() Returns the largest of the given arguments or items in an iterable
min() Returns the smallest of the given arguments or items in an iterable
pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable
  • A module is a file that contains a collection of related functions
  • Before we can use the module, we have to import it
In [99]:
import math
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
math.sin(radians)
Out[99]:
0.7071067811865476

Iterables and Iterators

Function Description
all() Returns True if all elements of an iterable are true
any() Returns True if any elements of an iterable are true
enumerate() Returns a list of tuples containing indices and values from an iterable
filter() Filters elements from an iterable
iter() Returns an iterator object
len() Returns the length of an object
map() Applies a function to every item of an iterable
next() Retrieves the next item from an iterator
range() Generates a range of integer values
reversed() Returns a reverse iterator
slice() Returns a slice object
sorted() Returns a sorted list from an iterable
zip() Creates an iterator that aggregates elements from iterables

User Defined Functions

  • Python allows programmers to define their OWN function
  • A function definition specifies the name of a new function and the sequence of statements that execute when the function is called.

Why create your own functions?

  • Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
  • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
  • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
  • Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
In [102]:
# A simple Python function to check whether x is even or odd 
def evenOdd( x ): 
    if (x % 2 == 0): 
        print ("even")
    else: 
        print ("odd")
        
# Driver code 
evenOdd(2) 
evenOdd(3) 
even
odd

File Handling

  • To read/write a file, you have to open it with an appropriate mode as the second parameter

open(filename, mode)

mode description
r Opens a file for reading only, default mode
w Opens a file for writing only
a Opens a file for appending only. File pointer is at end of file
rb Opens a file for reading only in binary
wb Opens a file for writing only in binary
In [103]:
fout = open('output.txt', 'w')
print(fout)
<_io.TextIOWrapper name='output.txt' mode='w' encoding='cp1252'>
  • If the file already exists, opening it in write mode clears out the old data.
  • If the file doesn’t exist, a new one is created.
  • The write method puts data into the file.
In [104]:
line1 = "This here's the wattle,\n"
fout.write(line1)
Out[104]:
24
In [105]:
line2 = "the emblem of our land.\n"
fout.write(line2)
Out[105]:
24
In [109]:
# When you are done writing, you have to close the file.

fout.close()

Reading data from the file

  • To read data back from the file you need one of these three methods
Method Description
read([number]) Return specified number of characters from the file.
if omitted it will read the entire contents of the file.
readline() Return the next line of the file.
readlines() Read all the lines as a list of strings in the file
In [110]:
# Reading all the data at once

f = open('output.txt', 'r')
f.read() 
Out[110]:
"This here's the wattle,\nthe emblem of our land.\n"
In [111]:
f.close()
In [112]:
# Reading all lines as an array

f = open('output.txt', 'r')
f.readlines() 
Out[112]:
["This here's the wattle,\n", 'the emblem of our land.\n']
In [113]:
f.close()
In [114]:
# Reading only 1 line

f = open('output.txt', 'r')
f.readline()
Out[114]:
"This here's the wattle,\n"
In [115]:
f.close()
In [117]:
# Iterating through the file using file pointer

f = open('output.txt', 'r')
for line in f:
    print(line)
f.close()    
This here's the wattle,

the emblem of our land.

NumPy

  • NumPy is the fundamental package for scientific computing with Python.
  • It contains among other things
    • a powerful N-dimensional array object
    • sophisticated (broadcasting) functions
    • tools for integrating C/C++ and Fortran code
    • useful linear algebra, Fourier transform, and random number capabilities
  • NumPy can also be used as an efficient multi-dimensional container of generic data.
  • Numpy arrays are a great alternative to Python Lists
  • NumPy’s main object is the homogeneous multidimensional array.
  • NumPy’s array class is called ndarray. It is also known by the alias array
  • The more important attributes of an ndarray object are:
    • ndarray.ndim: the number of axes (dimensions) of the array.
    • ndarray.shape: the dimensions of the array.
    • ndarray.size: the total number of elements of the array.
    • ndarray.dtype: an object describing the type of the elements in the array.
    • ndarray.itemsize: the size in bytes of each element of the array.
    • ndarray.data: the buffer containing the actual elements of the array.

Numpy Arrays

  • create an array from a regular Python list or tuple using the array function
In [118]:
import numpy as np

a = np.array([2,3,4])
print(a, a.dtype)
[2 3 4] int32
In [119]:
# array transforms sequences of sequences into two-dimensional arrays, 
# sequences of sequences of sequences into three-dimensional arrays

b = np.array([(1.2, 3.5, 5.1),(4.1,6.1,0.5)])
print(b, b.dtype)
print(b.shape)
[[1.2 3.5 5.1]
 [4.1 6.1 0.5]] float64
(2, 3)
In [120]:
# The type of the array can also be explicitly specified at creation time

c = np.array( [ [1,2], [3,4] ], dtype=complex )
c
Out[120]:
array([[1.+0.j, 2.+0.j],
       [3.+0.j, 4.+0.j]])
  • The function zeros creates an array full of zeros,
  • the function ones creates an array full of ones, and
  • the function empty creates an array whose initial content is random and depends on the state of the memory.
In [121]:
print('Zeros: ',np.zeros( (3,4) ))
print('Ones', np.ones( (2,4), dtype=np.float64 ))
print('Empty', np.empty( (2,3) ))
Zeros:  [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
Ones [[1. 1. 1. 1.]
 [1. 1. 1. 1.]]
Empty [[1.2 3.5 5.1]
 [4.1 6.1 0.5]]
In [122]:
# NumPy provides a function analogous to range that returns arrays instead of lists.

np.arange( 10, 30, 5 )
Out[122]:
array([10, 15, 20, 25])
In [123]:
# The reshape function can be used to convert an array into a matrix

a = np.arange(15).reshape(3, 5)
a
Out[123]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
In [124]:
print("array dimensions: ", a.shape)
print("number of dimensions: ", a.ndim)
print("element types: ", a.dtype.name)
print("size of elements: ", a.itemsize)
print("total number of elements: ",a.size)
print("type of object:",type(a))
array dimensions:  (3, 5)
number of dimensions:  2
element types:  int32
size of elements:  4
total number of elements:  15
type of object: <class 'numpy.ndarray'>
In [125]:
# Arithmetic operators on arrays apply elementwise

a = np.array( [20,30,40,50] )
b = np.arange( 4 )
print('a: ', a)
print('b:', b)
print('a-b:', a-b)
print('B**2', b**2)
print('10*sin(a): ', 10*np.sin(a))
print('Which elements of a < 35:', a<35)
print('Elements of a < 35: ',a[a<35])
a:  [20 30 40 50]
b: [0 1 2 3]
a-b: [20 29 38 47]
B**2 [0 1 4 9]
10*sin(a):  [ 9.12945251 -9.88031624  7.4511316  -2.62374854]
Which elements of a < 35: [ True  True False False]
Elements of a < 35:  [20 30]
In [126]:
A = np.array( [[1,1], [0,1]] )
B = np.array( [[2,0], [3,4]] )
print('A = ', A)
print('B = ', B)
print('A*B = ', A*B)
print('A . B = ', A.dot(B))
print('Numpy A. B = ', np.dot(A, B))
A =  [[1 1]
 [0 1]]
B =  [[2 0]
 [3 4]]
A*B =  [[2 0]
 [0 4]]
A . B =  [[5 4]
 [3 4]]
Numpy A. B =  [[5 4]
 [3 4]]

Further Reading: Python Books

  • Think Python 2e - Allen B. Downey
  • Automate the Boring Stuff with Python - Al Sweigart
  • Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython - Wes McKinney
  • Think Stats - Allen B. Downey
  • Think Bayes: Bayesian Statistics in Python - Allen B. Downey
  • Python Data Science Handbook - Jake VanderPlas