An Introduction to Python – Part II Dr. Nancy Warter-Perez.

Slides:



Advertisements
Similar presentations
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Advertisements

Introduction to C Programming
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
An Introduction to Python – Part II Dr. Nancy Warter-Perez June 15, 2005.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
An Introduction to Python – Part II Dr. Nancy Warter-Perez April 21, 2005.
An Introduction to Python – Part III Dr. Nancy Warter-Perez May 1, 2007.
Introduction to Python
An introduction to Python and its use in Bioinformatics Csc 487/687 Computing for Bioinformatics Fall 2005.
An Introduction to Python and Its Use in Bioinformatics Dr. Nancy Warter-Perez April 19, 2005.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
An Introduction to Python – Part III Dr. Nancy Warter-Perez.
An Introduction to Python Dr. Nancy Warter-Perez April 15, 2004.
An Introduction to Python and Its Use in Bioinformatics Dr. Nancy Warter-Perez.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Introduction to Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Strings CS303E: Elements of Computers and Programming.
A Review of C++ Dr. Nancy Warter-Perez June 16, 2003.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Data Structures and Debugging Dr. Nancy Warter-Perez June 18, 2003.
Built-in Data Structures in Python An Introduction.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
Python Conditionals chapter 5
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
Python Let’s get started!.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
INLS 560 – S TRINGS Instructor: Jason Carter. T YPES int list string.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
CSc 120 Introduction to Computer Programing II Adapted from slides by
An Introduction to Python and Its Use in Bioinformatics
Basic operators - strings
Lecture 9 Shell Programming – Command substitution
Variables, Expressions, and IO
Engineering Innovation Center
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Introduction to C++ Programming
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
CS 100: Roadmap to Computing
Basic String Operations
Unit 3: Variables in Java
“Everything Else”.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II2 Overview References Python Programming for the Absolute Beginner (PP) Learning Python (LP) Solution to Programming Workshop #1 If tests (PP Ch1, LP Ch 9) Loops (PP Ch1, LP Ch 10) for while Example amino acid search program Programming Workshop #2

Introduction to Python – Part II3 Solution to Programming Workshop 1 Write a Python program to compute the hydrophobicity of an amino acid # Program to compute the hydrophobicity of an amino acid # (solution only includes first 3 amino acids) # Written by: Prof. Warter-Perez # Date created: April 15, 2004 # Last modified: hydro = {"A":1.8,"C":2.5,"D":-3.5} aa = raw_input ("Please enter amino acid: ") print "The hydrophobicity of %s is %f."% (aa, hydro[aa])

Introduction to Python – Part II4 Make solution case insensitive # Program to compute the hydrophobicity of an amino acid # Written by: Prof. Warter-Perez # Date created: April 15, 2004 # Last modified: April 20, made script case insensitive for # amino acids hydro = {"A":1.8,"C":2.5,"D":-3.5} aa = raw_input ("Please enter amino acid: ") aa = aa.upper() print "The hydrophobicity of %s is %f."% (aa, hydro[aa])

Introduction to Python – Part II5 Python Basics - Comments Python comments # line comment Header comments #Description of program #Written by: #Date created: #Last Modified:

Introduction to Python – Part II6 Python Basics - Variables Python variables are not “declared”. To assign a variable, just type: identifier=literal Identifiers Have the following restrictions: Must start with a letter or underscore (_) Case sensitive Must consist of only letters, numbers or underscore Must not be a reserved word (LP pg 137) Have the following conventions: All uppercase letters are used for constants Variable names are meaningful – thus, often multi-word Convention 1: alignment_sequence Convention 2: AlignmentSequence Python specific conventions: Avoid _X, __X__, __X, _, (LP pg 138)

Introduction to Python – Part II7 Numbers Normal Integers –represent whole numbers Ex: 3, -7, 123, 76 Long Integers – unlimited size Ex: L Floating-point – represent numbers with decimal places Ex: 1.2, ,3.14e-10 Octal and hexadecimal numbers Ex: O177, 0x9ff, Oxff Complex numbers Ex: 3+4j, j, 3J

