: Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11
Program Overview Program Code Block Statements Expressions
Expressions & Statements An expression has a value, evaluated by Python An expression is combination of tokens and values >>>1+2 3 A statement combines expressions to form program logic Statements do something a = 1 + 2 print(a) Lines starting with # are comments and are ignored # This is a single line comment
Blocks & Indentation A block is a collection of contiguous statements to be executed one after another Python uses indentation to denote beginning/end of a block structure Indentation comprised of tabs or spaces at start of a line of code Can use either (tab/spaces) but must be consistent
Blocks & Indentation In Python no need to mark block boundaries Python automatically detects block boundaries based on line indentation Indentation improves readability Indentation level of statements is significant Exact amount of indentation does not matter, only relative indentation of nested blocks x = 0 while x < 10: print(x) x = x + 1 # this is correct x = 0 while x < 10: print(x) x = x + 1 # wrong, infinite loop
Overview So far only encounterd list of instructions, executed one after the other Input: print( Hello World ) print( this is a test ) Output: Hello World this is a test Real power of programming comes from repetition and selection
Conditionals If Statements: Select actions to perform based on a given Boolean expression (True or False) if <condition1>: <block1> elif <condition2>: <block2> else: <block3> x = 3 y = 4 if x < y: print( y greater ) elif x > y: print( x greater ) else: print( x,y equal ) Combine conditions using logical operators (and / or) elif is short for else-if elif and else are optional can have more than one elif
Loops While Loops: Repeatedly execute a block of code while a given condition is True while <condition>: <block1> else: x = 1 while x < 10: print( x is,x) x = x + 1 <block2> Special keywords can be used to control execution of loop: continue: jump to top of innermost (enclosing) loop break: jump out of innermost (enclosing) loop if break is used then else block won t be executed else-block executed when while condition turns False else is optional (not used frequently)
Loops For Loops: Itereate over a sequence of elements and repeatedly apply a block of code to each element names = [ Al, for <value> in <seq>: Ben, Chris ] <block1> for n in names: else: print( hi,n) <block1> Note: A for loop must always be applied to something that evaluates to a sequence (e.g., a list) for loops also can have break and/or continue statements
Loops The range() function returns a list of numbers >>>range(5) [0,1,2,3,4] >>>range(1,5) [1,2,3,4] # from zero # 1 to 5 exclusive >>>range(1,5,2) # in steps of 2 [1,3] Use range() with for loop >>>for x in range(1,4):... print(x)... 1 2 3
in Python A function is a named sequence of statements to perform a desired operation. To define a function we need: Start definition with def A unique name Zero or more input arguments in brackets A colon : A block of code An optional return value General Format: def <name>(a1,a2,...,an): <block1> return <value> def subtr(x,y): diff=x-y return diff
in Python Calling : can be called repeatedly once defined To call function, always need brackets and correct number of arguments >>>def subtr(x,y):... return x-y... >>>subtr(5,2) # call with 2 arguments 3 >>>d = subtr(9,3) # assign return value >>>d 6 >>>subtr(1) # wrong number of args TypeError: subtr() missing 1 required positional argument: y
in Python Calling : To call function, always need brackets, even if no arguments required >>>def hello():... print( Hello World )... >>>hello() Hello World >>>hello <function hello at 0x7f8035fd4a60>
in Python Calling : can call other functions >>>def square(x):... return x * x... >>>def sum of squares(x,y):...return square(x) + square(y)... >>>sum of squares(3,4) 25 Note: in this example the x in square(x) knows nothing about the x in sum of squares(x,y), they just happen to have the same name
in Python Calling : Arguments can be given default values Arguments that have default values must come after arguments that don t >>>def hello user(name = user ):... print( Hello, name)... >>>hello user() Hello user >>>hello user( Fabian ) Hello Fabian
Calling : in Python Arguments that have default values must come after arguments that don t Arguments are assumed in the order in which they are declared >>>def volume(l, W=5, H=7):... return L * W * H... >>>volume(2) # L=2, W=5(def), H=7(def) 70 >>>volume(2,3) # L=2, W=3, H=7(def) 42 >>>volume(2,h=3) # L=2, W=5(def), H=3 30 >>>volume(2,3,11) # L=2, W=3, H=11 66
Using in Scripts Example: Simple Python script to compute the factorial of a number
Calling on Variables Certain types of variables in Python have functions associated Syntax <variable>.<function>(arg1,arg2,...) Strings have number of functions that perform common operations # Find 1st occurance >>>str1= Hello >>>str1.find( l ) 2 # alphabetical only? >>>str1.isalpha() True >>>str2= Hello 123! >>>str2.isalpha() False
Built-In Python contains a wide range of built-in functions to perform basic operations Call range() function to build a sequence >>>range(5) [0,1,2,3,4] Call len() function to get length of string/list/dictionary >>>len( qwerty ) 6 Call abs() function to get absolute value of argument >>>abs(-15) 15 Call help() function to get more information about a function >>>help(abs) Help on built-in function abs in builtins: abs(x, /) Return the absolute value of the argument.
Console Input/Output Simplest way of displaying output is to use print command >>>print( the numbers are, 34, and, 71) the numbers are 34 and 71 >>>print( the number is {}.format(2)) the numbers is 2 Reading input from the keyboards is also easy using input() (same as raw input()) >>>s = input( enter value: ) enter value: 23 # user typed 23 <ret> >>>type(s) <class str > >>>x = int(s) >>>type(x) <class int >
File Input/Output Files are special types of variables in Python They are created using the open() function Remeber to close() them when finished f = open( <filepath>, <action> ). f.close() The <action> can be r for reading, w for writing or a for appending (default is reading) If the file to be written to ( w ) already exists, then it will be over-written (and its previous contents lost)
Reading Files After opening a file to read, can use several functions read() readline() readlines() Alternate way of reading line-by-line read single character from file read full line from file read all lines from file f = open( test.txt, r ) for line in f: print(len(line.strip())) f.close()
Writing Files After opening a file to write, use write() function with string formatting f = open( out.txt, w ) for i in range(1,5): f.write( Number {}\n.format(i)) f.close() out.txt will be over-written if it already exists Use append ( a ) if contents of file are to be preserved Need to explicitly move to next line with \n f.write() returns number of characters it writes out Output may be corrupted if not f.close()-ed Alternatively use with / as block with open( f.c, r ) as f, open( g.c, w ) as g: <do file reading/writing>
Python Error Messages A key programming task is debugging when a program does not work correctly or as expected If Python finds an error in your code, it raises an exception e.g., try to convert incompatible types (n=int( abc )) e.g., division by zero (inf=1/0) e.g., invalid syntax in code (a typo, pirnt(a)) e.g., try to write where you don t have permission e.g., try to read a non-existent file >>>f = open( missing.txt, r ) Traceback (most recent call last): File <stdin>, line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: missing.txt
Handling By default, exception will terminate program execution Handle errors in structured way by catching exceptions Plan in advance for errors that might occur Tell user what went wrong & how to fix it try: <block of code> except <errortype>: <error handling> try: f = open( f.c, r ) except FileNotFoundError: print( No file ) Program no longer automatically terminates Can continue, trying to fix the error Other exception types: ArithmeticError (OverflowError, ZeroDivisionError, FloatingPointError), IndexError, MemoryError, SyntaxError, TabError, TypeError
Indentation figure Colm Ryan COMP 50050 Peadar O Gaora, GENE 30040