The UOB Python Lectures: Part 1 - Introduction to Python

Size: px
Start display at page:

Download "The UOB Python Lectures: Part 1 - Introduction to Python"

Transcription

1 The UOB Python Lectures: Part 1 - Introduction to Python Hesham al-ammal University of Bahrain 18/3/2013 Blog and slides: heshaaam.wordpress.com 1 1

2 Feel like flying? Ref: xkcd.com 2 2

3 History: Name Python is named based on the British comedy series Monty Python s Flying Circus Not the constricting snake 3 3

4 History: BDFL Guido van Rossom (Google 2012) Principal author and Benevolent dictator (BDFL), central role in deciding direction of Python Created in 1990 at CWI, Netherlands 4 Python s Logo

5 Interpreted vs Compiled Programming Languages Compiled Interpreted C C++ Java Python Perl Lisp Interactive vs. Batch 5 5

6 Interactive Python $ python Python 2.7 (#1, Feb , 00:02:06) Type "help", "copyright", "credits" or "license" for more information. >>> >>> the_world_is_flat = 1 >>> if the_world_is_flat:... print "Be careful not to fall off!"... Be careful not to fall off! 6 6

7 Batch mode Edit #! /usr/bin/env python the_world_is_flat=1 if the_world_is_flat: print "Be careful not to fall off" Save file.py Debug/Run Python file.py 7 7

8 Python Versions We will be using version 2.7 Versions backward compatible Version 3 is totally different fork of Python and thus not outward compatible Version 2 will continue for a while 8 8

9 Tutorial Outline Data Types: Numbers, Strings, Lists Control Flow: If, For, break, continue,... Data structures Modules Input and output Classes The Standard Library Ref: 9 9

10 Integers Integer division: floor Power No limit to integer arithmetic except mempr (arbitrary long integers) >>> 7/3 2 >>> 2** L

11 Floating Point / Complex Full support for floating point numbers and mixed arithmetic Complex numbers are also supported 11 >>> 3 * 3.75 / >>> 7.0 / >>> 1j * 1J (-1+0j) >>> 1j * complex(0,1) (-1+0j) >>> 3+1j*3 (3+3j) >>> (3+1j)*3 (9+3j) >>> (1+2j)/(1+1j) ( j) 11

12 Strings Strings can be enclosed in single quotes or double quotes Notice special characters Multiple line strings are possible >>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.' 12 12

13 Strings (cont.) Strings can be concatinated Strings can be subscripted >>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' '<HelpAHelpAHelpAHelpAHelpA>' >>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp' 13 13

14 Slicing strings >>> word[:2] # The first two characters 'He' >>> word[2:] # Everything except the first two characters 'lpa' 14 14

15 Assigning to strings is an error >>> word[0] = 'x' Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: object does not support item assignment >>> word[:1] = 'Splat' Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: object does not support slice assignment However, this is OK: creating new strings >>> 'x' + word[1:] 'xelpa' >>> 'Splat' + word[4] 'SplatA' 15 15

16 Negative string slicing Indices may be negative numbers, to start counting from the right. H e l p A Imagine numbers between characters >>> word[-1] # The last character 'A' >>> word[-2] # The last-but-one character 'p' >>> word[-2:] # The last two characters 'pa' >>> word[:-2] # Everything except the last two characters 'Hel' 16 16

17 Lists Many compound data types in Python Most verstaile is a list Comma-separated between square brackets All slice operations return new lists >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> 3*a[:3] + ['Boo!'] ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!'] >>> a[:] ['spam', 'eggs', 100, 1234] 17 17

18 More about lists >>> # Replace some items:... a[0:2] = [1, 12] >>> a [1, 12, 123, 1234] >>> # Remove some: like strings... a[0:2] = [] >>> a [123, 1234] >>> # Insert some:... a[1:1] = ['bletch', 'xyzzy'] >>> a [123, 'bletch', 'xyzzy', 1234] >>> # Insert (a copy of) itself at the beginning >>> a[:0] = a >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] >>> # Clear the list: replace all items with an empty list >>> a[:] = [] >>> a [] Lists are not immutable 18 18

19 Even more about lists You can use len() Lists can be nested 19 >>> a = ['a', 'b', 'c', 'd'] >>> len(a) 4 >>> q = [2, 3] >>> p = [1, q, 4] >>> len(p) 3 >>> p[1] [2, 3] >>> p[1][0] 2 >>> p[1].append('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra'] 19

20 Our first useful program Interactive mode Indentation defines block >>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b Multiple assignments In other languages: temp = a a = b b = temp In Python: b, a = a, b 20 20

21 Our first useful program Batch mode #! /usr/bin/env python # Fibonacci series: # the sum of two elements defines the next a, b = 0, 1 while b < 10: print b a, b = b, a+b 21 21

22 Interlude And now for something completely different 22 22

23 The Zen of Python 1 Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. 23 UOB Students 23

24 The Zen of Python 2 In the face of ambiguity, refuse the temptation to guess. There should be one and preferably only one obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea let's do more of those! 24 24

25 Coding style: Readability Counts Programs must be written for people to read, and only incidentally for machines to execute. Abelson & Sussman, Structure and Interpretation of Computer Programs 25 25

26 Back to our regularly scheduled programming 26 26

27 More control statements: if >>> x = int(raw_input("please enter an integer: ")) Please enter an integer: 42 >>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More'... More 27 27

28 for loops Unlike for loops in C++, it iterates on elements of a sequence like a list or a string. For exmaple (no pun intended): >>> # Measure some strings:... words = ['cat', 'window', 'defenestrate'] >>> for w in words:... print w, len(w)... cat 3 window 6 defenestrate

29 for loops and slicing If you need to edit the sequence make a copy of the list using slicing >>> for w in words[:]: # Loop over a slice copy of list.... if len(w) > 6:... words.insert(0, w)... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] 29 29

30 The range() function For iterating over a range of numbers >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)):... print i, a[i]... 0 Mary 1 had 2 a 3 little 4 lamb 30 30