Introduction to Python – Part II8 Python Basics – arithmetic operations +add -subract *multiply /divide %modulus/remainder y=5; z=3 x = y + z x = y – z x = y * z x = y / z x = y % z x = 8 x = 2 x = 15 x = 1 x = 2 OperatorsExample

Introduction to Python – Part II9 Python Basics – arithmetic operations << shift left >> shift right **raise to power y=5; z=3 x = y << 1 x = y >> 2 x = y ** z x = 10 x = 1 x = 125 OperatorsExample

Introduction to Python – Part II10 Python Basics – Relational and Logical Operators Relational operators ==equal !=, <>not equal >greater than >=greater than or equal <less than <=less than or equal Logical operatorsandornot

Introduction to Python – Part II11 Python Basics – Relational Operators Assume x = 1, y = 4, z = 14 ExpressionValueInterpretation x < y + z1True y == 2 * x + 30False z <= x + y0False z > x1True x != y1True

Introduction to Python – Part II12 Python Basics – Logical Operators Assume x = 1, y = 4, z = 14 ExpressionValueInterpretation x<=1 and y==30False x<= 1 or y==31True not (x > 1)1True not x > 10False not (x<=1 or y==3)0False

Introduction to Python – Part II13 Enclosed in single or double quotes Ex: ‘Hello!’, “Hello!”, “3.5”, “a”, ‘a’ Sequence of characters: mystring=“hello world!” mystring[0] -> “h”mystring[1] -> “e” mystring[2] -> “l”mystring[-1] -> “!” Strings -1 is last, -2 next to last, etc…

Introduction to Python – Part II14 String operations mystring = “Hello World!” ExpressionValuePurpose len(mystring)12 number of characters in mystring “hello”+“world”“helloworld” Concatenate strings “%s world”%“hello”“hello world” Format strings (like sprintf) “world” == “hello” “world” == “world” 0 or False 1 or True Test for equality “a” < “b” “b” < “a” 1 or True 0 or False Alphabetical ordering

Introduction to Python – Part II15 Strings (2) slicing: mystring = “spoon!” mystring[2:] -> “oon!” mystring[:3] -> “spo” #note last element is never included! mystring[1:3]-> “po” Many useful built-in functions mystring.upper() -> “SPOON!” mystring.replace(‘o’, ‘O’) -> “spOOn!”

Introduction to Python – Part II16 Strings (3) “%” operator: sort of “fill in the blanks” operation: mystring=“%s has %d marbles” % (“John”,35) mystring -> “John has 35 marbles” %sreplace with string %d,%ireplace with integer %freplace with float Values to put in blanks “blanks”

Introduction to Python – Part II17 Lists mylist=[“a”,”b”,3.58,”d”,4,0] mylist[0] mylist[2] a 3.58 Indexing mylist[-1] mylist[-2] 0404 Negative indexing (counts from end) mylist[1:4][“b”,3.58,”d”]Slicing (like strings) “b” in mylist “e” not in mylist 1 or True mylist.append(8)[“a”,”b”,3.58,”d”,4,0,8]Add to end of list

Introduction to Python – Part II18 Tuples Tuples – sequence of values like lists, but cannot be changed after it is created mytuple=(1,”a”,”bc”,3,87.2) mytuple[2] -> “bc” mytuple[1]=“3” Used when you want to pass several variables around at once Error!

Introduction to Python – Part II19 Dictionaries Dictionaries – map ‘keys’ to ‘values’ like lists, but indices can be of any type Also, keys are in no particular order Eg: mydict={‘b’:3, ’a’:4, 75:2.85} mydict[‘b’] -> 3 mydict[75] -> 2.85 mydict[‘a’] -> 4

Introduction to Python – Part II20 Dictionaries mydict={“r”:1,”g”:2,”y”:3.5,8.5:8,9:”nine”} mydict.keys()['y', 8.5, 'r', 'g', 9]List of the keys mydict.values()[3.5, 8, 1, 2, 'nine']List of the values mydict[“y”]3.5Value lookup mydict.has_key(“r”)True or 1Check for keys mydict.update({“a”:75}){8.5: 8, 'a': 75, 'r': 1, 'g': 2, 'y': 3.5, 9: 'nine'} Add pairs to dictionary

