Python Tutorial. Day 1

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

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

IPSL python tutorial: some exercises for beginners

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

Python - 2. Jim Eng

Introductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

Introductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October :50 PM

Python Objects. Charles Severance. Python for Everybody

Introduction to Python for Plone developers

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Programming environments. Introduction to Python. Adrian Copie, Ph.D.

Strings. Looping. dna = 'ATGTAGC' print(dna) In [1]: ATGTAGC. You can loop over the characters of a string using a for loop, as we saw on Tuesday:

Handling Strings and Bytes

Python Programming. Lecture 1. January 25 th. University of Pennsylvania 2010, Adam Aviv CIS 192 Spring

COMP 364: Classes, Objects, and Names

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Assignment 1: Getting Started with Python

Strings. Chapter 6. Python for Everybody

String Processing CS 1111 Introduction to Programming Fall 2018

Strings are actually 'objects' Strings

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

COLLEGE OF ENGINEERING, NASHIK-4

Babu Madhav Institute of Information Technology, UTU 2015

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT

Essentials for Scientific Computing: Introduction to Python Day 11 & 12

Script language: Python Data structures

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

6. Data Types and Dynamic Typing (Cont.)

DECODE SPECIAL OPERATOR, FORMAT OPERATOR CONTENTS TRIPLE QUOTES. IS a-to-z METHODS REPLACE L E N G T H E X P A N D T A B S ENC0D3

Introduction to Text-Processing. Jim Notwell 23 January 2013

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Module 3: Strings and Input/Output

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

Intro to Python. by Daniel Greenfeld

Python for Informatics

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

EE 355 Unit 17. Python. Mark Redekopp

Python Tutorial. Day 2

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

Introduction to String Manipulation

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

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

Zero Buffer Documentation

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

MULTIPLE CHOICE. Chapter Seven

Introduction to Python

Python Programming: Lecture 2 Data Types

CIS192 Python Programming. Robert Rand. August 27, 2015

CSCE 110 Programming I

Iterators & Generators

Collections. Lists, Tuples, Sets, Dictionaries

Topic 7: Lists, Dictionaries and Strings

Standard Types. Standard Types. Numbers

Lab 5: Function Types, Lists and Dictionaries, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Pathologically Eclectic Rubbish Lister

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

COMP1730/COMP6730 Programming for Scientists. Strings

Strings, Lists, and Sequences

Advanced Python. Executive Summary, Session 1

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

Lecture 6: A step back

CS 234 Python Review Part 2

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

CIS192 Python Programming

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

Data Structures. Lists, Tuples, Sets, Dictionaries

Python in 10 (50) minutes

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Some material adapted from Upenn cmpe391 slides and other sources

UNIVERSITÀ DI PADOVA. < 2014 March >

Scripting Languages. Python basics

Chapter 10: Creating and Modifying Text Lists Modules

Lecture 3. Strings, Functions, & Modules

Programming in Python

(CC)A-NC 2.5 by Randall Munroe Python

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

A Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015)

Exercise: The basics - variables and types

Physics 514 Basic Python Intro

Introduction to Python

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Introduction to Python! Lecture 2

Senthil Kumaran S

Bash scripting basics

Python. Executive Summary

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Beyond Blocks: Python Session #1

Programming with Python

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

1 Four reasons for learning python 3. 2 Installing Python 4

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

ENGR 102 Engineering Lab I - Computation

Transcription:

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 python2.4 print "Hello Kitty" # comments like shell as usual chmod +x FILENAME 3

