Python for Beginners. John B. Johnston Bioinforma3cs Engineer
|
|
- Harry Wright
- 6 years ago
- Views:
Transcription
1 Python for Beginners John B. Johnston Bioinforma3cs Engineer
2 Python What is it? Python is an interpreted, interac3ve programming language that incorporates external reusable modules. Python is widely used by biologists for data manipula3on, analysis, and visualiza3on.
3 Python Why for biology? More readable than languages such as Perl Rapid applica3on development Many external libraries/modules available Highly scalable Incorporates advanced design features Free and widely available
4 Running Python Programs Python can be run interac3vely inside of the Python shell where commands can be issued. To invoke the interac3ve shell use the command python (no quotes).
5 Running Python Programs Python can be encapsulated in a text file and run outside the interac3ve shell. Save your code to a file, use python./<progname>
6 hello.py
7 Exercise #1 Open the python interac3ve shell Using the print statement, have python print out some message to your screen
8 Variables and Types Not sta3cally typed Numbers integers and floa3ng point (7, 16.23, 9.0, 1254, 6.7E- 03) Strings defined with single or double quotes ( Hello, Hello ) Variable assignment: someint = 77 thefloat = 63.2 mystring = hello QB- 826
9 Python Keywords print print to console while flow control (e.g. loops) for iterate over collec3on of items if, elif, else condi3onal control is tests for object iden3ty not, and, or boolean truth tests class create user defined objects import, from, as external module control break, con3nue interrupt flow control Not a comprehensive list!
10 Common Data Structures Lists a simple collec3on of data objects. Can be mul3- dimensional. mylist = [1,2,3,4,5,6] print mylist[2] 3 print mylist[0] 1 print mylist[-1] 6 Each element in the list can be accessed by an index that begins at 0
11 Common Data Structures Tuples these are similar to lists, but are immutable (lists however, are mutable). mytuple = 100, 2300, 75, bingo print mytuple[0] 100 print mytuple (100, 2300, 75, bingo )
12 Common Data Structures Sets collec3ons of unordered data objects with no duplicate elements. These can be used like sets basket = [ apple, orange, banana ] techcos = [ google, apple, dell ] fruit = set(basket) IT = set(techcos) fruit & IT (intersection) set([ apple ]) fruit IT (union) set(['google', 'apple', 'orange', 'banana', 'dell'])
13 Common Data Structures Dic3onaries a mapped collec3on of unique key- value pairs phonenums = { jack : , jenny : ] phonenums[ jenny ]
14 Common Data Structures We can also create complex structures, for example: Lists of lists Dic3onaries of lists Lists of tuples, etc. We can use built- in operators on these basic structures to create other structure forms, like: Stacks Queues Dequeues, etc.
15 Math in Python - Operators Command Opera,on Example Output + Addi3on Subtrac3on * Mul3plica3on 7*3 21 / Division 19/3 6 % Remainder/Modulo 19%3 1 ** Exponent 2**4 16 *Not a comprehensive list!
16 Exercise #2 Try some simple math in python: * 8 20 / / 3 20/3.0 No3ce anything interes3ng about the last 3 expressions?
17 Number Types & Conversion Python converts numbers in an expression containing mixed types. This can lead to unexpected results, so be careful! Integers (1, 555, 32, 7) Floats (4.56, , 122.0) Complex (2E- 09, 3.4E10) int(x) float(x) complex(x)
18 Built- in Func3ons Func,on Descrip,on sqrt(x) Square root of x where x > 0 round(x,n) min(x1, x2, x3..) max(x1, x2, x3 ) log10(x), log(x) x rounded to n digits Smallest value in the list Largest value in the list Log base 10 and natural log, respec3vely random() Generate a random float between 0-1, exclusive of 1 shuffle(lst) cos(x), sin(x), tan(x), etc. pi, e Randomize items in list in- place Various trigonometric func3ons Mathema3cal constants Usually prefaced with math.func(). E.g. math.sqrt(3) Not a complete list
19 Python Statements A line of instruc3on in Python is called a statement Single line statements: mycolor = blue thesum = A mul3- line statement: X = \ \ Mul3ple statements in a line: a = 1; b=2; sum = a+b
20 Exercise #3 Try execu3ng a statement: total = ((40/5) + 10) * 8 How can you see the value of total? What is the quan3ty of total?
21 Indenta3on in Python Python uses colons (:) and indenta3on to define blocks of code. Code blocks might include func3ons, the body of a loop, or statements to execute if a condi3onal evaluates to True or False. Indent using tabs or whitespace, as much as you like so long as it is consistent in the block Indenta3on also makes the code more readable
22 Indenta3on Example Here is a loop that uses indenta3on to define its code block: for i in range(1,11): print(i) if i == 5: break How many levels of indenta3on do we have?
23 Exercise #4 Try the indenta3on example below Note the change in the shell prompt Use whitespace or tabs to achieve the right level of indenta3on Hit return on blank line to exit block for i in range(1,11): print(i) if i == 5: break
24 Other Kinds of Operators We ve already seen and used mathema3cal operators, but there are others Assignment operators Comparison operators Logical operators Membership operators Bitwise operators
25 Assignment Operators Operator Descrip3on Example = Assign value resolved from right operands to operand on le += Adds right operand to le and assigns to le operand - = Subs right operand from le and assigns to le operand *= Mul3plies right operand with le and assigns result to le operand **= Right operand exponent to le, assign to le operand /= Divide le operand with right, assign to le C = A + B C += 1 (C = C + 1) C - = 1 (C = C 1) C *= 7 (C = C * 7) C **= a (C = C**a) C /= b (C = C/b)
26 Comparison Operators Operator Descrip3on Example == TRUE if operands ARE equal (2 == 4) is false!= TRUE if operands are NOT equal (2!= 4) is true <> TRUE if operands are NOT equal (2 <> 4) is true > TRUE if le operand is greater than right (2 > 4) is false < TRUE if le operand is less than right (2 < 4 ) is true >= TRUE if le operand is greater than or equal to right <= TRUE if le operand is less than or equal to right (2 >= 4) is false (2 <= 4) is true (2 <= 2) is true
27 Logical Operators Operator Descrip3on Example and TRUE if BOTH operands are true (a and b) is true or TRUE if EITHER operand is true (a or b) is true not Reverses the logical state of the operands not(a and b) is false
28 Membership Operators Operator Descrip3on Example in TRUE if BOTH operands are true (a and b) is true not in TRUE if EITHER operand is true (a or b) is true A = 10 B = 20 list = [10, 2, 300, 4, 50] If (a in list): print a is available in the list else: print a is NOT available in the list
29 Python Condi3onals
30 Exercise #5 Lets use that operator example as a condi3onal Vary the value of A, test B A = 10 B = 20 list = [10, 2, 300, 4, 50] If (A in list): print A is available in the list else: print A is NOT available in the list
31 A = 10 B = 20 list = [10, 2, 300, 4, 50] If- Elif- Else If (A in list) and (B in list): print A and B are available in the list elif (A in list): print A is available in the list elif(b in list): print B is available in the list else: print Neither A or B are in the list
32 Python Loops
33 Major Loop Types while loop code block is repeated while a given condi3on is TRUE. Test at top of loop for loop code execu3on is repeated according to an iterator value that is updated in the loop block Nested loops loops may be nested inside one another
34 Loop Controls break terminates loop and pops control out of block con3nue causes loop to skip statements that follow it and return to top of block pass does nothing but provide a syntac3c placeholder
35 For Loop Form Commonly used to iterate over collec3ons (e.g. lists) mylist = [a, b, c, d, e] for item in mylist: print item
36 Exercise #6 Given this list of numbers, construct a for loop to sum those numbers and print the result: numbers = [6,5,3,8,4,2,5,4,11] What is your answer (no chea3ng)?
37 Exercise #7 Try inpung the following code: for val in "string": if val == "i": break print(val) print("the end") What was your result? What happened there?
38 For Loops and Range The range func3on generates lists of numbers that can be used as- is or to access indices. for number in range(6): print number
39 For Loops and Range Using two numbers, range will count up from the first number (inclusive) to the second (exclusive) for number in range(2,6): print number With three, it counts from first to second in a step size given by the third for number in range(2, 14, 4): print number
40 While Loop Example # take input from the user n = int(input("enter n: ")) # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("the sum is",sum)
41 Python Strings The manipula3on of strings is vitally important to bioinforma3cians Python does not have a character type, it treats these as strings of length 1 Strings in Python can also be thought of as lists of characters and can be accessed/manipulated in much the same way
42 String Processing Examples Case opera3ons: >>> dna = 'CTGACCACTTTACGAGGTTAGC >>> dna CTGACCACTTTACGAGGTTAGC >>> dna.lower() ctgaccactttacgaggttagc Accessing string elements: >>> dna[0] 'C' >>> dna[1] 'T' >>> dna[2] 'G' >>> dna[-1] C'
43 String Processing Examples Given the GFF file excerpt: chri SGD gene ID=YAL049C;gene=AIM2 chri SGD gene ID=YAL048C;gene=GEM1 chri SGD gene ID=YAL040C; gene=cln3 Suppose each line is stored as a string in the list mygff >>> print mygff[0] chri SGD gene ID=YAL049C;gene=AIM2 >>> print mygff[1] chri SGD gene ID=YAL048C;gene=GEM1
44 String Processing Examples Spling a string: >>> mygff[0].split() ['chri', 'SGD', 'gene', '51855', '51855', '.', '- ', '.', 'ID=YAL049C;gene=AIM2'] String split based on whitespace Non- whitespace elements of string become items in a list Now lets save our split opera3on output in a new variable: >>> recordone = mygff[0].split() >>> recordone ['chri', 'SGD', 'gene', '51855', '51855', '.', '- ', '.', 'ID=YAL049C;gene=AIM2'] >>> recordone[- 1] 'ID=YAL049C;gene=AIM2'
45 String Processing Examples Using this technique, we can parse out the bits we re interested in, say chromosome, posi3on, and gene name: >>> recordone ['chri', 'SGD', 'gene', '51855', '51855', '.', '- ', '.', 'ID=YAL049C;gene=AIM2'] >>> recordone[- 1] 'ID=YAL049C;gene=AIM2' >>> geneone = recordone[- 1].split(';') >>> geneone ['ID=YAL049C', 'gene=aim2'] >>> geneonename = geneone[- 1].split('=') >>> geneonename ['gene', 'AIM2'] >>> NewRecord = recordone[0] + " " + recordone[3] + " " + recordone[4] + " " + geneonename[1] >>> NewRecord 'chri AIM2'
46 Other String Operators string[2:5] return slice of string (first index inclusive, last, exclusive) len(string) return the string length string.isdigit() - returns TRUE if all characters are digits string.isalpha() returns TRUE if all characters are alphabe3c string.replace(old, new) replace all occurrences of substring old with substring new string.find(sub) find the substring sub in the string, return lowest index posi3on if found, otherwise - 1. string.count(sub) count number of occurrences of substring in string Many others
47 String Processing Observa3ons Using these or similar techniques we can see how we can parse targeted informa3on Combined with a loop structure to operate record- by- record, and a data structure for storage, we can create a complete, reduced data set Useful for analysis, visualiza3on, crea3ng databases, etc. There are many string func3ons, and many ways to use them. This is just one example.
48 Exercise #8 Use our collec3on of string func3ons to calculate the GC content in percent, of the DNA sequence: TAGGCTAATGCTAGAATCCATGATTA (or even make up your own)
49 Exercise #8 One Solu3on >>> dna = "TAGGCTAATGCTAGAATCCATGATTA" >>> ((dna.count("g") + dna.count("c")) / float(len(dna))) * >>>
50 Exercise #9 Let s pull together a few things we ve learned about loops, condi3onals, and strings. You are given the following code: protein = vlswadktnvvs mylength = len(protein) Construct a for loop that iterates over protein and prints out every THIRD residue (star3ng with the very first residue), unless that residue is w ; in which case, print out Tryptophan.
51 Exercise #9 One Solu3on >>> protein = "vlswadktnvvs >>> mylength = len(protein) >>> for residue in range(0, mylength, 3):... if protein[residue] == "w":... print "Tryptophan"... else:... print protein[residue]... v Tryptophan k v
52 Python Func3ons A self- contained block of organized, reusable code used to perform a par3cular single func3on. Provide modularity Improve readability Easier to maintain Reduce code redundancy
53 General Func3on Form def myfunction( parameters ): do something here something else.. return [expression] myval = myfunction(someparam)
54 An Applica3on of Func3ons Recall our exercise where we computed GC content? Imagine we wanted to perform that func3onality on many records. What would be the advantages of encapsula3ng that as a discrete func3on?
55 Exercise #10 Create a func3on to calculate GC content, and invoke it, by passing a DNA sequence to the func3on. Feel free to reuse your code from Exercise #8.
56 Exercise #10 One Solu3on >>> def mygc(dna):... GCcount = ((dna.count("g") + dna.count("c")) / float(len(dna))) * return (GCcount)... >>> mygc("taggctaatgctagaatccatgatta") >>>
57 Func3ons and Scope Recall my solu3on from Exercise #10: >>> def mygc(dna):... GCcount = ((dna.count("g") + dna.count("c")) / float(len(dna))) * return (GCcount) What happens if I try to print the variable GCcount outside the func3on block? >>> print GCcount Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'GCcount' is not defined >>>
58 Func3ons and Scope Why did that error happen? Values assigned or declared in a func3on block are only accessible in that block. This is local scope Values assigned or declared in the main program block have global scope and can be accessed by all func3ons once declared
59 Improving our Func3on >>> def mygc(dna):... GCcount = ((dna.count("g") + dna.count("c")) / float(len(dna))) * return (GCcount)... >>> mygc("taggctaatgctagaatccatgatta") >>> What happens if I pass a lower or mixed case sequence to mygc? What about the precision of my return value? How can I make my func3on more flexible, say, to count whatever I want (AT, A, G, T, C, etc.)?
60 Improving our Func3on >>> def mygc(dna, substr):... GCcount = 0... for base in substr:... GCcount += dna.upper().count(base.upper())... GCcount = (GCcount / float(len(dna))) * return str(round(gccount,2))... >>> mygc("taggctaatgctagaatccatgatta", "AT") '65.38' >>> mygc("taggctaatgctagaatccatgatta", "GC") '34.62 >>> mygc("taggctaatgctagaatccatgatta", "gc") '34.62' >>> mygc("taggctaatgctagaatccatgatta", "at") '65.38' >>> mygc("taggctaatgctagaatccatgatta", "t") '30.77 >>> mygc("taggctaatgctagaatccatgatta", "gcat") '100.0'
61 Escaping the Shell All of the code we ve worked with in the interac3ve shell could have been saved in a file and executed as a standalone program. To write code, you need to use a text editor First exit the Python interac3ve shell using either: quit() Cntl- d
62 Nano A simple text editor If you are familiar with a par3cular Linux text editor, feel free to use it For everyone else, let s use nano Start the editor by issuing the command: nano myprog.py This will open a new file myprog.py for edi3ng.
63 Crea3ng a Program The first thing we need to add to our program is the shebang. The shebang tells the OS what programming language we re using: #!/usr/bin/env python The /usr/bin/env invokes the env command which determines the currently ac3ve copy/version of python. We could also simply use: #!/usr/bin/python
64 Exercise #11 For this exercise, we simply want to complete our simple program and run it. For your program: Create a variable DNA and assign a string value of bases to it. Create a simple for loop that iterates through the string and prints each leƒer to the screen. At the very end of the program, print the single statement END! When you re finished, save the program, and run it using python./mprog.py
65 Notes on Exercise #11 To run the program without using the python, set the executable bits on the file: chmod u+x myprog.py Then run the program simply with:./myprog.py
66 Interac3ve User Input You can add user input prompts very easily to the program you just created User input will wait un3l a value is entered mydna = raw_input( Enter a DNA sequence ) This will store the value entered into the variable mydna
67 Exercise #12 Reopen your file from Exercise #11 Replace your hard- coded statement for the value of dna with the interac3ve user input statement Save and rerun your program to test
68 Working with Files You can also use files for input or output for your Python program To access a file, you need an new object, called a file handle myhandle = open( /users/somebody/file.pdb, r ) This specifies the file path/name, and in this case, that it should be opened for reading
69 Working with Files Once the file handle has been created and opened, you can access the elements inside. One way: for item in myhandle: print item Another reads each line one at a 3me: myhandle.readline() Or read it all at once: myhandle.readlines()
70 Working with Files Wri3ng to files is very similar. First open a file handle: myhandle = ( /users/someuser/output.txt, w ) Then do your write: myhandle.write( This is my output file\n ) somedata = myhandle.write(somedata) Close your files when done: myhandle.close()
71 Exercise #13 First, copy this PDB file to your home directory: cp /users/john1545/1bck.pdb. Now write a python program (saved to file) that: Reads in the file (enter filenames via user input) Checks each line to see if it is an ATOM, and, if the atom is an oxygen (O). If so, write the following fields to an output file: ATOM, residue name (e.g., CYS, GLU, etc), and the atom type (O) E.g. ATOM THR O ATOM SER O ATOM SER O ATOM LYS O
72 Exercise #13 One Solu3on #!/usr/bin/env python filein = raw_input("enter the pdb filename: ") fileout = raw_input("enter output filename: ") fhandle = open(filein, "r") fout = open(fileout, "w") for item in fhandle: if ("ATOM" in item): recordsplit = item.split() if (recordsplit[- 1] == "O"): fout.write(recordsplit[0] + " " + recordsplit[3] + " " + recordsplit[- 1] + "\n") print "End!"
73 Exercise #13 One Solu3on ~]$ cat output.txt ATOM MET O ATOM VAL O ATOM ASN O ATOM ASN O ATOM PRO O ATOM THR O ATOM THR O ATOM VAL O ATOM PHE O ATOM PHE O ATOM ASP O ATOM ASP O ATOM ASP O ATOM ILE O ATOM ALA O
74 Wrapping Up Python is an extremely versa3le language that can be used effec3vely for biological data analysis We barely scratched the surface of the language s features Consider looking into Biopython addon modules and tools for Python, specific for bioinforma3cs hƒp://biopython.org/
75 Thank You John B. Johnston Bioinforma3cs Engineer
Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH
Introduction to Python Ph.D. Scien5fic Compu5ng Consultant PACE GATECH Things Covered What is Python? How to access Python environment? Fundamental elements in Python Variables (assignment, comparison,
More informationWriting a Fraction Class
Writing a Fraction Class So far we have worked with floa0ng-point numbers but computers store binary values, so not all real numbers can be represented precisely In applica0ons where the precision of real
More informationCS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++
CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel
More informationImpera've Programming
Impera've Programming Python Programs Interac)ve Input/Output One- Way and Two- Way if Statements for Loops User- Defined Func)ons Assignments Revisited and Parameter Passing Python program line1 = 'Hello
More informationHere n is a variable name. The value of that variable is 176.
UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction
ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More information18.1. CS 102 Unit 18. Python. Mark Redekopp
18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two
More informationProgramming to Python
Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the
More informationPython Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]
Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.
More informationUNIVERSITÀ DI PADOVA. < 2014 March >
UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible
More informationShell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi
Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+
More informationReal Python: Python 3 Cheat Sheet
Real Python: Python 3 Cheat Sheet Numbers....................................... 3 Strings........................................ 5 Booleans....................................... 7 Lists.........................................
More informationGetting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013
CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?
More informationSenthil Kumaran S
Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created
More informationVariable and Data Type 2
The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists
More informationIntroduction to Programming for Biology Research
Introduction to Programming for Biology Research Introduction to MATLAB: part I MATLAB Basics - The interface - Variables/arrays/matrices - Conditional statements - Loops (for and while) MATLAB: The
More informationUniversity of Texas at Arlington, TX, USA
Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,
More informationPython for Non-programmers
Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013
More informationDocument Databases: MongoDB
NDBI040: Big Data Management and NoSQL Databases hp://www.ksi.mff.cuni.cz/~svoboda/courses/171-ndbi040/ Lecture 9 Document Databases: MongoDB Marn Svoboda svoboda@ksi.mff.cuni.cz 28. 11. 2017 Charles University
More informationIntroduction to Python - Part I CNV Lab
Introduction to Python - Part I CNV Lab Paolo Besana 22-26 January 2007 This quick overview of Python is a reduced and altered version of the online tutorial written by Guido Van Rossum (the creator of
More informationIntroduction to Computer Programming in Python Dr. William C. Bulko. Data Types
Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationHistory Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability
History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,
More informationTable of Contents EVALUATION COPY
Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...
More informationBash scripts. Marcus Holm. slides courtesy of: Douglas Scofield
Bash scripts Marcus Holm slides courtesy of: Douglas Scofield Bash scripts overview Why write a script? Bash variable subs?tu?on and variable names The first script Posi?onal parameters Default values
More informationAlgorithms Lecture 11. UC Davis, ECS20, Winter Discrete Mathematics for Computer Science
UC Davis, ECS20, Winter 2017 Discrete Mathematics for Computer Science Prof. Raissa D Souza (slides adopted from Michael Frank and Haluk Bingöl) Lecture 11 Algorithms 3.1-3.2 Algorithms Member of the House
More informationSome material adapted from Upenn cmpe391 slides and other sources
Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationCSC Software I: Utilities and Internals. Programming in Python
CSC 271 - Software I: Utilities and Internals Lecture #8 An Introduction to Python Programming in Python Python is a general purpose interpreted language. There are two main versions of Python; Python
More information06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python
CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison
More informationIntroduction to Python (All the Basic Stuff)
Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions
More informationProgramming Environments
Programming Environments There are several ways of crea/ng a computer program Using an Integrated Development Environment (IDE) Using a text editor You should use the method you are most comfortable with.
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationPython Tutorial. Day 1
Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env
More informationSTATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration
STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the
More informationFlow Control: Branches and loops
Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the
More informationSequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python
Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted
More informationCommon Loop Algorithms 9/21/16 42
Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match Is Found 4. Maximum and Minimum 5. Comparing Adjacent Values 9/21/16 43 Sum
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More informationfrom scratch A primer for scientists working with Next-Generation- Sequencing data Chapter 1 Text output and manipulation
from scratch A primer for scientists working with Next-Generation- Sequencing data Chapter 1 Text output and manipulation Chapter 1: text output and manipulation In this unit you will learn how to write
More informationWorksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords
Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long
More informationJarek Szlichta
Jarek Szlichta http://data.science.uoit.ca/ Python is a straightforward language very simple syntax It encourages programmers to program without boilerplate (prepared) code 2 Python is completely object
More informationAll programs can be represented in terms of sequence, selection and iteration.
Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational
More informationIntroduction to Python! Lecture 2
.. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists
More informationPython Day 3 11/28/16
Python Day 3 11/28/16 Objectives Review Concepts Types of Errors Escape sequences String functions Find the Errors bookcost = int(input("how much is the book: ")) discount = float(input("what is the discount:
More informationIntroduction to Python
Introduction to Python Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows)
More informationIntroduction to Programming in Python (2)
Introduction to Programming in Python (2) Steve Renals s.renals@ed.ac.uk ICL 29 September 2005 Conditionals Loops Function basics Variables and functions Functional programming Designing functions Python
More informationCHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS
CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations
More information1 Strings (Review) CS151: Problem Solving and Programming
1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote
More informationGenome 373: Intro to Python II. Doug Fowler
Genome 373: Intro to Python II Doug Fowler Review string objects represent a sequence of characters characters in strings can be gotten by index, e.g. mystr[3] substrings can be extracted by slicing, e.g.
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful
More informationWrap up indefinite loops Text processing, manipula7on. Broader Issue: Self-driving cars. How do write indefinite loops in Python?
Objec7ves Wrap up indefinite loops Text processing, manipula7on Ø String opera7ons, processing, methods Broader Issue: Self-driving cars Feb 16, 2018 Sprenkle - CSCI111 1 Review How do write indefinite
More informationLecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers
....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \
More informationCSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial
CSI31 Lecture 5 Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial 1 3.1 Numberic Data Types When computers were first developed, they were seen primarily as
More informationGIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes
GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and
More informationCS 112: Intro to Comp Prog
CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment:
More informationIntroduction to Python
Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code
More informationStarting. Read: Chapter 1, Appendix B from textbook.
Read: Chapter 1, Appendix B from textbook. Starting There are two ways to run your Python program using the interpreter 1 : from the command line or by using IDLE (which also comes with a text editor;
More informationPython I. Some material adapted from Upenn cmpe391 slides and other sources
Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationLISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University
LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python
More informationMain Memory Organization
Main Memory Organization Bit Smallest piece of memory Stands for binary digit Has values 0 (off) or 1 (on) Byte Is 8 consecu>ve bits Word Usually 4 consecu>ve bytes Has an address 8 bits 0 1 1 0 0 1 1
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is
More informationPython: common syntax
Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable
More informationChapter 8 SETS AND DICTIONARIES
Chapter 8 SETS AND DICTIONARIES Chapter Contents Sets Dictionaries Complex Data Structures 10/19/16 Page 2 Chapter Goals To build and use a set container To learn common set opera2ons for processing data
More informationpython 01 September 16, 2016
python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7
More informationMEIN 50010: Python Introduction
: Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-04 Outline Goals Teach basic programming concepts Apply these concepts using Python Use Python Packages
More informationPlay with Python: An intro to Data Science
Play with Python: An intro to Data Science Ignacio Larrú Instituto de Empresa Who am I? Passionate about Technology From Iphone apps to algorithmic programming I love innovative technology Former Entrepreneur:
More informationLECTURE 1. Getting Started with Python
LECTURE 1 Getting Started with Python ABOUT PYTHON Development started in the 1980 s by Guido van Rossum. Only became popular in the last decade or so. Python 2.x currently dominates, but Python 3.x is
More information4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.
1. Write an X To the left of each valid Python name (identifier). (4pts) a) X pyhonindetfriar c) X a_b_c_d b) 9to5 d) x*y all or none 2. Write an X To the left of each Python reserved word (keyword). (4pts)
More informationText Input and Conditionals
Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()
More informationIntroduction to Python
Introduction to Python EECS 4415 Big Data Systems Tilemachos Pechlivanoglou tipech@eecs.yorku.ca 2 Background Why Python? "Scripting language" Very easy to learn Interactive front-end for C/C++ code Object-oriented
More informationPYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s
PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,
More informationPhysics 514 Basic Python Intro
Physics 514 Basic Python Intro Emanuel Gull September 8, 2014 1 Python Introduction Download and install python. On Linux this will be done with apt-get, evince, portage, yast, or any other package manager.
More informationComputer Lab 1: Introduction to Python
Computer Lab 1: Introduction to Python 1 I. Introduction Python is a programming language that is fairly easy to use. We will use Python for a few computer labs, beginning with this 9irst introduction.
More informationCIS192: Python Programming
CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms
More informationCrash Dive into Python
ECPE 170 University of the Pacific Crash Dive into Python 2 Lab Schedule Today Ac:vi:es Endianness Python Thursday Network programming Lab 8 Network Programming Lab 8 Assignments Due Due by Mar 30 th 5:00am
More informationVisualize ComplexCities
Introduction to Python Chair of Information Architecture ETH Zürich February 22, 2013 First Steps Python Basics Conditionals Statements Loops User Input Functions Programming? Programming is the interaction
More informationIntroduction to Python
Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions
More information1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman
1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive
More informationMath Day 2 Programming: How to make computers do math for you
Math Day 2 Programming: How to make computers do math for you Matt Coles February 10, 2015 1 Intro to Python (15min) Python is an example of a programming language. There are many programming languages.
More informationLecture 4. Defining Functions
Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in
More informationPython for Informatics
Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.
More informationIntroduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology
Introduction to Python Part 1 Brian Gregor Research Computing Services Information Services & Technology RCS Team and Expertise Our Team Scientific Programmers Systems Administrators Graphics/Visualization
More informationPython 1: Intro! Max Dougherty Andrew Schmitt
Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and
More informationUnix Shell scripting. Dr Alun Moon 7th October Introduction. Notation. Spaces
Unix Shell scripting Dr Alun Moon 7th October 2017 Introduction Shell scripts in Unix are a very powerfull tool, they form much of the standard system as installed. What are these good for? So many file
More informationIntermediate/Advanced Python. Michael Weinstein (Day 1)
Intermediate/Advanced Python Michael Weinstein (Day 1) Who am I? Most of my experience is on the molecular and animal modeling side I also design computer programs for analyzing biological data, particularly
More informationLecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming
Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly
More information1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen
1 Truth Last lecture we learned about the int, float, and string types. Another very important object type in Python is the boolean type. The two reserved keywords True and False are values with type boolean.
More informationMACRO NOTES DOCUMENTATION
MACRO NOTES DOCUMENTATION 1 The NIH Image manual, appendix A provides a descrip;on of the macro language and menu by menu explana;on of the commands 2 Reference card - this comes as a macro/text file with
More informationEE 355 Unit 17. Python. Mark Redekopp
1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,
More informationBiopython. Karin Lagesen.
Biopython Karin Lagesen karin.lagesen@bio.uio.no Object oriented programming Biopython is object-oriented Some knowledge helps understand how biopython works OOP is a way of organizing data and methods
More informationLocal defini1ons. Func1on mul1ples- of
Local defini1ons The func1ons and special forms we ve seen so far can be arbitrarily nested except define and check- expect. So far, defini.ons have to be made at the top level, outside any expression.
More informationIntroduction to Python, Cplex and Gurobi
Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python
More informationsomedata = { } somedata[ cheese ] = dairy somedata[ Cheese ] = dairy items = ( ( 3, 2 ), ( 5, 7 ), ( 1, 9 ), 0, ( 1 ) )
Structuring State 4 Self-Review Questions Self-review 4.1 What are the values of the variables a, b, c and d after the following statements have been executed? a = 1 b = 2 c = a + b d = a + c a will be
More informationMacro Assembler. Defini3on from h6p://www.computeruser.com
The Macro Assembler Macro Assembler Defini3on from h6p://www.computeruser.com A program that translates assembly language instruc3ons into machine code and which the programmer can use to define macro
More informationBBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal
BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3 Aykut Erdem, Erkut Erdem, Fuat Akal 1 Today Introduc/on to Programming Basic Concepts Developing Algorithms Crea
More informationPython Class-Lesson1 Instructor: Yao
Python Class-Lesson1 Instructor: Yao What is Python? Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined
More information