Python 1: Introduction to Python 1 / 19

Similar documents
Python Programming Exercises 1

Physics 514 Basic Python Intro

Introduction to Python

Python for Bioinformatics Fall 2014

>>> * *(25**0.16) *10*(25**0.16)

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

Lecture 3. Strings, Functions, & Modules

18.1. CS 102 Unit 18. Python. Mark Redekopp

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

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

CSCI 121: Anatomy of a Python Script

Algorithms and Programming I. Lecture#12 Spring 2015

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Advanced Python. Executive Summary, Session 1

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Getting Started Values, Expressions, and Statements CS GMU

Programming in Python 3

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

Programming Fundamentals and Python

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

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Downloaded from Chapter 2. Functions

MEIN 50010: Python Introduction

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Python 1: Intro! Max Dougherty Andrew Schmitt

Scripting Languages. Python basics

Computer Lab 1: Introduction to Python

from scratch A primer for scientists working with Next-Generation- Sequencing data Chapter 1 Text output and manipulation

Python for C programmers

Python Tutorial. Day 1

Fundamentals of Programming (Python) Getting Started with Programming

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

CS 102 Lab 3 Fall 2012

Beyond Blocks: Python Session #1

Python for Non-programmers

Introduction to Python

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Introduction to Python

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

Sequences and iteration in Python

IT441. Network Services Administration. Perl: File Handles

Functions. Python Part 3

A simple interpreted language

EL2310 Scientific Programming

ENGR 101 Engineering Design Workshop

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

Python. Karin Lagesen.

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules

AP Computer Science A

Act like a code monkey Coding Basics

Introductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

Lecture 1. basic Python programs, defining functions

A Little Python Part 1. Introducing Programming with Python

Lecture 3: Functions & Modules

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Getting Started with Python

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

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Starting. Read: Chapter 1, Appendix B from textbook.

Python. Executive Summary

Introduction to Python

The Math Class. Using various math class methods. Formatting the values.

STATS 507 Data Analysis in Python. Lecture 0: Introduction and Administrivia

Programming to Python

Introduction to Python Code Quality

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Introduction to Python. Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO

Variables, expressions and statements

Introduction to Python - Part I CNV Lab

Table of Contents EVALUATION COPY

Science One CS : Getting Started

Python Programming Language

Python Class-Lesson1 Instructor: Yao

Types, lists & functions

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Chris Simpkins (Georgia Tech) CS 2316 Data Manipulation for Engineers Python Overview 1 / 9

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Not-So-Mini-Lecture 6. Modules & Scripts

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

1. Hello World Bash Shell Script. Last Updated on Wednesday, 13 April :03

Bash Check If Command Line Parameter Exists

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

Introduction to Programming in Python (2)

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Get It Interpreter Scripts Arrays. Basic Python. K. Cooper 1. 1 Department of Mathematics. Washington State University. Basics

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Lecture 1. Types, Expressions, & Variables

CSC Software I: Utilities and Internals. Programming in Python

Python Intro GIS Week 1. Jake K. Carr

Week 1, continued. This is CS50. Harvard University. Fall Cheng Gong

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Computing with Numbers Zelle - Chapter 3

Hello, World and Variables

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Lecture 4. Defining Functions

Lecture 02 The Shell and Shell Scripting

Transcription:

Python 1: Introduction to Python 1 / 19

Python Python is one of many scripting languages. Others include Perl, Ruby, and even the Bash/Shell programming we've been talking about. It is a script because we write the code in a text file and then run it directly with an interpreter. Before when we ran a script in bash/shell we would do $ bash myscript.sh To run code for python we will do $ python myscript.py 2 / 19

A rst script Here's a text file that is called 'hello.py' and contains the following print("hello World!") $ python hello.py hello world $ python hello.py > message.txt # can redirect the output $ cat message.txt hello world 3 / 19

