Python 141215095441 Conversion Gate01 PDF
Python 141215095441 Conversion Gate01 PDF
2017
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Objectives
I Introduction to Python
I Hands-on
I Syntax
I Strings
I Lists
I Control Flow & Loops
I Functions
I Import & Future Topics
I Helpful hints & resources
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
What is Python?
I Is it a Scripting language?
I An Object-oriented language maybe?
I How about an Interpreted language?
Python is
I General purpose, object oriented, high level, interpreted
language
I Simple,Portable,Open source & Powerful
I Developed in early 90’s by Guido Van Rossum
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Python vs Java
I Dynamic vs Static Typing - Handling variables
I Indentation vs Braces - Separate code into blocks
I Terse vs Verbose - Number of lines of code
I Easy to learn vs Steep learning curve
I Use Python + Java
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Strings
I Can be declared in single quotes (’ ’) or double quotes (” ”)
or triple quotes (””” ””” or ''' ''')
singleQuote = 'One Line'
doubleQuote = ”One Line with ' eg. Jame's”
tripleQuote = """Span
multiple lines"""
I Each character can be accessed by using their index. Index
starts from zero(0)
I Consider ”Python”
PYTHON
P will be at 0th position of string and N will be at 5th
position from the start
I Strings are ”immutable”
I Immutable means that we cannot change the value. If we have
an instance of the String class, any method you call which
seems to modify the value, will actually create a new string.
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
String Methods
Let our string variable be called ’var’
I Length of string - len(var)
I Convert to string - str(var)
I Convert to lowercase - var.lower()
I Convert to uppercase - var.upper()
I Is digit/Is alpha - var.isdigit()/var.isalpha()
I Replace characters - var.replace(old,new)
I Split a sentence - var.split(delimiter)
I Swap case - var.swapcase()
I Range slice - var[start index:end index]
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Lists
I It is a datatype you can use to store a collection of different
pieces of information as a sequence under a single variable
name
I Can be accessed by index
I Creating lists - Putting different comma separated values
within square brackets
list1 = [”physics”,”astronomy”,56.98,”MJ”,-9.36]
I Accessing values - Individual elements or a range of
elements
list1[3];list1[-2];list1[1:4];list1[-3:]
I Updating lists - Update single or multiple entries in a list
list1[2] = ”Botany 101”
I Negative index represents access from the right starting from -1
list1[-2] = ”MJ”
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
List Methods
Let our list variable be called ’list1’
I Length of the list - len(list1)
I Maximum/Minimum value - max(list1)/min(list1)
I Append object to list - list1.append(obj)
I Frequency of object - list1.count(obj)
I Return index - list1.index(obj)
I Insert object - list1.insert(index,obj)
I Delete object - list1.pop()/list1.remove(obj)
I Reverse the list - list1.reverse()
ISort the list(natural order) - list1.sort()
Tuples
Tuples are sequences, just like lists except.
I Tuples are immutable - cannot be changed or updated unlike lists
I Tuples use parentheses (), whereas lists use square brackets []
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Dictionary
I Similar to a list by values are accessed by looking up a key
instead of an index
I A key can be a string or number
I Creating dictionaries -key-value pairs are separated by (:),
items are separated by (,) and everything is enclosed in
curly braces
dict1 = {”name”:”Daniel”,”age”:23,”degree”:”MS”}
dict2 = {’name’:”Ian Callum”,’age’:60,
’job’:”Car designer”,
’brand’:”Jaguar”,
’worked-for’:[”Ford”,”TWR”,”Aston Martin”]}
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Some more
I Accessing values - Values can be accessed only through
keys
dict1[’age’] - 23
dict2[’brand’] - Jaguar
I Updating dictionary - Add new entry or modify an
existing entry
dict1[’subjects’] = [”OS”,”DBMS”,”Artificial Intelligence”]
dict2[’worked-for’][1]=”Tom Walkinshaw Racing”
I Deleting dictionary elements - 3 variations
dict1 = {”Sayuri”:556-2365,”ken”:556-8749,
”Tom”:556-5800}
del dict[’Sayuri’] - Removes entry with key ’Sayuri’
dict.clear() - Removes all entries in the dictionary
del dict - Deletes entire dictionary
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Dictionary Methods
Let our dictionary variable be called ’dict1’
I Length of the dictionary - len(dict1)
I Shallow copy - dict1.copy()
I For key,return value - dict1.get(key)
I Check for key (returns boolean) - dict1.has key(key)
I List of k-v pairs - dict1.items()
I List of keys - dict1.keys()
I List of values - dict1.values()
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Control Flow
I Comparison Operators
I Equal to (==)
I Not equal to (!=)
I Less than (<)
I greater than (>)
I greater than or equal to (>=)
I less than or equal to (<=)
I Logical Operators
I Logical AND (and)
I Logical OR (or)
I Logical NOT (not)
I Note: Precedence:- not >and >or
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Exercise 2
Program to generate 6+2 UC id for a given name.(6+2 ID takes
the first 6 letters from the last name & first and last letters from
the first name)
I Store the first and last names in two different variables.
I Check if the length of the last name is <6 or not.
If < 6, pick first letters of first name to make up for the length
the last name.
I Accordingly, make use of slicing and concatenate the
letters to give the 6+2 ID.
Hint for taking input
Python 2 -> var =input('enter value') # will convert and return number
var =raw_input('enter value') # will return string
Python 3 -> var =input('enter value') # will return string
var =raw_input('enter value') # not available
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
While loop
I While loop will execute as long as the looping condition is
satisfied or True.
while <loop condition>:
statement(s)
I Infinite loop-Occurs when
I Loop condition cannot possibly be wrong (while 1!=2:)
I Logic of the loop prevents the loop condition from
becoming false
count = 10
while count>0 :
count += 1
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
While loop
I Break statement - One liner which means, ”exit the current
loop”
count = 0
while True :
Print count
count +=1
if count >= 10:
break
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
While/else loop
I A feature very unique to Python
I The ’else’ block executes when either
I Loop is never entered
I Loop exits normally
I The ’else’ block does not execute when, the loop exits as a result
of a break
import random #will explain import in latter slide
count = 0
while count<3:
num = random.randint(1,6)
print num
if num == 5:
print ”sorry, you lose!”
break
count +=1
else:
print ”You win!”
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
For loop
I Each item in the sequence is assigned to the iterating
variable and the statements are executed until the entire
sequence is exhausted
for <iterating var>in <sequence>:
statement(s)
I Iterating over a range of values
I for letter in 'string':
print letter
I for num in range(10):
print num
I for num in range(-6,6):
print num
I for num in range(-10,-100,-30):
print num
I for fruit in ['bannana', 'orange']:
print fruit
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
More Iterations
I Iterating a string
for letter in ”Monty Python!” :
print ”Current letter:”, letter
I Iterating a list
list1 = [”F-type”,”C-X75”,”XJ-13”]
for index in range(len(list1)):
print ”current model: ”,list1[index]
I Iterating a dictionary
dict1 = {’name’:”Bob”,’age’:34,’dob’:”6-25-1990” }
for keys in dict1.keys():
print ”Value of ”+keys+” :%s” %dict1[keys]
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
For/else loop
I A feature very unique to Python just like while /else
I The ’else’ block executes when the loop exits normally
I Does not execute when, the loop exits as a result of a break
fruits = [’banana’,’apple’,’orange’,’tomato’,’pear’]
print ’You have...’
for f in fruits:
if f == ’tomato’:
print ’A tomato is not a fruit!’
break
print ’A’,f
else:
print ’A fine selection of fruits!’
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Exercise 3
DNA Transcription - The process of converting DNA to RNA
Example :
G->C;C->G;A->T;T->A
Input: GCTAGCCTACG
Output: CGATCGGATGC
Hint: Use ”for” loop to traverse the DNA string. Use ”if...else”
construct to check and replace each letter in the string.
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Function Definition
I It is a block of organized, reusable code that is used to
perform an action
I Defining a Function
I Begins with keyword ’def’ followed by the function name
and parentheses
I Any input parameter/arguments should be placed within
these parentheses
I Code block starts with colon (:) and is indented
I return [expression] statement exits a function, optionally
passing back an expression to the caller
def function name(parameters):
”function docstring”
function suite
return [expression]
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Calling a Function
I After the basic structure is finalized, we can execute by
either
I Calling it from another function
I Calling it directly from command prompt
I Called function
def printme(str):
”This prints a string passed into the function”
print str
return :
#Function call
printme(’First call to user defined function’)
printme(’Second call to user defined function’)
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Importing Modules
I Module is a file that contains definitions - including
variables and functions - that you can use once it is
imported
I Generic import - Import only a module
Syntax: import module l[,module 2[,...module N]
Usage: import math,support
I Function import-Import specific attributes from a module
Syntax: from module name import
name 1[,name 2[,....name N]
Usage: from math import sqrt,pow
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
More Importing
I Universal import - Import all variables and functions in a
module
Syntax: from module name import *
Usage: import math import *
I dir() Function - Return a sorted list of strings containing
names defined in a module
import math
content = dir(math)
print content
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Advanced Topics
I File input&output
I Exceptions
I Classes&Objects
I Regular Expressions
I Database Access
I Multithreading
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Helpful hints&resources
I CEAS Library Python resources
I http://guides.libraries.uc.edu/python
I Online links & tutorials
I Python documentation - https://www.python.org/doc/
I Python Programming wiki book -
http://en.wikibooks.org/wiki/Python Programming
I Python tutorials - Udemy, Code academy, etc
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS
Questions ??
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS