Lecture 1: Python Essentials
EL 364
Kobina Abakah-Paintsil
1
Lecture • The objective of this lecture is to revise essential
python data types, functions, decision-making
Objective approaches, iterative loops and how to handle file
processing in python.
2
A. Installing Anaconda
B. Spyder: Installation, Updating preferences and settings,
Getting used to interface
C. Standard Data Types (Variables) in Python: Numbers,
Strings, Boolean, Lists, Tuples, Dictionaries
Lecture
D. Basic decision-making using Python: If Else statements
Outline
E. Iterative Loops in Python: For Loops, While Loops
F. File Processing in Python: Open, Read, Write, Close
3
Standard Data Types (Variables) in Python
• Numbers: Python supports two types of numbers - integers(whole numbers) and
floating-point numbers (decimals).
• Integer Implementation: A = 9
• Float implementation: A = 9.0 OR A = float(9)
• Strings: Strings are defined either with a single quote (‘ ’) or a double quotes (“ ”). Use double
quotes if you have apostrophes in your string.
• String Implementation: B = “Ky is a fine boy” OR B = ‘KY is a fine boy’
• Boolean: True OR False
4
Standard Data Types (Variables) in Python
• Lists: A list is a sequence of elements similar to arrays in other programming languages.
Elements in a list are indexed.
• List Example: classReps = [‘Eugene’, ‘Vera’, ‘KY’, ‘Anita’]
• To access an element in a list use: nameoflist[index of element] e.g. classReps[1]
• The following operations can be done on a list:
Operation Explanation Code Example
Append Add an element to a list [Link](‘Richlove’)
Update Update element in a list classReps[1] = ‘Richlove’
Delete Delete an element in a list del classReps[4]
Length Get the length of list len(classReps)
Concatenate Concatenate to list bestPals = [‘Opare Gyawu’, ‘Jessica’]
concList = classReps + bestPals
Sort list Sorts the list ascending by [Link]()
default
5
Standard Data Types (Variables) in Python
• Multidimensional lists: They contain multiple lists in one variable.
• Multidimensional list are in the form of list = [ [elements], [elements] ].
• Example:
Elements
0 1 2
Lists 0 Anita Vera Eugene
1 123 456 789
• In code format this example will be typed as:
twodlist = [[“Anita", “Vera", “Eugene"], [123, 456, 789]]
• Elements in a multidimensional list can be accessed using:
nameoflist[row_index][column_index]
Example: twodlist[0][1]
6
Standard Data Types (Variables) in Python
• Tuples: Tuples are also a sequence of elements like arrays and are indexed just like lists. The
difference between lists and tuples is immutability.
• Tuples are immutable therefore; their elements cannot be updated like those of lists.
• Comparatively, tuples are faster to process.
• They are normally used in situations where data is being passed between systems such as between
data management systems and python modules.
• They are also the best choice when you do not want elements to change during the program
execution process or want a faster access to elements of the tuple sequence.
• An example of a tuple is:
tuple1=( “KY”, “Scali”, “Jeffery” )
7
Standard Data Types (Variables) in Python
• Dictionaries: They are a collection of key-value pairs. Values can be accessed using keys.
• Given the example Address below:
Type Value
Street Tarkwa-Bogoso Highway
City Tarkwa
Region Western
Country Ghana
• The same address a list will be given as:
address = [‘Tarkwa-Bogoso Highway’, ‘Tarkwa’, ‘Western’, ‘Ghana’]
• This means that the programmer will have to keep track of the index in order to retrieve a particular
value from the list. This can be avoided by using dictionaries as expressed below:
Address = {‘Street’: ‘Tarkwa-Bogoso Highway’, ‘City’ : ‘Tarkwa’, ‘Region’ : ‘Western’, ‘Country’ : ‘Ghana’}
Key Value
8
Standard Data Types (Variables) in Python
• Dictionaries: They are a collection of key-value pairs. Values can be accessed using keys.
• Note that keys are case sensitive.
• To access a value:
Nameofdictionary[key]
• The following operations can be performed on dictionaries
Operation Code Example
Update values Address[‘Street’] = ‘Tarkwa Highway’
Add a new key and value pair Address[‘PostCode’] = ‘WT0038’
Delete key-value pair del Address[‘PostCode’]
Get Length of dictionary len(Address)
Convert dictionary to string str(Address)
Get all keys in a dictionary print ([Link]())
Get all values in a dictionary Print([Link]()) 9
Basic Decision-Making in Python
• Decision making in python can be achieved using if else statements.
• An if statement executes a block of code only if the specified condition is met.
• Syntax:
if condition:
# body of if statement
• An if statement can have an optional else clause. The else statement executes if the condition
in the if statement evaluates to False.
• Syntax:
if condition:
# body of if statement
else:
# body of else statement
10
Iterative Loops
• While Loops: In Python, we use the while loop to repeat a block of code until a certain
condition is met.
• Syntax:
while <condition>:
#statements
11
Iterative Loops
• For Loops: In Python, a for loop is used to iterate over sequences such as lists, strings, tuples,
etc.
• Syntax:
for variables in sequence:
#statement(s)
12
File Processing
• Typical file functions include opening, reading, writing and closing a file.
• To open a file a variable(file object) must be created to store it. Example:
cityTemp = open(‘[Link]’, ‘r’)
• There are various modes for the open function, and they include:
• "r" - Read - Default value. Opens a file for reading, error if the file does not exist
• "a" - Append - Opens a file for appending, creates the file if it does not exist
• "w" - Write - Opens a file for writing, creates the file if it does not exist
• "x" - Create - Creates the specified file, returns an error if the file exist
• The readline() method is used to read one record from a file whereas the readlines() method is
used to read all records in a file starting from the position of the cursor in the file.
• The split() method splits a string into a list.
13
File Processing
• The write() method writes a specified text to the file.
• The close() method closes an open file. You should always close your files, in some cases, due
to buffering, changes made to a file may not show until you close the file.
• The seek() method sets the current file position in a file stream.
• The rstrip() method removes any trailing characters (characters at the end a string), space is the
default trailing character to remove.
14