The Python interpreter The Python interpreter is a program we run, giving it a file or script which specifies the actions for it to take. One can also just run the interpreter on the command line and interact with it directly. Just execute the python command on the command line. $ python Python 2.7.10 (default, Oct 3 2015, 13:37:56) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang 700.0.72)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "hello world" hello world 4 / 19

Python version 3 There is a new (released 2009!) version of Python. Some syntax differences and the way that lists and some operators work is different. What's different 3.0 vs 2.0 - https://docs.python.org/3.0/whatsnew/3.0.html What's new in 3.6? - https://docs.python.org/3/whatsnew/3.6.html $ module switch python/3 $ python3 Python 3.6.0 (default, Jan 30 2017, 17:43:08) [GCC 4.8.3 20140911 (Red Hat 4.8.3 9)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print "hello world" File "<stdin>", line 1 print "hello world" ^ SyntaxError: Missing parentheses in call to 'print' >>> print( "hello world") hello world 5 / 19

Some math with the interpreter >>> 3+10 13 >>> 33/13 2 >>> 33/13.0 2.5384615384615383 >>> 2**10 # 2^10 1024 >>> (909+951) / 2.0 # Parenthees make a difference 930 >>> 909+951/2.0 1384 6 / 19

Modules: for Math Python has the concept of modules or libraries that contain routines we can re-use. We will spend more time on the types of modules that exist (the list is vast!). Using the math module which definese many routines. >>> sqrt(9) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sqrt' is not defined >>> import math >>> math.sqrt(9) 3 >>> math.pow(2,10) 1024.0 >>> 33/13.0 2.5384615384615383 >>> math.ceil(33/13.0) # round up 3.0 >>> math.floor(33/13.0) # round down 2.0 >>> round(2.2) # round works as you expect for rounding (<.5) 2.0 >>> round(2.6) # round works as you expect for rounding (>=.5) 3.0

Other math capabilities The % operator is modulus - it means return the remainder after dividing by the number. It is useful to see if something divides evenly into a number >>> 10 / 3 3 >>> 10 % 3 # 10 / 3 is 3 with remainder of 1 1 >>> 10 / 2 5 >>> 10 % 2 # 10 / 2 is 5 with a remainder of 0 0 This can be useful to see if something is "Modulo" something (or Mod) -- really useful when looking at sequence data and checking to see if it will translate -- is the length/value mod 3 == 0 - means it is divisible perfectly by 3. 8 / 19

Strings Quotes can define the different special characters and use of strings >>> 'break dance' 'break dance' >>> "break dance" 'break dance' >>> "don't break dance" "don't break dance" >>> 'don\'t break dance' "don't break dance" >>> ('concatenate ' 'these ' 'together') 'concatenate these together' 9 / 19

Variables Data can be assigned to variables. Variables don't exist until they are declared. The = is used for assignment. Some modifiers allow for modifying variable in place += add to the value of the variable -=, /=, *= are other >>> d = 0 # declare the variable d >>> print("d is ", d) d is 0 >>> print("e is ", e) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'e' is not defined >>> d=8*7 >>> print(d) 56 >>> d += 100 >>> print(d) 156 10 / 19

String functions Documented well in the python string library code. string.find(substring,[,starting[,end]]) Find a substring within a string >>> str = "Jumping cow over the moon" >>> str.find("cow") 8 >>> str.find("o") # start searching from beginning 9 >>> str.find("o",12) # start searching after character 12 22 string.split(separator, max_split) Split a string into a list based on a separator (great for column delimited data!). max_splits specifies if it should stop after N separators are found >>> str = "Jumping cow over the moon" >>> str.split(" ") ['Jumping', 'cow', 'over', 'the', 'moon'] >>> str.split(" ",2) ['Jumping', 'cow', 'over the moon'] 11 / 19

