Single Source Python 2 3

Size: px
Start display at page:

Download "Single Source Python 2 3"

Transcription

1 Single Source Python 2 3 May 21, Single Source Python 2/3 1.1 A Tutorial at PyData Berlin Dr. Mike Müller Python Academy GmbH & Co. KG PyData Berlin 2016 Berlin, Germany 2 Overview Motivation Major differences between Python 2 and 3 Conversion strategies Single source Roll your own Use a library python-future.org 3 Motivation Python 3.0 was released 2008 Python 2 (2.7) still widely used Supporting only major Python version is often not an option Single source can be a good solution 1

2 4 Overview of important Python 2/3 differences Many small changes You might not encounter many of them Lot s of cleanups of warts Many (partially) backported to Python 2.7 Very few real syntax incompatibility between 2 and 3 5 print is a function likely the most obvious one but is pretty easy to fix from future import print function print(value,..., sep=, end= \n, file=sys.stdout, flush=false) In [3]: for x in range(10): print(x, end= ) In [4]: print(*range(10), sep= ) Iterators are everywhere zip() map() In [6]: zip( abc, xyz ) Out[6]: <zip at 0x1050ae548> In [7]: list(zip( abc, xyz )) Out[7]: [( a, x ), ( b, y ), ( c, z )] In [8]: map(str.upper, abc ) Out[8]: <map at 0x1050ad198> In [9]: list(map(str.upper, abc )) Out[9]: [ A, B, C ] 7 range() a.k.a. xrange() ++ range() just like xrange() no limit slice-able In [10]: range(10) Out[10]: range(0, 10) 2

