python

37
Introduction to Python 2017

Upload: ceaslibrary

Post on 15-Jul-2015

194 views

Category:

Software


4 download

TRANSCRIPT

Page 1: Python

Introduction to Python

2017

Page 2: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

ObjectivesI Introduction to PythonI Hands-on

I SyntaxI StringsI ListsI Control Flow & LoopsI Functions

I Import & Future TopicsI Helpful hints & resources

Page 3: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

What is Python?I Is it a Scripting language?I An Object-oriented language maybe?I How about an Interpreted language?

Python isI General purpose, object oriented, high level, interpreted

languageI Simple,Portable,Open source & PowerfulI Developed in early 90’s by Guido Van Rossum

Page 4: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Python vs Java

I Dynamic vs Static Typing - Handling variablesI Indentation vs Braces - Separate code into blocksI Terse vs Verbose - Number of lines of codeI Easy to learn vs Steep learning curveI Use Python + Java

Page 5: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

where is Python used

I Used extensively in web - Django, TurboGears, Plone, etcI Communicating with Databases - MySQL, Oracle,

MongoDB, etcI Desktop GUI - GTK+, QT, TK, etcI Scientific computing - SciPy, Scientific Python, etcI Software Development - SCons, Buildbot, Roundup, etcI Games 3D graphics - Pygame, PyKyra, etcI For success stories -

https://www.python.org/about/success

Page 6: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Download & Installation

I Latest releases - Python 2.7.9 & Python 3.4.3I Python Interpreter

I Linux - Installed in all distro’s, elsehttps://www.python.org/downloads/source/

I Mac - Installed, elsehttps://www.python.org/downloads/mac-osx/

I Windows - Download fromhttps://www.python.org/downloads/

I Text EditorI Linux - Vim, Gedit, Kate, Emacs, etcI Mac - Vim, TextMate or any unix like editorI Windows - Notepad++ or IDE

I Python Documentation - https://www.python.org/doc/I Set editor to expand tab to 4 spaces

Page 7: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Python programsI Python programs and modules are written as text files

with .py extensionI Program - .py file executed directly as program (often

referred to as scripts)I Module - .py file referenced via the import statement

I Write a simple print program and save as 'myFirst.py' and save on desktopprint "Hello, Python!"

I Run Python Shell 'C:\path..\myFirst.py'

Ways to run python

I

I

I

Interactive Interpreter (Classic command line interpreter or Python Shell) - Run as a calculator or used to run a python programScript from command line - Used to run a python programIntegrated Development Environment (IDE) - Eclipse, Netbeans, etc

Page 8: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Variables & Data typesI Variables

I Stores a piece of data and gives it a specific nameI Do not need to specify data typeI Equal sign (=) is used to assign values to variables

I Data TypesI Numbers - int,long,float,complexI Boolean - True, FalseI StringI ListI TupleI Dictionary

Page 9: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Indentation,Comments & Math operators

I IndentationI Whitespace is used to structure the code instead of bracesI A tab - 4 spaces

I CommentsI Single line - #I Multi-line - Not supported in Python but people use Triple quote.

I Math operatorsI Addition (+),Substraction(-),Multiplication(*),Division(/)I Modulus(%),Exponent(**),Floor Division (//)

I Exercise 1 (Run as calculator and a saved .py program) Tip Calculator!!Cost of meal = 54.76Tax = 7.85%Tip = 15%Find cost after tax, tip, cost after tip, total cost

Page 10: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

StringsI 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. Indexstarts from zero(0)

I Consider ”Python”PYTHONP will be at 0th position of string and N will be at 5th

position from the startI 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.

Page 11: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

String MethodsLet 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]

Page 12: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

String Concatenation FormattingI Concatenation

I Combining of strings is done by using the (+) operatorbetween them

I In order to combine a string with a non-string variable, usestr() method to convert non-strings to strings.

I FormattingThe string format operator is %