Interactive Mode like shell, but unlike perl, python can be interactive $ python Python 2.4.1 (#1, Sep 21 2005, 14:17:33) [GCC 4.0.0 20041026 (Apple Computer, Inc. build 4061)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> built in debugger (will cover later) can preload code, then test: python -i FILE.py some platforms have line editing support (readline) 4

Assignment variable names as in shell: foo bar_3 ice9 only letters, digits (cannot start) and underscore unlike shell or perl, no sign to reference: >>> spam = 5 >>> spam * 3 15 5

Types: Integers usual math operators: + - * / ** % >>> 7 / 2 # integer division returns floor 3 >>> 7 / -2-4 can force whole answer in division: // >>> 2.3 / 2 1.1499999999999999 >>> 2.3 // 2 1.0 6

Types: Integer Base usual Unix base conventions leading zero is octal (base eight): >>> 033 27 >>> print oct(27) 033 leading 0x is hex (base 16): >>> 0x99 153 >>> print hex(153) 0x99 7

Types: Floating Point, Complex usual Unix/C exponent notation: 2.4e1 = 24.0 mixed types coerced up >>> (3 + 4) / 2 3 >>> (3 + 4) / 2.0 3.5 >>> (3 + 4) / 2.0 + 2j (3.5+2j) complex numbers created with function >>> complex(2,1) (2+1j) 8

Types: more Complex complex literals also possible use properties real and imag to decompose: >>> f = (2+1j) * (3+2j) >>> f.real 4.0 >>> f.imag 7.0 9

Types: Sequences all sequences take similar operations element reference: s[1] slice: s[3:5] length function: len(s) iteration: for elt in s: print elt 10

finding element: s.index( item ) testing membership: if eggs in s:

Sequences: Lists (arrays) list literal with square brackets: [2, 3, 5] any type can be an element: ["a", 2, 3.14] append: s.append("spam") change item: s[3] = "eggs" empty list: f = [] 11

Sequences: Tuple arrays are mutable: you can change elements tuples are immutable (immutable sequences take less memory) library functions often return tuples access functions work the same tuple literal: f = (2, 3, 66) 12

Sequences: String strings are another immutable sequence no difference between single and double quote, a, "a", "How s it going?" multi-line strings in triple quotes, wow, """wow""" normal Unix/C string escapes work as expected >>> print "a\tb\tc\n" a b c >>> 13

>>> s = "This is a test." >>> s[0] T >>> s[-1]. >>> s[4:8] is >>> s[:4] This >>> s[-4:] est. >>> s.split() [ This, is, a, test. ] >>> moo.strip() moo Cutting up Strings 14

OOPy Digression all types in Python are object oriented methods are simply functions that apply to an object notation is like C/C++: and method, s.split() a dot separating object all types have methods; methods not all literals can call 15

Python is introspective: you can ask types what they can do with function dir >>> f = "spam" >>> dir(f) [ add, class, contains, delattr, doc, eq, ge, getattribute, getitem, getnewargs, getslice, gt, hash, init, le, len, lt, mod, mul, ne, new, reduce, reduce_ex, repr, rmod, rmul, setattr, str, capitalize, center, count, decode, encode, endswith, expandtabs, find, index, isalnum, isalpha, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, replace, rfind, rindex, rjust, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill ] >>>

Doc strings Functions and methods can have documentation strings Use the attribute doc returns a string, so use print to look at it >>> >>> print f.strip. doc S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping >>> 16

Strings: Formatting like C printf format strings marked with % operator simplest format is %s, which converts all types to a string string % [item tuple ] 17

>>> (a, b, c) = (1, 2, 3) # note tuple assignment >>> "%s + %s = %s" % (a, b, a + b) 1 + 2 = 3 >>> print """ %s... %s... + %s... ----... %s""" % (a, b, c, a + b + c) 1 2 + 3 ---- 6 >>> print "%s" % w00t w00t >>> 18

Types: Collections As of Python 2.4 there are two types of collections collections are unordered dictionary: a hash table set: a collection of unique items (2.4) 19

Collections: Dictionaries literal: {key:item,...}, empty {} access and set like a list: d[ name ] = Palin method items returns list of (key, item) tuples method keys returns list of only keys method values returns list of only values method get retrieves value, with default 20

>>> d = { a :1, b :3, pi :3.14159} >>> d[ c ] = 42 >>> d { a : 1, pi : 3.1415899999999999, c : 42, b : 3} >>> d[ f ] Traceback (most recent call last): File "<stdin>", line 1, in? KeyError: f >>> d.get( f, 22) 22 >>> d.keys() [ a, pi, c, b ] >>> d.items() [( a, 1), ( pi, 3.1415899999999999), ( c, 42), ( b, 3)] >>> "pi is %(pi)s" % d # note "%(KEY)s" format pi is 3.14159 >>> 21

Collections: Sets new in Python 2.4 an unordered collection of unique items may not contain mutable items (no lists or dicts) requires function to create: f = set() set can take a single argument, any sequence type 22

method add adds elements union: s1 s2; intersection s1 & s2

>>> f = set() >>> f set([]) >>> f.add( ll ) >>> g = set("abcde") >>> g set([ a, c, b, e, d ]) >>> g = set("abcdeab") >>> g set([ a, c, b, e, d ]) >>> f g set([ a, c, b, e, d, ll ]) >>> 23

Type Conversion base types have conversion functions int, float, complex, long, str, list, tuple, dict, set most work as expected dict expects a sequence of sequences 24

remove duplicate entries (order lost): >>> f = [1, 2, 5, 2, 4, 1, 3, 6, 2, 6, 4, 2, 3] >>> f = list(set(f)) >>> f [1, 2, 3, 4, 5, 6] unlike perl, string to number conversion not automatic >>> str(int("4") + float("3.14159e2")) 318.159 >>> 25

Next Week control structures functions details on type methods basic exception handling 26