31 Enough with control structures You just should know that there are more control structures when you need them: break continue pass 31 31

32 Defining Functions >>> def fib(n): # write Fibonacci series up to n... """Print a Fibonacci series up to n.""" Documentation... a, b = 0, 1 string literal... while a < n:... print a,... a, b = b, a+b... >>> # Now call the function we just defined:... fib(2000)

33 Return values >>> def fib2(n): # return Fibonacci series up to n... """Return a list containing the Fibonacci series up to n."""... result = []... a, b = 0, 1... while a < n:... result.append(a)... a, b = b, a+b... return result... >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] Method append belongs to the object result Functions without return just return None 33 33

34 More on functions: Default Arguments def ask_ok(prompt, retries=4, complaint='yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusing user') print complaint Notice the in keyword Options only the mandatory argument: ask_ok('do you really want to quit?') one of the optional arguments: ask_ok('ok to overwrite the file?', 2) all arguments: ask_ok('ok to overwrite the file?', 2, 'Come on, only yes or no!') 34 34

35 Things I will not mention in functions Arbitrary argument lists Lambda forms Documentation strings 35 35

36 Coding Style Use 4-space indentation, and no tabs. Wrap lines so that they don t exceed 79 characters. Use blank lines to separate functions and classes, and larger blocks of code inside functions. When possible, put comments on a line of their own. Use docstrings. Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4)

37 Data Structures 37 37

38 Lists and their methods 1 list.append(x) Add an item to the end of the list; equivalent to a[len(a):] = [x]. list.extend(l) Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L. list.insert(i, x) Insert an item at a given position

39 Lists and their methods 2 list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item. list.pop([i]) Remove the item at the given position in the list, and return it. list.index(x) Return the index in the list of the first item whose value is x

40 Lists and their methods 3 list.count(x) Return the number of times x appears in the list. list.sort() Sort the items of the list, in place. list.reverse() Reverse the elements of the list, in place

41 Lists as stacks >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] 41 41

42 Lists as queues use collections.deque which was designed to have fast appends and pops from both ends >>> from collections import deque >>> queue = deque(["eric", "John", "Michael"]) >>> queue.append("terry") # Terry arrives >>> queue.append("graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['michael', 'Terry', 'Graham']) 42 42

43 Functional Programming Tools 43 43

44 filter(function,sequence) >>> def f(x): return x % 2!= 0 and x % 3!= 0... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] 44 44

45 map(function, sequence) >>> def cube(x): return x*x*x... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 45 45

46 reduce(function, sequence) returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on. >>> def add(x,y): return x+y... >>> reduce(add, range(1, 11))

47 List comprehension You can do this >>> squares = [] >>> for x in range(10):... squares.append(x**2)... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] or get the same result with this squares = [x**2 for x in range(10)] 47 47

48 More list comprehension >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x!= y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] is equivalent to >>> combs = [] >>> for x in [1,2,3]:... for y in [3,1,4]:... if x!= y:... combs.append((x, y))... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 48 48

49 Dictionaries >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> tel.keys() ['guido', 'irv', 'jack'] >>> 'guido' in tel True Associative memory 49 49