I %c - characterI %s - string conversion via str() prior to formattingI %d - signed decimal integerI %x %X - hexadecimal integer(lowercase/uppercase)I %f - floating point real number

Page 13: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Lists

I It is a datatype you can use to store a collection of differentpieces of information as a sequence under a single variablename

I Can be accessed by indexI Creating lists - Putting different comma separated values

within square bracketslist1 = [”physics”,”astronomy”,56.98,”MJ”,-9.36]

I Accessing values - Individual elements or a range ofelementslist1[3];list1[-2];list1[1:4];list1[-3:]

I Updating lists - Update single or multiple entries in a listlist1[2] = ”Botany 101”

I Negative index represents access from the right starting from -1list1[-2] = ”MJ”

Page 14: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

A tad bit more

I Deleting elements - Either use del statement or remove()methodlist1 = [”physics”,”astronomy”,56.98,”MJ”,-9.36]del list1[3] - when you know the index of the elementlist1.remove(”physics”) - when you don’t know the indexof the element

I Other List operationsI Length - len([3,4,5,”supernova”,”jaguar”])I Concatenation - [1,2,3] + [5,6,7] = [1,2,3,5,6,7]I Repetition-

[”hi”,”bye”]*3 = [”hi”,”bye”,”hi”,”bye”,”hi”,”bye”]I Membership(returns Boolean) - 56.98 in list1

Page 15: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

List MethodsLet 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()I Sort the list(natural order) - list1.sort()

TuplesTuples are sequences, just like lists except.

I Tuples are immutable - cannot be changed or updated unlike listsI Tuples use parentheses (), whereas lists use square brackets []

Page 16: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Dictionary

I Similar to a list by values are accessed by looking up a keyinstead of an index

I A key can be a string or numberI Creating dictionaries -key-value pairs are separated by (:),

items are separated by (,) and everything is enclosed incurly bracesdict1 = {”name”:”Daniel”,”age”:23,”degree”:”MS”}dict2 = {’name’:”Ian Callum”,’age’:60,’job’:”Car designer”,’brand’:”Jaguar”,’worked-for’:[”Ford”,”TWR”,”Aston Martin”]}

Page 17: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Some more

I Accessing values - Values can be accessed only throughkeysdict1[’age’] - 23dict2[’brand’] - Jaguar

I Updating dictionary - Add new entry or modify anexisting entrydict1[’subjects’] = [”OS”,”DBMS”,”Artificial Intelligence”]dict2[’worked-for’][1]=”Tom Walkinshaw Racing”

I Deleting dictionary elements - 3 variationsdict1 = {”Sayuri”:556-2365,”ken”:556-8749,”Tom”:556-5800}del dict[’Sayuri’] - Removes entry with key ’Sayuri’dict.clear() - Removes all entries in the dictionarydel dict - Deletes entire dictionary

Page 18: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Dictionary MethodsLet 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()

Page 19: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Control FlowI Comparison Operators

I

I

I

I

I

I

Equal to (==)Not equal to (!=)Less than (<)greater than (>)greater than or equal to (>=) less than or equal to (<=)

I Logical OperatorsI Logical AND (and)I Logical OR (or)I Logical NOT (not)I Note: Precedence:- not >and >or

Page 20: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

If and else decisionsI If statement - Consists of a Boolean expression followed by

one or more statements if<condition >: statement(s)

I If...else statement-If statement followed by an optional elsestatement which executes when the Boolean expression is falseif<condition >: statement(s)else : statement(s)

Page 21: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

If,elif and else decisionsI If...elif...else statement Otherwise if the following

expression is true, do this!if <condition >: statement(s)elif <condition >: statement(s)else: statement(s)

Page 22: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Exercise 2Program 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 inputPython 2 -> var =input('enter value') # will convert and return number

var =raw_input('enter value') # will return stringPython 3 -> var =input('enter value') # will return string

var =raw_input('enter value') # not available

Page 23: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

While loopI While loop will execute as long as the looping condition is

