An Introduction to Python

Similar documents
Text Input and Conditionals

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

Decisions, Decisions. Testing, testing C H A P T E R 7

Intro. Scheme Basics. scm> 5 5. scm>

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

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Flow Control: Branches and loops

Python Intro GIS Week 1. Jake K. Carr

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

LOOPS. Repetition using the while statement

The Big Python Guide

Making Decisions In Python

Exception Handling. Genome 559

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

Class extension and. Exception handling. Genome 559

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

An Introduction to Python

Python for Informatics

Chapter 9: Dealing with Errors

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

CS Programming Languages: Python

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Part III Appendices 165

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

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

4.3 FURTHER PROGRAMMING

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

Exceptions in Java

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

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

CS Summer 2013

Beyond Blocks: Python Session #1

Debugging Your Python Code: For Dummies

Introduction to Python

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Python for Non-programmers

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Functions and Decomposition

Introduction to computers and Python. Matthieu Choplin

Advanced topics, part 2

Pace University. Fundamental Concepts of CS121 1

T H E I N T E R A C T I V E S H E L L

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Control Structures 1 / 17

CS 111X - Fall Test 1

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

4. Java language basics: Function. Minhaeng Lee

Class extension and. Exception handling. Genome 559

CS150 - Sample Final

CMPT 100 : INTRODUCTION TO

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Real Python: Python 3 Cheat Sheet

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

Variables, expressions and statements

Python Tutorial. Day 2

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Intel x86 Jump Instructions. Part 5. JMP address. Operations: Program Flow Control. Operations: Program Flow Control.

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Visualize ComplexCities

Data Structures. Lists, Tuples, Sets, Dictionaries

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

Intel x86 Jump Instructions. Part 5. JMP address. Operations: Program Flow Control. Operations: Program Flow Control.

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Collections. Lists, Tuples, Sets, Dictionaries

Advanced Python. Executive Summary, Session 1

for loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Math Day 2 Programming: How to make computers do math for you

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

A453 Task 1: Analysis: Problem: Solution:

Quiz. Introduction: Python. In this project, you ll make a quiz game to challenge your friends. Activity Checklist.

4.2 Function definitions the basics

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Introduction to C Programming

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Errors and Exceptions

CS150 Sample Final. Name: Section: A / B

Python 1: Intro! Max Dougherty Andrew Schmitt

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

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Python Activity 7: Looping Structures WHILE Loops

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Table of Contents EVALUATION COPY

Modules and scoping rules

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

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

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

Transcription:

An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu

Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many other programing languages)

Python s Data Structures Lists 2 * Can access and change elements of a list by index. * Starting at 0 * mylist[0] * Just like strings.

Python s Data Structures Lists 3 * Lists have lots of handy functions. * mylist.function(arguments) * Most are self explanatory. * Get an error if index() can t find what it s looking for.

Python s Data Structures Lists 4 3 ways to delete

Python s Data Structures Lists 5

Python s Data Structures Dictionaries * Like lists, but have keys and values instead of index. * Keys are strings or numbers * Values are almost anything. E.g. Strings, lists, even another dictionary!

Reminder: writing in TextEdit (for Mac users)

Example: Tip Calculator * First let s figure out the pseudocode: * Set cost of meal * Set rate of tax * Set tip percentage * Calculate meal + tax * Calculate and return meal with tax + tip

A Script Not a Module

Example: Tip Calculator 3 * What if we want to calculate for a different meal cost without rewriting the code. * Pass the amount from the command line to python. * How do we get python to understand the new amount? * Need to import sys * sys.argv is a list of strings of parameters passed from the command line.

Handling Commandline Arguments sys.argv[0] is tipcalculator.py sys.argv[1] arg1

Handling Commandline Arguments 2

Handling Commandline Arguments 3 * Make calculatetip a function. Useful if we need to reuse that code in future programs! * Command line arguments from sys.argv are always strings so cast to a float if we want to do maths with them.

Test Your Tip Calculator

For Loops Main program statements For loop * If we want to perform the same tasks on every item in a list, string or dictionary we can use a FOR LOOP. for variable in listname: #any code here Looping block Continue main program for No more item? Next item

For Loops on a List (Back in the python interactive environment) for num in mylist: print 2^num

For Loops on a Dictionary for key in mydictionary: print key as a string and value as an integer

For Loops on a String for letter in mystring: mynewstring = mynewstring + 2*letter