Introduction to Python – Part II21 Dictionaries – other considerations Slicing not allowed Referencing invalid key is an error: >>> mydict={8.5: 8, 'a': 75, 'r': 1, 'g': 2, 'y': 3.5, 9: 'nine'} >>> mydict["red"] Traceback (most recent call last): File " ", line 1, in ? KeyError: 'red‘ Use mydict.get(“red”) instead, it returns None if key is not found

Introduction to Python – Part II22 Input/Output Function raw_input() designed to read a line of input from the user 1 optional argument: string to prompt user If int or float desired, simply convert string: int(mystring)->convert to int (if possible) float(mystring)->convert to float (if possible) >>> mystr=raw_input("Enter a string:") Enter a string:Hello World! >>> mystr 'Hello World!'

Introduction to Python – Part II23 Output Function print Prints each argument, followed by space After all arguments, prints newline Put comma after last arg to prevent newline “add” strings to avoid spaces print “a”,”b”,”c” a b c print “a”,”b”,”c”, a b c print “a”+”b”+”c” abc Newline! No Newline! No spaces!

Introduction to Python – Part II24 Output Example >>> print "hello","world";print "hello","again" hello world hello again >>> print "hello","world",;print "hello","again" hello world hello again >>> print "hello %s world" % "cold and cruel" hello cold and cruel world >>> print "hello","cold"+ " " + "and","cruel","world" hello cold and cruel world

Introduction to Python – Part II25 Python Basics – Relational and Logical Operators Relational operators ==equal !=not equal >greater than >=greater than or equal <less than <=less than or equal Logical operatorsandornot

Introduction to Python – Part II26 if Statement if expression: action Example: a1 = 'A‘; a2 = 'C'; match = 0; if (a1 == a2) : match+=1;

Introduction to Python – Part II27 if-elif-else Statement if expression: action 1 elif expression: action 2 else : action 3 Example: a1 = 'A‘; a2 = 'C'; match = 0; gap = 0; if (a1 == a2) : match+=1; elif (a1 > a2): else: gap+=1;

Introduction to Python – Part II28 for Statement for var in list: action Sets var to each item in list and performs action range() function generates lists of numbers: range (5) -> [0,1,2,3,4] Example mylist=[“hello”,”hi”,”hey”,”!”]; for i in mylist: print i Iteration 1 prints: hello Iteration 2 prints: hi Iteration 3 prints: hey Iteration 4 prints: !

Introduction to Python – Part II29 while Statement while expression: action Example x = 0; while x != 3: x = x + 1 Iteration 1: x=0+1=1 Iteration 2: x=1+1=2 Iteration 3: x=2+1=3 Iteration 4: don’t exec / 2 Infinite loop!

Introduction to Python – Part II30 Example: Amino Acid Search Write a program to count the number of occurrences of an amino acid in a sequence. The program should prompt the user for A sequence of amino acids (seq) The search amino acid (aa) The program should display the number of times the search amino acid (aa) occurred in the sequence (seq)

Introduction to Python – Part II31 Example: Amino Acid Search (2) #this program will calculate the number of occurrences of an amino acid in a #sequence #by Bryce Ready done=0 while (not done): sequence=raw_input("Please enter a sequence:"); aa=raw_input("Please enter the amino acid to look for:");

Introduction to Python – Part II32 Example: Amino Acid Search (3) #compute the number of occurrences using for loop cnt=0 for i in sequence: if i == aa: cnt+=1 if cnt == 1: print "%s occurs in that sequence once" % aa else: print "%s occurs in that sequence %d times" % (aa, cnt) answer=raw_input("try again? [yn]") if answer == "n" or answer == "N": done = 1

Introduction to Python – Part II33 Programming Workshop #2 Write a sliding window program to compute the %GC in a sequence of nucleotides. The program should prompt the user for The DNA sequence The window size (assume the window increment is 1)