3 In [13]: range(int(1e100)) Out[13]: range(0, In [14]: %%python2 xrange(int(1e100)) Traceback (most recent call last): File "<stdin>", line 2, in <module> OverflowError: Python int too large to convert to C long In [15]: r = range(10) r[2:7] Out[15]: range(2, 7) In [16]: %%python2 xr = xrange(10) xr[2:7] Traceback (most recent call last): File "<stdin>", line 3, in <module> TypeError: sequence index must be integer, not slice 8 Key views dict.keys() returns a view Python 2: list views are more efficient they update In [28]: d = { a : 100, b : 200, c : 300} k = d.keys() k Out[28]: dict keys([ b, a, c ]) In [29]: d[ x ] = 400 k Out[29]: dict keys([ b, x, a, c ]) 9 No apple-orange comparisons only defined comparisons for many the most important change In [18]: 1 < TypeError Traceback (most recent call last) 3

4 <ipython-input-18-9ee3bb6f2cf3> in <module>() ----> 1 1 < 1 TypeError: unorderable types: int() < str() In [20]: %%python2 print(1 < 1 ) True In [21]: 100 < None TypeError Traceback (most recent call last) <ipython-input-21-ab68f0474b07> in <module>() ----> < None TypeError: unorderable types: int() < NoneType() In [22]: %%python2 print(100 < None) False 10 Integers without limits long became int no big change difference has been small in Python 2 In [23]: Out[23]: In [25]: %%python2 print(repr( )) L 11 Mathematical division divide integers just like in math by default from future import division In [30]: 1 / 2 Out[30]: 0.5 4

5 In [32]: 1 // 2 Out[32]: 0 In [33]: %%python2 0 0 print(1 / 2) print(1 // 2) In [34]: %%python from future import division print(1 / 2) print(1 // 2) 12 Strings are always unicode Maybe the biggest change, depending on the use case Python 2: weak distinction between bytes and strings 13 Prefixing Python 2: abc : bytestring u abc : unicode string Python 3: abc : string unicode b abc : bytestring both: u abc : string unicode b abc : bytestring 14 Source code encoding default encodings: Python 2 ascii Python 3 utf-8 both, explicit: # -*- coding: utf-8 -*- 5

6 15 Cleanup - Modern Python 2 can do no classic classes anymore no backticks, use repr() <> gone exception instances only with as, old comma syntax is gone literal octal numbers with 0o prefix, e.g. 0o7 open() is now io.open() use next() not obj.next() use functools.reduce() instead of buil-in reduce() use func(*args) instead of apply(func, args) 16 Cleanup - Modern Python 2 can do with a little help raw input() > input(), input() > eval(input()) importlib.reload() instead of reload() 17 Cleanup - Modern Python 2 can do with help of a library exec statement turned into a function metaclasses as keyword argument in class definition, no metaclass anymore super() without class and self round() uses a different rule round(2.5) == 2, instead of round(2.5) == 3 18 New syntax - Python 3 only keyword-only arguments nonlocal extended unpacking of iterables True, False, and None are keywords, yeah variables from list comprehensions don t leak anymore, great exception instances only available in except block 19 Re-structuring of the standard library Removal of old, unused modules gopherlib renaming to comply with PEP8, ConfigParser > configparser, StringIO moved into io grouping of related modules like http or dbm 20 Write your own compatibility layer use modern Python 2 (exceptions, next) future version testing re-defining built-ins standard lib packports handling strings and bytes IO 6

7 21 Never use classic classes In [73]: class A(object): pass 22 Don t use ancient features no backticks, use repr() never use <> prefix literal octal numbers with 0o prefix, e.g. 0o7 use functools.reduce() instead of buil-in reduce() use func(*args) instead of apply(func, args) In [136]: %%python2 a = a print( a ) a In [79]: a = a print( a ) File "<ipython-input-79-2c78c9df6889>", line 2 print( a ) ^ SyntaxError: invalid syntax In [81]: a = a print(repr(a)) a 23 Exceptions always with as In [55]: %%python2 try: 1 / 0 except ZeroDivisionError, err: pass print(err) integer division or modulo by zero In [56]: try: 1 / 0 except ZeroDivisionError, err: pass print(err) 7

8 File "<ipython-input-56-d4e7da7453b9>", line 3 except ZeroDivisionError, err: ^ SyntaxError: invalid syntax In [82]: try: 1 / 0 except ZeroDivisionError as err: pass In [83]: %%python2 try: 1 / 0 except ZeroDivisionError as err: pass 24 Use io.open you can specify an encoding In [84]: import io io.open is open Out[84]: True In [87]: %%python2 from io import open In [88]: open(file, mode= r, buffering=-1, encoding=none, errors=none, newline=none, closefd=true, open 25 Use next() In [93]: i = iter( abc ) print(next(i)) a In [92]: %%python2 i = iter( abc ) print(next(i)) a 26 Travel to the future add this line at the beginning of all your source files In [137]: from future import absolute_import, division, print_function 8

9 27 Unicode litertals can be problematic In [138]: from future import unicode_literals not always recommended good for 3 > 2 much less useful for 2 > 3 e.g., may cause problems with library calls (e.g. paths) 28 Version Testing always test for < 3 or > 2 never == 2 or == 3 Python 4 will be comming 29 Re-defining built-ins In [106]: %%python2 from future import absolute_import, division, print_function import sys if sys.version_info.major < 3: input = raw_input range = xrange from io import open from itertools import izip as zip, imap as map, ifilter as filter print(filter) <type itertools.ifilter > 30 Standard library packports several libraries are backported lru cache: backports.functools lru cache pathlib2 In [107]: try: from functools import lru_cache except ImportError: from backports.functools_lru_cache import lru_cache 31 Your own compatibility layer use of all seems justified In [ ]: # %load compat.py from future import absolute_import, division, print_function 9

10 import sys all = [] if sys.version_info.major < 3: input = raw_input range = xrange from io import open from itertools import (izip as zip, imap as map, ifilter as filter) all = [ input, filter, map, open, range, zip ] In [109]: %%python3 <class range > from compat import * print(range) In [110]: %%python2 <type xrange > from compat import * print(range) 32 Using help six Python 2.5 and up, latest version only 2.6 future Python 2.6 and up 33 Using python-future.org does the work for you and is much better at it makes Python 2 behave largely like Python 3 34 Options starting from scratch starting from Python 2 starting from Python 3 automatic conversion porting philosophy 35 Starting from scratch at the beginng of your source files add: 10

11 In [112]: from future import (absolute_import, division, print_function, unicode_literals) from builtins import * write standard Python 3 without th Python 3 only parts 36 Starting from Python 2 In [ ]: # %load py2sample.py import StringIO fobj = StringIO.StringIO("""Hello world line1 = fobj.next() print Done In [ ]: $ futurize -w py2sample.py RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored py2sample.py --- py2sample.py (original) +++ py2sample.py -1,10 from future import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import next -import StringIO +import io -fobj = StringIO.StringIO("""Hello world +fobj = io.stringio("""hello world line1 = next(fobj) RefactoringTool: Files that were modified: RefactoringTool: py2sample.py In [ ]: # %load py2sample.py from future import print_function from future import standard_library standard_library.install_aliases() import io 11

12 fobj = io.stringio("""hello world line1 = next(fobj) print( Done ) 37 Backup py2sample.py.bak 38 Two-stage approach first stage applies only save changes no imports from future produces modern, 2.6-compatible code result may not run with Python 3 yet In [ ]: $ futurize -w --stage1 py2sample.py RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored py2sample.py --- py2sample.py (original) +++ py2sample.py -1,3 +from future import print_function import -6,6 fobj = StringIO.StringIO("""Hello world -line1 = fobj.next() +line1 = next(fobj) -print Done +print( Done ) RefactoringTool: Files that were modified: RefactoringTool: py2sample.py In [ ]: # %load py2sample.py from future import print_function import StringIO fobj = StringIO.StringIO("""Hello world 12

13 line1 = next(fobj) print( Done ) In [ ]: $ futurize -w --stage2 py2sample.py RefactoringTool: Refactored py2sample.py --- py2sample.py (original) +++ py2sample.py -1,10 from future import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import next -import StringIO +import io -fobj = StringIO.StringIO("""Hello world +fobj = io.stringio("""hello world line1 = next(fobj) RefactoringTool: Files that were modified: RefactoringTool: py2sample.py In [ ]: # %load py2sample.py from future import print_function from future import standard_library standard_library.install_aliases() from builtins import next import io fobj = io.stringio("""hello world line1 = next(fobj) print( Done ) 39 Going fix-by-fix more than fifty different fixes futurize --list-fixes In [ ]: $ futurize -f lib2to3.fixes.fix_next py2sample.py RefactoringTool: Refactored py2sample.py --- py2sample.py (original) +++ py2sample.py -4,6 13

14 fobj = StringIO.StringIO("""Hello world -line1 = fobj.next() +line1 = next(fobj) print Done RefactoringTool: Files that need to be modified: RefactoringTool: py2sample.py In [ ]: futurize -f lib2to3.fixes.fix_has_key py2sample.py RefactoringTool: No files need to be modified. 40 Strategies need to have tests (coverage) create environments for Python 2 and 3 (conda) version control all steps either go fix-by-fix (>50) or go stage-by-stage (2 steps) 41 Starting from Python 3 In [116]: # %load py3sample.pya zip( abc, range(3)) Out[116]: <zip at 0x1051d3f88> pasteurize -w py3sample.py In [ ]: # %load py3sample.py from future import unicode_literals from future import print_function from future import division from future import absolute_import from builtins import zip from builtins import range from future import standard_library standard_library.install_aliases() zip( abc, range(3)) old version in py3sample.py.bak In [ ]: 14

Python 3000 and You. Guido van Rossum PyCon March 14, 2008

Python 3000 and You. Guido van Rossum PyCon March 14, 2008 Python 3000 and You Guido van Rossum PyCon March 14, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print

More information

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008 Python 3000 and You Guido van Rossum EuroPython July 7, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print

More information

Python 2-to-3 Migration Guide

Python 2-to-3 Migration Guide Introduction Python 1 3 will be 10 years old in December of this year (2018). It has been mature and robust for a while now. Yet, because of inertia, Python 2 is still alive and well in many organizations.

More information

Porting Python 2 Code to Python 3 Release 2.7.6

Porting Python 2 Code to Python 3 Release 2.7.6 Porting Python 2 Code to Python 3 Release 2.7.6 Guido van Rossum Fred L. Drake, Jr., editor Contents November 10, 2013 Python Software Foundation Email: docs@python.org 1 Choosing a Strategy ii 1.1 Universal

More information

Programming in Python 3

Programming in Python 3 Programming in Python 3 Programming transforms your computer from a home appliance to a power tool Al Sweigart, The invent with Python Blog Programming Introduction Write programs that solve a problem

More information

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function Files Files File I/O Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function open(file, mode='r', buffering=-1, encoding=none,...

More information

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Python. How You Can Do More Interesting Things With Python (Part II)

Python. How You Can Do More Interesting Things With Python (Part II) Python How You Can Do More Interesting Things With Python (Part II) Python for Statement for in : statement-block my_dict = { k1 : 1, k2 : 2 } for (k,v) in my_dict.items(): print(

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d. Gaddis: Starting Out with Python, 2e - Test Bank Chapter Two MULTIPLE CHOICE 1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical

More information

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

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

CircuitPython 101: Working with Lists, Iterators and Generators

CircuitPython 101: Working with Lists, Iterators and Generators CircuitPython 101: Working with Lists, Iterators and Generators Created by Dave Astels Last updated on 2018-11-01 12:06:56 PM UTC Guide Contents Guide Contents Overview List Functions Slicing Filtering

More information

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter Variables, Expressions, and Statements Chapter 2 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. http://creativecommons.org/licenses/by/3.0/.

More information

Python 3 guide for scientists Documentation. Release

Python 3 guide for scientists Documentation. Release Python 3 guide for scientists Documentation Release Adrian Price-Whelan, Stephanie Douglas, Stuart Mumford, Nathan Feb 07, 2018 Contents 1 Contents 3 1.1 Useful Python 3 features.........................................

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

Python debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

The State of Python. and the web. Armin Ronacher

The State of Python. and the web. Armin Ronacher The State of Python and the web Armin Ronacher // @mitsuhiko Who am I Armin Ronacher (@mitsuhiko) Founding Member of the Pocoo Team we're doing Jinja2, Werkzeug, Flask, Pygments, Sphinx and a bunch of

More information

Variables, Expressions, and Statements

Variables, Expressions, and Statements Variables, Expressions, and Statements Chapter 2 Python for Informatics: Exploring Information www.pythonlearn.com Constants Fixed values such as numbers, letters, and strings are called constants because

More information

CIS192 Python Programming. Robert Rand. August 27, 2015

CIS192 Python Programming. Robert Rand. August 27, 2015 CIS192 Python Programming Introduction Robert Rand University of Pennsylvania August 27, 2015 Robert Rand (University of Pennsylvania) CIS 192 August 27, 2015 1 / 30 Outline 1 Logistics Grading Office

More information

msgpack Documentation

msgpack Documentation msgpack Documentation Release 0.4 Author 2017-11-04 Contents 1 API reference 3 Python Module Index 9 i ii MessagePack is a efficient format for inter language data exchange. Contents 1 2 Contents CHAPTER

More information

Python 3: The Next Generation

Python 3: The Next Generation Python 3: The Next Generation Wesley J. Chun wescpy@gmail.com @wescpy http://corepython.com OSCON (Portland, OR) July 2011 About the Speaker Software engineer by profession Currently at Google (cloud products)

More information

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

python 01 September 16, 2016

python 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 information

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

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

Advanced Python Subjects. By Imri Goldberg plnnr.com

Advanced Python Subjects. By Imri Goldberg   plnnr.com Advanced Python Subjects By Imri Goldberg www.algorithm.co.il plnnr.com Introduction Many people I know come to Python from C/C++. Including me! They bring with them many unpythonic idioms: inheritance

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 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 information

A Little Python Part 1. Introducing Programming with Python

A Little Python Part 1. Introducing Programming with Python A Little Python Part 1 Introducing Programming with Python Preface Not a complete course in a programming language Many details can t be covered Need to learn as you go My programming style is not considered

More information

Introduction to Bioinformatics

Introduction to Bioinformatics Introduction to Bioinformatics Variables, Data Types, Data Structures, Control Structures Janyl Jumadinova February 3, 2016 Data Type Data types are the basic unit of information storage. Instances of

More information

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

More information

Argparse Tutorial Release 2.7.9

Argparse Tutorial Release 2.7.9 Argparse Tutorial Release 2.7.9 Guido van Rossum and the Python development team December 10, 2014 Python Software Foundation Email: docs@python.org Contents 1 Concepts 1 2 The basics 2 3 Introducing Positional

More information

Python Tutorial. Day 1

Python 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 information

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

Sequence 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 information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Eric Kutschera University of Pennsylvania January 30, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 January 30, 2015 1 / 31 Questions Homework

More information

Introduction to Python

Introduction to Python Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology Python Python high-level

More information

Porting Code to Python 3 with 2to3

Porting Code to Python 3 with 2to3 A P P E N D I X A Porting Code to Python 3 with 2to3 Virtually all Python 2 programs need at least some tweaking to run properly under Python 3. To help with this transition, Python 3 comes with a utility

More information

Exceptions CS GMU

Exceptions CS GMU Exceptions CS 112 @ GMU Exceptions When an unrecoverable action takes place, normal control flow is abandoned: an exception value crashes outwards until caught. various types of exception values can be

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital PYTHON FOR MEDICAL PHYSICISTS Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital TUTORIAL 1: INTRODUCTION Thursday 1 st October, 2015 AGENDA 1. Reference list 2.

More information

Table of Contents EVALUATION COPY

Table 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 information

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

What we already know. more of what we know. results, searching for This 6/21/2017. chapter 14 What we already know chapter 14 Files and Exceptions II Files are bytes on disk. Two types, text and binary (we are working with text) open creates a connection between the disk contents and the program

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

Python Reference (The Right Way) Documentation

Python Reference (The Right Way) Documentation Python Reference (The Right Way) Documentation Release 0.1 Jakub Przywóski Sep 30, 2017 Contents 1 Contents 1 1.1 Introduction............................................... 1 1.2 Definitions................................................

More information

Python Working with files. May 4, 2017

Python Working with files. May 4, 2017 Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output

More information

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers Python Tutorial Lecture for EE562 Artificial Intelligence for Engineers 1 Why Python for AI? For many years, we used Lisp, because it handled lists and trees really well, had garbage collection, and didn

More information

Introduction to Python

Introduction to Python Introduction to Python Michael Krisper Thomas Wurmitzer October 21, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 1 / 26 Schedule Tutorium I Dates & Deadlines Submission

More information

Course Title: Python + Django for Web Application

Course Title: Python + Django for Web Application Course Title: Python + Django for Web Application Duration: 6 days Introduction This course offer Python + Django framework ( MTV ) training with hands on session using Eclipse+Pydev Environment. Python

More information

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

Intro 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 information

PyQ Documentation. Release 3.8. Enlightenment Research, LLC.

PyQ Documentation. Release 3.8. Enlightenment Research, LLC. PyQ Documentation Release 3.8 Enlightenment Research, LLC. November 21, 2016 Contents 1 Quickstart 3 2 Table of Contents 5 2.1 Installation................................................ 5 2.1.1 OS Support...........................................

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Python File Modes. Mode Description. Open a file for reading. (default)

Python File Modes. Mode Description. Open a file for reading. (default) UNIT V FILES, MODULES, PACKAGES Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

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

Interactive 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 information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

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

Interactive 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 information

Python for C programmers

Python for C programmers Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

CIS192: Python Programming

CIS192: 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 information

CS 11 python track: lecture 3. n Today: Useful coding idioms

CS 11 python track: lecture 3. n Today: Useful coding idioms CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise

More information

Lecture 3. Strings, Functions, & Modules

Lecture 3. Strings, Functions, & Modules Lecture 3 Strings, Functions, & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students

More information

Organization of Programming Languages CS 3200/5200D. Lecture 12

Organization of Programming Languages CS 3200/5200D. Lecture 12 Organization of Programming Languages CS 3200/5200D Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Scripting Languages: Python Designed by Guido van Rossum in

More information

Python - a Dynamic Programming Language. Guido van Rossum May 31, 2007

Python - a Dynamic Programming Language. Guido van Rossum May 31, 2007 Python - a Dynamic Programming Language Guido van Rossum May 31, 2007 Outline What is Python? Origins, history and design philosophy Python today The future: Python 3000 Links, Q&A 3 Copyright 2007 Google

More information

B.V. Patel Institute of BMC & IT, UTU 2014

B.V. Patel Institute of BMC & IT, UTU 2014 BCA 3 rd Semester 030010301 - Java Programming Unit-1(Java Platform and Programming Elements) Q-1 Answer the following question in short. [1 Mark each] 1. Who is known as creator of JAVA? 2. Why do we

More information

Python for Informatics

Python 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 information

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

06/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 information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

Computational Physics

Computational Physics Computational Physics Intro to Python Prof. Paul Eugenio Department of Physics Florida State University Jan 16, 2018 http://comphy.fsu.edu/~eugenio/comphy/ Announcements Read Chapter 2 Python programming

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3] What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)

More information

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

pybdg Documentation Release 1.0.dev2 Outernet Inc

pybdg Documentation Release 1.0.dev2 Outernet Inc pybdg Documentation Release 1.0.dev2 Outernet Inc April 17, 2016 Contents 1 Source code 3 2 License 5 3 Documentation 7 Python Module Index 15 i ii Bitloads, or bit payloads, are compact payloads containing

More information

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

More information

Getting Started Values, Expressions, and Statements CS GMU

Getting Started Values, Expressions, and Statements CS GMU Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

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

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

CS Advanced Unix Tools & Scripting

CS Advanced Unix Tools & Scripting & Scripting Spring 2011 Hussam Abu-Libdeh slides by David Slater March 4, 2011 Hussam Abu-Libdeh slides by David Slater & Scripting Python An open source programming language conceived in the late 1980s.

More information

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

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France [Software Development] Python (Part A) Davide Balzarotti Eurecom Sophia Antipolis, France 1 Homework Status 83 registered students 41% completed at least one challenge 5 command line ninjas 0 python masters

More information

Introduction to Python

Introduction to Python Introduction to Python Michael Krisper Thomas Wurmitzer March 22, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 1 / 27 Schedule Tutorium Dates & Deadlines Submission System

More information

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

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was

More information

SD314 Outils pour le Big Data

SD314 Outils pour le Big Data Institut Supérieur de l Aéronautique et de l Espace SD314 Outils pour le Big Data Functional programming in Python Christophe Garion DISC ISAE Christophe Garion SD314 Outils pour le Big Data 1/ 35 License

More information

semidbm Documentation

semidbm Documentation semidbm Documentation Release 0.4.0 James Saryerwinnie Jr September 04, 2013 CONTENTS i ii semidbm is a pure python implementation of a dbm, which is essentially a persistent key value store. It allows

More information

redis-lua Documentation

redis-lua Documentation redis-lua Documentation Release 2.0.8 Julien Kauffmann October 12, 2016 Contents 1 Quick start 3 1.1 Step-by-step analysis........................................... 3 2 What s the magic at play here?

More information

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

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

What's New in Python 2.2

What's New in Python 2.2 What's New in Python 2.2 LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation guido@python.org guido@zope.com Overview Appetizers Nested Scopes Int/Long

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

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

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : } Chapter 8 More Data Structures We have seen the list data structure and its uses. We will now examine two, more advanced data structures: the set and the dictionary. In particular, the dictionary is an

More information

Computing with Numbers

Computing with Numbers Computing with Numbers Example output: Numeric Data Types Numeric Data Types Whole numbers are represented using the integer data type (int for short).values of type int can be positive or negative whole

More information