Python2 vs 3: Ranges range(start,stop[,step]) Useful for looping over unusual ranges. * Python2 * range returns a list * Python3 * range does not return a list * Use float on o\ne of the integers for a float division * Can use list to see what it means Same syntax for the for loops

Ranges range(start,stop[,step]) Useful for looping over unusual ranges. Same syntax in Python2 and 3

A Function to Find the Complement Make a function that takes a string of nucleotides and returns a string with the reverse complement. If the string contains a character that is not a nucleotide, print a message saying so. Pseudocode: for nucleotide in sequence if nucleotide == A : prepend complementsequence with T else if nucleotide == T :.

Reverse Complement 2 Import sys so we can get command line arguments Make a function that takes a sequence as an argument

A Function to Find the Complement 3 Define a new empty string for the reverse complement Use a for loop to do something for each nucleotide in the sequence If one of the nucleotides isn t AGCT the print a message and return nothing (quit the function without returning a new string).

A Function to Find the Complement 4 If the nuceotide is A, append T to our reverse complement string Do the same for each nucleotide

A Function to Find the Complement 5 The reversecomp function should return rc_seq string once the for loop has checked every nucleotide in the sequence.

A Function to Find the Complement 6 Run the script and print the output. This should be the result of passing the first command line argument to our new reversecomp function.

A Function to Find the Complement 7 Save it as revcomp.py and let s test it! What does return '' used for?

A Function to Find the Complement 8 Another improvement: Run the function within the print statement!

A Function to Find the Complement 9 Can we make better code than these if statements: If Elif Elif Elif

Dictionaries! Works the same, much more elegant code!

More Data Structures: Enumerate Returns an enumerate object which is the input with sequentially numbered inputs.

Zips together two lists Zip

Break statements Exit the loop they are in. Notice the output isn t printed for the negative number:

While loops Keeps executing the code in the loop while the condition remains true. Rechecks the condition after each iteration. False while True while condition: #code to execute

While loops Set loopcondition to True. While loop checks if loopcondition is true. It is, so the code inside the loop will be executed next.

While loops Set loopcondition to False. The while loop doesn t recheck the loopcondition until it reaches the end so the code will continue executing.

While loops Print this will print once. We are at the end of the loop now so the loopcondition will be checked next.

While loops loopcondition is False now so the code inside the loop will not be executed.

While loops Indeed the text is printed just once!

While loops Don t forget to include the count+=1 else you create an infinite loop! Why does it print 9 last yet count = 10 after the code is finished? How do we get it to print all the way to 10?

While loops Switching order of count and print statements is one way! Could also have made condition: While count <=10

While loops Keep doing a loop until the correct input is received: Reminder: in Python2, it should be raw_input

Break statements can exit while loops The while loop condition is never met but the code reaches a break before count reaches 100.

While / Else Else: only executed if while loop finishes without reaching a break.

Play the random number game!

Reverse Complement Returns

Errors Everyone gets errors in their code. You may already have had some! Knowing what the errors mean help you fix them. Errors messages are quite informative even if they seem difficult to understand

Syntax Error Notice the error highlighting which part of the code is incorrect. Syntax errors are the most generic and common. To fix, check the line in the error message, specifically check around the arrow. What is wrong with the first line above?

Indentation Error We ve fixed the while True: line. Indentation error is a specific type of syntax error which tells you your code was not correctly indented. How do we correct this code?

Exceptions Sometimes code will be valid and won t cause an error while you input it but can error when it is executed. Errors that occur at the time code runs are called exceptions. Not all exceptions are fatal, you can include code to handle exceptions.

Exceptions Name error Divide by zero error Keyboard interrupt (ctrl+c)

Exceptions Type error Input object error Let s figure out how to handle these exceptions

Handling Exceptions We can see that this code throws a ValueError. If we don t want this to stop the program, or we want to show a more helpful error message then we need to add some code:

Handling Exceptions The try section is executed first. If a number is received, then no exception will be thrown so the break command will be reached

Handling Exceptions If no error types are matched the code will throw an unformatted exception as if the tryand except commands were not there.

Handling Exceptions Can have multiple exceptions handled by the same section. Have an else clause that runs if the try ends without a break command.

Exception Hierarchy If you handle a class it will handle all subclasses, so consider that if you catch StandardError it will be difficult to write code to handle all possible exceptions. Try and handle as low level exception as possible and avoid: except Exception