substring - extracting parts of a larger string You can query the string with the [ ] operator to get a subset of the string >>> msg="i am a golden god!" >>> msg[:4] # everything before position 4 'I am' >>> msg[7:13] # get a middle part from 7 15 'golden' >>> msg[14:] # get from 14 to the end 'god!' >>>msg[msg.find('am'):msg.find('!')] 'am a golden god' 12 / 19

Lists For collecting enumerated items >>> l = [ 2, 3, 5] >>> l[0] # lists start at 0 2 >>> l[1:3] 3,5 >>> l.append(10) >>> print(l) [2, 3, 5, 10] The sum() function will summate a list, len() will report how long it is. max() will report the largest number in a list >>> sum(l) 20 >>> len(l) 4 >>> max(l) 10 13 / 19

Lists other tools Lists can be sorted >>> l = [10,3,17,4] >>> l.sort() >>> l [3, 4, 10, 17] >>> ls = ['zf','fz','no','apple'] >>> ls.sort() >>> print(ls) ['apple', 'fz', 'no', 'zf'] 14 / 19

>>> q = "Symbol:NASDAQ=AAPL;Date:2015 10 01;Performance:Open=111.29,Close=109.56" >>> types = q.split(";") >>> print(types) ['Symbol:NASDAQ=AAPL', 'Date:2015 10 01', 'Performance:Open=111.29,Close=109.56'] >>> symbolset = types[0].split(":") >>> print(symbolset) ['Symbol', 'NASDAQ=AAPL'] >>> symbol = symbolset[1].split("=") >>> symbol ['NASDAQ', 'AAPL'] >>> print(symbol[1]) 'AAPL' >>> print(symbolset[1].split("=")[1]) 'AAPL' Using split to parse strings Starting with strings containing several parts which encode information you want. Symbol:NASDAQ=AAPL;Date:2015 10 01;Performance:Open=111.29,Close=109.56 Symbol:NASDAQ=MSFT;Date:2015 10 01;Performance:Open=46.65,Close=46.53 Extract some of the info using split

Documentation and Comments Comment lines start with a '#' There are also othe self-documentation feature to make it easy to generate readable documention for web or other sites. These are flanked with three double quotes like """Documentation here""" # can also be on multiple lines """This message could be concise, on multiple lines, and later I could tell you more about my program or function""" 16 / 19

repr function to display an object/string/number # use repr to print out literally the string >>> hello = 'hello world\n' >>> print(hello) hello world >>> print(repr(hello)) 'hello world\n' 17 / 19

More fancy printing Can use formatting to print some things out like these important numbers and phrase. >>> n = [1, 2, 'oh my god'] >>> print(n) [1, 2, 'oh my god'] # print things out with fancier printing >>> print(n[0].rjust(5), n[1].rjust(5), n[2].ljust(10)) AttributeError: 'int' object has no attribute 'rjust' >>> print( repr(n[0]).rjust(5), repr(n[1]).rjust(5), n[2].ljust(10)) 1 2 oh my god >>> print( repr(n[0]).ljust(5), repr(n[1]).rjust(5), n[2].ljust(10)) 1 2 oh my god >>> print( repr(n[0]).ljust(5), repr(n[1]).rjust(5), n[2].rjust(10)) 1 2 oh my god >>> print( repr(n[0]).rjust(5), repr(n[1]).rjust(5), n[2].rjust(12)) 1 2 oh my god >>> print( repr(n[0]).rjust(5), repr(n[1]).rjust(5), n[2].ljust(12)) 1 2 oh my god 18 / 19

Print out with placeholders The format is first a formatting string which contains symbols {}. These {} are replaced, in order, by the items that follow in the format() function applied. >>> a = 15 >>> b = 41 >>> print( "a + b = ", a+b) a + b = 56 >>> print( "{} + {} = {}".format(a,b,a+b)) 15 + 41 = 56 >>> print("{} ({}) + {} ({}) = {}".format("a",a,"b",b,a+b)) a (15) + b (41) = 56 19 / 19