MEIN 50010: Python Flow Control

Similar documents
Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

MEIN 50010: Python Strings

MEIN 50010: Python Introduction

Flow Control: Branches and loops

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Introduction to Python

Accelerating Information Technology Innovation

Python for C programmers

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Programming in Python 3

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Exceptions CS GMU

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Python for Informatics

Text Input and Conditionals

Lists, loops and decisions

Accelerating Information Technology Innovation

Scripting Languages. Python basics

Python File Modes. Mode Description. Open a file for reading. (default)

8. Control statements

Getting Started with Python

Fundamentals of Programming (Python) Getting Started with Programming

Introduction to Python (All the Basic Stuff)

Flow Control. CSC215 Lecture

Control Structures 1 / 17

Python Intro GIS Week 1. Jake K. Carr

Slide Set 15 (Complete)

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

YOLOP Language Reference Manual

Python Tutorial. Day 2

Exceptions and File I/O

CS Programming Languages: Python

Visualize ComplexCities

CSI33 Data Structures

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Advanced Python. Executive Summary, Session 1

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python for Non-programmers

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Conditionals and Recursion. Python Part 4

61A Lecture 2. Friday, August 28, 2015

Statements 2. a operator= b a = a operator b

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

MEIN 50010: Python Data Structures

Chapter 9: Dealing with Errors

ENGR 101 Engineering Design Workshop

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Python: common syntax

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

COMP 204: Sets, Commenting & Exceptions

Introduction to python

Python for Non-programmers

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

CS 115 Lecture 8. Selection: the if statement. Neil Moore

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

PLT Fall Shoo. Language Reference Manual

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

A Brief Introduction to Python

Introduction to Python

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CIS192 Python Programming

Beyond Blocks: Python Session #1

COMP 204: Sets, Commenting & Exceptions

Pace University. Fundamental Concepts of CS121 1

STSCI Python Introduction. Class URL

Variable and Data Type I

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

CIS192 Python Programming

Try and Error. Python debugging and beautification

CIS192 Python Programming

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

Basic Syntax - First Program 1

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22

Exceptions & a Taste of Declarative Programming in SQL

Introduction to Python, Cplex and Gurobi

Language Reference Manual

Types, lists & functions

Sprite an animation manipulation language Language Reference Manual

CS1 Lecture 3 Jan. 22, 2018

String Computation Program

CSC326 Python Imperative Core (Lec 2)

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Python 1: Intro! Max Dougherty Andrew Schmitt

MEIN 50010: Python Recursive Functions

Python. Executive Summary

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Transcription:

: 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