satisfied or True.while <loop condition>: statement(s)

I Infinite loop-Occurs whenI

I

Loop condition cannot possibly be wrong (while 1!=2:) Logic of the loop prevents the loop condition from becoming falsecount = 10while count>0 : count += 1

Page 24: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

While loopI Break statement - One liner which means, ”exit the current

loop”count = 0 while True : Print count count +=1 if count >= 10: break

Page 25: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

While/else loopI A feature very unique to PythonI The ’else’ block executes when either

I Loop is never enteredI 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 +=1else: print ”You win!”

Page 26: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

For loopI Each item in the sequence is assigned to the iterating

variable and the statements are executed until the entiresequence is exhaustedfor <iterating var>in <sequence>:statement(s)

I Iterating over a range of valuesI

I

I

for letter in 'string': print letter for num in range(10): print numfor num in range(-6,6): print numfor num in range(-10,-100,-30): print numfor fruit in ['bannana', 'orange']: print fruit

I

I

Page 27: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

More IterationsI Iterating a string

for letter in ”Monty Python!” : print ”Current letter:”, letter

I Iterating a listlist1 = [”F-type”,”C-X75”,”XJ-13”] for index in range(len(list1)): print ”current model: ”,list1[index]

I Iterating a dictionarydict1 = {’name’:”Bob”,’age’:34,’dob’:”6-25-1990” } for keys in dict1.keys(): print ”Value of ”+keys+” :%s” %dict1[keys]

Page 28: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

For/else loopI A feature very unique to Python just like while /elseI The ’else’ block executes when the loop exits normallyI 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’,felse: print ’A fine selection of fruits!’

Page 29: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Exercise 3DNA Transcription - The process of converting DNA to RNA Example :G->C;C->G;A->T;T->AInput: GCTAGCCTACGOutput: CGATCGGATGCHint: Use ”for” loop to traverse the DNA string. Use ”if...else” construct to check and replace each letter in the string.

Page 30: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Function DefinitionI It is a block of organized, reusable code that is used to

perform an actionI Defining a Function

I

I

I

I

Begins with keyword ’def’ followed by the function name and parenthesesAny input parameter/arguments should be placed within these parenthesesCode block starts with colon (:) and is indentedreturn [expression] statement exits a function, optionally passing back an expression to the callerdef function name(parameters): ”function docstring” function suite return [expression]

Page 31: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Calling a FunctionI After the basic structure is finalized, we can execute by

eitherI Calling it from another functionI Calling it directly from command prompt

I Called functiondef 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’)

Page 32: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Importing ModulesI Module is a file that contains definitions - including

variables and functions - that you can use once it isimported

I Generic import - Import only a moduleSyntax: import module l[,module 2[,...module N]Usage: import math,support

I Function import-Import specific attributes from a moduleSyntax: from module name importname 1[,name 2[,....name N]Usage: from math import sqrt,pow

Page 33: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

More ImportingI Universal import - Import all variables and functions in a

moduleSyntax: from module name import *Usage: import math import *

I dir() Function - Return a sorted list of strings containingnames defined in a moduleimport mathcontent = dir(math)print content

Page 34: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Advanced TopicsI File input&outputI ExceptionsI Classes&ObjectsI Regular ExpressionsI Database AccessI Multithreading

Page 35: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Helpful hints&resourcesI CEAS Library Python resources

I http://guides.libraries.uc.edu/python

I Online links & tutorialsI Python documentation - https://www.python.org/doc/I Python Programming wiki book -

http://en.wikibooks.org/wiki/Python ProgrammingI Python tutorials - Udemy, Code academy, etc

Page 36: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Questions ??

Page 37: Python

OBJECTIVES INTRODUCTION SYNTAX STRINGS LISTS DICTIONARY LOOPS FUNCTIONS IMPORT&FUTURE TOPICS

Thank you for attending the workshop !!Your kind suggestions/feedbacks are more than welcome