50 What have we learned? Hopefully some basic syntax Python Phylosophy of Python All of the tools that you need, elegantly 50 50

51 What we haven t learnt The Python Standard Library Other useful libraries 51 51

52 Why Python? Python as glue: hundreds of libraries in C++, Fortran, etc. Almost no need for a second language. Quick prototyping, scripting, etc. Strong support for scientific computing. Support for web dev, mobile dev 52 52

53 Why Python? Open source, join the revolution Runs on all platforms Cython for high performance ipython (replace Mathematica) MatPlotLib (replace Matlab) 53 53

54 More Python? python.org The tutorial Many video lectures on many topics

55 ipython Powerful interactive shells (terminal and Qt-based). A browser-based notebook with support for code, text, mathematical expressions, inline plots and other rich media. Support for interactive data visualization and use of GUI toolkits. Flexible, embeddable interpreters to load into your own projects. Easy to use, high performance tools for parallel computing

56 56 56

57 Thank you for listening 57 57

Introduction to Python

Introduction to Python Introduction to Python Python: very high level language, has high-level data structures built-in (such as dynamic arrays and dictionaries). easy to use and learn. Can be used for scripting (instead of

More information

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011 Python Lists Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 5, 2011 Stéphane Vialette (LIGM UPEMLV) Python Lists October 5, 2011 1 / 31 Outline 1 Introduction 2 Methods 3 Lists as

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

Phys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 2

Phys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 2 Phys 60441 Techniques of Radio Astronomy Part 1: Python Programming LECTURE 2 Tim O Brien Room 3.214 Alan Turing Building tim.obrien@manchester.ac.uk Lists A compound data type (elements can be same type

More information

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline Python Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar December 28, 2011 1 Outline Introduction Installation and Use Distinct Features Python Basics Functional Example Comparisons with

More information

LECTURE 1. Getting Started with Python

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

OOP and Scripting in Python

OOP and Scripting in Python DIEE - Università degli Studi di Cagliari OOP and Scripting in Python Introduction Giuliano Armano DIEE Univ. di Cagliari Python Roots... Object Oriented Programming (C++, Modula-3, ABC, Icon) Scripting

More information

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More?

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More? Why Python? Introduction into Python Daniel Polani Properties: minimalistic syntax powerful high-level data structures built in scripting, rapid applications, and as we will se AI widely in use (a plus

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

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

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

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. May 28, Python Software Foundation

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. May 28, Python Software Foundation Python Tutorial Release 3.2.5 Guido van Rossum Fred L. Drake, Jr., editor May 28, 2014 Python Software Foundation Email: docs@python.org Contents 1 Whetting Your Appetite 3 2 Using the Python Interpreter

More information

Python Tutorial. Release 2.5. Guido van Rossum Fred L. Drake, Jr., editor. 19th September, Python Software Foundation

Python Tutorial. Release 2.5. Guido van Rossum Fred L. Drake, Jr., editor. 19th September, Python Software Foundation Python Tutorial Release 2.5 Guido van Rossum Fred L. Drake, Jr., editor 19th September, 2006 Python Software Foundation Email: docs@python.org Copyright 2001-2006 Python Software Foundation. All rights

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.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 information

Python Tutorial. Release 2.5. Guido van Rossum Fred L. Drake, Jr., editor. 19th September, Python Software Foundation

Python Tutorial. Release 2.5. Guido van Rossum Fred L. Drake, Jr., editor. 19th September, Python Software Foundation Python Tutorial Release 2.5 Guido van Rossum Fred L. Drake, Jr., editor 19th September, 2006 Python Software Foundation Email: docs@python.org Copyright 2001-2006 Python Software Foundation. All rights

More information

Learning R via Python...or the other way around

Learning R via Python...or the other way around Learning R via Python...or the other way around Dept. of Politics - NYU January 7, 2010 What We ll Cover Brief review of Python The Zen of Python How are R and Python the same, and how are they different

More information

CSC 221: Introduction to Programming. Fall 2013

CSC 221: Introduction to Programming. Fall 2013 CSC 221: Introduction to Programming Fall 2013 Python data, assignments & turtles Scratch programming review Python & IDLE numbers & expressions variables & assignments strings & concatenation input &

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

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

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

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

Inverse Ray Shooting Tutorial. Jorge Jiménez Vicente Dpto. Física Teórica y del Cosmos Universidad de Granada Spain

Inverse Ray Shooting Tutorial. Jorge Jiménez Vicente Dpto. Física Teórica y del Cosmos Universidad de Granada Spain Inverse Ray Shooting Tutorial Jorge Jiménez Vicente Dpto. Física Teórica y del Cosmos Universidad de Granada Spain Final goal Session I Introduction to Python Solving the lens equation Ray shooting basics

More information

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19 1 Decorators 2 Descriptors 3 Static Variables 4 Anonymous Classes Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, 2009 1 / 19 Decorator Pattern In object-oriented programming, the

More information

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

More information

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. October 19, Python Software Foundation

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. October 19, Python Software Foundation Python Tutorial Release 2.7.2 Guido van Rossum Fred L. Drake, Jr., editor October 19, 2011 Python Software Foundation Email: docs@python.org CONTENTS 1 Whetting Your Appetite 3 2 Using the Python Interpreter

More information

Introduction. What is this? What is Python? About this Tutorial. Additional Resources

Introduction. What is this? What is Python? About this Tutorial. Additional Resources Introduction What is this? This is a PDF snapshot of the Python Tutorial Wiki, prepared 2006-04-27. What is Python? Python is a powerful, yet easy to learn programming language. It has efficient high-level

More information

Python Tutorial. Release Guido van Rossum and the Python development team. December 10, Python Software Foundation

Python Tutorial. Release Guido van Rossum and the Python development team. December 10, Python Software Foundation Python 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 Whetting Your Appetite 3 2 Using the Python

More information

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Data Science Python. Anaconda.  Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas. Data Science Python Anaconda Python 3.x Includes ALL major Python data science packages Sci-kit learn Pandas PlotPy Jupyter Notebooks www.anaconda.com Python - simple commands Python is an interactive

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

Coding Styles for Python

Coding Styles for Python Wintersemester 2007/2008 1 The Zen of Python 2 Style Guide for Python Code 3 Whitespace in Expressions and Statements 4 Naming Conventions 5 References The Zen of Python Python 2.4.2 (#2, Sep 30 2005,

More information

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language

More information

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

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

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

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

Introduction to Python. Didzis Gosko

Introduction to Python. Didzis Gosko Introduction to Python Didzis Gosko Scripting language From Wikipedia: A scripting language or script language is a programming language that supports scripts, programs written for a special run-time environment

More information

Python Tutorial. Release Guido van Rossum and the Python development team. January 23, Python Software Foundation

Python Tutorial. Release Guido van Rossum and the Python development team. January 23, Python Software Foundation Python Tutorial Release 3.6.4 Guido van Rossum and the Python development team January 23, 2018 Python Software Foundation Email: docs@python.org CONTENTS 1 Whetting Your Appetite 3 2 Using the Python

More information

AI Programming CS S-02 Python

AI Programming CS S-02 Python AI Programming CS662-2013S-02 Python David Galles Department of Computer Science University of San Francisco 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use

More information

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

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

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro Cosmology with python: Beginner to Advanced in one week Tiago Batalha de Castro What is Python? (From python.org) Python is an interpreted, object-oriented, high-level programming language with dynamic

More information

Introduction to Python

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

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

An introduction to Python

An introduction to Python 1/119 Source: http://www.python.org PDF: http://www.monard.info An introduction to Python Introduction: why Python 2/119 3/119 Python in a few words Python is a scripting language which can replace most

More information

Course Introduction and Python Basics

Course Introduction and Python Basics Course Introduction and Python Basics Johan Falkenjack 2018-01-15 Course Introduction Python > Data Science 3 hp pass/fail 3 lectures, 3 labs (2 sessions for each lab) Python Basics Programming Paradigms

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

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

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

Some material adapted from Upenn cmpe391 slides and other sources

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

Python Basics. Nakul Gopalan With help from Cam Allen-Lloyd

Python Basics. Nakul Gopalan With help from Cam Allen-Lloyd Python Basics Nakul Gopalan ngopalan@cs.brown.edu With help from Cam Allen-Lloyd 1 Introduction to the idea Readable, easy to learn programming language. Created by Guido van Rossum Named after the BBC

More information

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. December 19, PythonLabs

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. December 19, PythonLabs Python Tutorial Release 2.3.3 Guido van Rossum Fred L. Drake, Jr., editor December 19, 2003 PythonLabs Email: docs@python.org Copyright c 2001, 2002, 2003 Python Software Foundation. All rights reserved.

More information

LECTURE 3 Python Basics Part 2

LECTURE 3 Python Basics Part 2 LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

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

Python Tutorial. Release 2.1. Guido van Rossum Fred L. Drake, Jr., editor. April 15, PythonLabs

Python Tutorial. Release 2.1. Guido van Rossum Fred L. Drake, Jr., editor. April 15, PythonLabs Python Tutorial Release 2.1 Guido van Rossum Fred L. Drake, Jr., editor April 15, 2001 PythonLabs E-mail: python-docs@python.org Copyright c 2001 Python Software Foundation. All rights reserved. Copyright

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

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

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. April 10, PythonLabs

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. April 10, PythonLabs Python Tutorial Release 2.2.1 Guido van Rossum Fred L. Drake, Jr., editor April 10, 2002 PythonLabs Email: python-docs@python.org Copyright c 2001 Python Software Foundation. All rights reserved. Copyright

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

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 10: Functional programming, Memoization March 26, 2007 http://www.seas.upenn.edu/~cse39904/ Announcements Should have received email about meeting times Length:

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

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: Its Past, Present, and Future in Meteorology

Python: Its Past, Present, and Future in Meteorology Python: Its Past, Present, and Future in Meteorology 7th Symposium on Advances in Modeling and Analysis Using Python 23 January 2016 Seattle, WA Ryan May (@dopplershift) UCAR/Unidata Outline The Past What

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

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

EE 355 Unit 17. Python. Mark Redekopp

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

An Introduction to Python

An Introduction to Python An Introduction to Python Release 2.2.2 Guido van Rossum Fred L. Drake, Jr., editor PythonLabs Email: python-docs@python.org A catalogue record for this book is available from the British Library. First

More information

Introduction to Python for Scientific Computing

Introduction to Python for Scientific Computing 1 Introduction to Python for Scientific Computing http://tinyurl.com/cq-intro-python-20151022 By: Bart Oldeman, Calcul Québec McGill HPC Bart.Oldeman@calculquebec.ca, Bart.Oldeman@mcgill.ca Partners and

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

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

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

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

Senthil Kumaran S

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

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD PYTHON Varun Jain & Senior Software Engineer Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT CenturyLink Technologies India PVT LTD 1 About Python Python is a general-purpose interpreted, interactive,

More information

Introduction to Python for IBM i

Introduction to Python for IBM i Introduction to Python for IBM i Mike Pavlak IT Strategist mike.pavlak@freschesolutions.com Agenda A little about Python Why use Python How to install/determine if installed IDE Syntax 101 Variables Strings

More information

LECTURE 1. Getting Started with Python

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

Introduction to Python, Cplex and Gurobi

Introduction 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 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

All programs can be represented in terms of sequence, selection and iteration.

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

Fundamentals of Programming (Python) Getting Started with Programming

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

More information

Python Tutorial (DRAFT)

Python Tutorial (DRAFT) Python Tutorial (DRAFT) Guido van Rossum Dept. CST, CWI, Kruislaan 413 1098 SJ Amsterdam, The Netherlands E-mail: gu@cwi.nl 19 February 1991 Abstract Python is a simple, yet powerful programming language

More information

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

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values

More information

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

Scientific Computing: Lecture 1

Scientific Computing: Lecture 1 Scientific Computing: Lecture 1 Introduction to course, syllabus, software Getting started Enthought Canopy, TextWrangler editor, python environment, ipython, unix shell Data structures in Python Integers,

More information

Python Tutorial. Release Guido van Rossum and the Python development team. October 24, Python Software Foundation

Python Tutorial. Release Guido van Rossum and the Python development team. October 24, Python Software Foundation Python Tutorial Release 3.5.2 Guido van Rossum and the Python development team October 24, 2016 Python Software Foundation Email: docs@python.org CONTENTS 1 Whetting Your Appetite 3 2 Using the Python

More information

C++ for Python Programmers

C++ for Python Programmers C++ for Python Programmers Adapted from a document by Rich Enbody & Bill Punch of Michigan State University Purpose of this document This document is a brief introduction to C++ for Python programmers

More information

Accelerating Information Technology Innovation

Accelerating 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 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

Computational Programming with Python

Computational Programming with Python Numerical Analysis, Lund University, 2017 1 Computational Programming with Python Lecture 1: First steps - A bit of everything. Numerical Analysis, Lund University Lecturer: Claus Führer, Alexandros Sopasakis

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CITS 4406 Problem Solving & Programming

CITS 4406 Problem Solving & Programming CITS 4406 Problem Solving & Programming Tim French Lecture 02 The Software Development Process (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives

More information

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Getting 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 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

Python for Non-programmers

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

Introduction to Python. Prof. Steven Ludtke

Introduction to Python. Prof. Steven Ludtke Introduction to Python Prof. Steven Ludtke sludtke@bcm.edu 1 8512 documented lanuages (vs. 2376) Four of the first modern languages (50s): FORTRAN (FORmula ( TRANslator LISP (LISt ( Processor ALGOL COBOL

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

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

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information