python 01 September 16, 2016

Size: px
Start display at page:

Download "python 01 September 16, 2016"

Transcription

1 python 01 September 16, Introduction to Python adapted from Steve Phelps lectures - ( 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: Out[1]: 9 good for scripting we can have a shell (interactive mode) In [2]: x = 2 y = Ciao z = 1.2 In [3]: x + 5 Out[3]: 7 3 Assignments versus equations Python is imperative when we write x = 5 this means something different from an equation x = 5. variables in Python can refer to different things as more statements are interpreted. In [4]: x = 1 print( The value of x is, x) x = 2.5 print( Now the value of x is, x) x = hello there print( Now it is, x) The value of x is 1 Now the value of x is 2.5 Now it is hello there 1

2 4 Calling Functions We can call functions in a conventional way using round brackets In [5]: print(round(3.14)) 3 5 Types Values in Python have an associated type. combining types incorrectly we get an error. In [6]: print(y) Ciao In [7]: y TypeError Traceback (most recent call last) <ipython-input-7-c3d4037f4656> in <module>() ----> 1 y + 5 TypeError: Can t convert int object to str implicitly 6 The type function We can query the type of a value using the type function. In [8]: type(1) Out[8]: int In [9]: type( ciao ) Out[9]: str In [10]: type(2.5) Out[10]: float In [11]: type(true) Out[11]: bool 2

3 7 Null values Sometimes we represent no data or not applicable. Python has the special value None. This corresponds to Null in Java or SQL. In [12]: result = None When we fetch the value None in the interactive interpreter, no result is printed out. In [13]: result We can check whether there is a result or not using the is operator: In [14]: result is None Out[14]: True In [15]: x = 5 x is None Out[15]: False 8 Converting values between types We can convert values between different types. To convert an integer to a floating-point number use the float() function. To convert a floating-point to an integer use the int() function. In [16]: x = 1 print(type(x)) print(x) <class int > 1 In [17]: y = float(x) print(type(y)) print(y) <class float > 1.0 In [18]: print(int(y)) 1 9 Variables are not typed Variables themselves do not have a fixed type. Only the values that they refer to have a type. the type referred to by a variable can change as more statements are interpreted. In [19]: y = ciao print( type referred by y is, type(y)) y = 5.0 print( type referred by y is, type(y)) type referred by y is type referred by y is <class str > <class float > 3

4 10 Polymorphism The meaning of an operator depends on the types we are applying it to. In [20]: 1 / 5 Out[20]: 0.2 In [21]: 1.0 / 5.0 Out[21]: 0.2 In [22]: Out[22]: 2 In [23]: a + b Out[23]: ab In [24]: Out[24]: Conditional Statements and Indentation The syntax for control structures in Python use colons and indentation. Beware that white-space affects the semantics of Python code. In [25]: x = 5 if x > 0: print( x is strictly positive ) print(x) print( finished ) x is strictly positive 5 finished In [26]: x = 0 if x > 0: print( x is strictly positive ) print(x) 0 finished 12 Lists print( finished ) We can use lists to hold an ordered sequence of values. In [27]: l = [ first, second, third ] l 4

5 Out[27]: [ first, second, third ] Lists can contain different types of variable, even in the same list. In [28]: another_list = [ first, second, third, 1, 2, 3] another_list Out[28]: [ first, second, third, 1, 2, 3] 13 Mutable Datastructures Lists are mutable - their contents can change as more statements are interpreted In [29]: l.append( fourth ) l Out[29]: [ first, second, third, fourth ] 14 References Whenever we bind a variable to a value in Python we create a reference. A reference is distinct from the value that it refers to. Variables are names for references. In [30]: X = [1, 2, 3] Y = X X and Y are two references to the same value [1, 2, 3] Because lists are mutable, changing them can have side-effects on other variables. If we append something to X what will happen to Y? In [31]: X.append(4) X Out[31]: [1, 2, 3, 4] In [32]: Y Out[32]: [1, 2, 3, 4] 15 State and identity The state referred to by a variable is different from its identity. To compare state use the == operator. To compare identity use the is operator. When we compare identity we check equality of references. When we compare state we check equality of values. In [33]: X = [1, 2] Y = [1] Y.append(2) 5

6 In [34]: X == Y Out[34]: True In [35]: X is Y Out[35]: False In [36]: X = Y In [37]: X is Y Out[37]: True 16 Iteration for loop iterates over each element of a list In [38]: for i in l: print(i) first second third fourth iterate with index In [39]: for i,element in enumerate([0, a, 5, last_element ]): print("index " + str(i) + " - " + str(element)) index 0-0 index 1 - a index 2-5 index 3 - last element 17 For loops with the range function The function range() counts for us (starting at 0). In [40]: range(4) Out[40]: range(0, 4) In [41]: for i in range(4): print("string: " + str(i)) string: 0 string: 1 string: 2 string: 3 18 List Indexing Lists can be indexed using square brackets to retrieve the element stored in a particular position. In [42]: print(l[0]) first In [43]: print(l[1]) second 6

7 19 List Slicing We can also a specify a range of positions. This is called slicing. The example below indexes from position 0 (inclusive) to 2 (exclusive). In [44]: print(l[0:2]) [ first, second ] If we leave out the starting index it implies the beginning of the list: In [45]: print(l[:2]) [ first, second ] If we leave out the final index it implies the end of the list: In [46]: l[2:] Out[46]: [ third, fourth ] 20 Negative Indexing Negative indices count from the end of the list: In [47]: l[-1] Out[47]: fourth In [48]: l[:-1] Out[48]: [ first, second, third ] By step e.g. 2 with ::2 In [49]: l[0::2] Out[49]: [ first, third ] In [50]: l[-1::-2] Out[50]: [ fourth, second ] 21 Collections Lists are an example of a collection. A collection is a type of value that can contain other values. There are other collection types in Python: tuple set dict 7

8 22 Tuples Tuples are another way to combine different values. The combined values can be of different types. Like lists, they have a well-defined ordering and can be indexed. To create a tuple in Python, use round brackets instead of square brackets In [51]: tuple1 = (50, hello ) tuple1 Out[51]: (50, hello ) In [52]: tuple1[0] Out[52]: 50 In [53]: type(tuple1) Out[53]: tuple 23 Tuples are immutable Unlike lists, tuples are immutable. Once we have created a tuple we cannot add values to it. In [54]: tuple1.append(2) AttributeError Traceback (most recent call last) <ipython-input-54-a29bee310764> in <module>() ----> 1 tuple1.append(2) AttributeError: tuple object has no attribute append 24 Sets Lists can contain duplicate values. A set, in contrast, contains no duplicates. Sets can be created from lists using the set() function. In [56]: X = set([1, 2, 3, 3, 4]) X Out[56]: {1, 2, 3, 4} In [57]: type(x) Out[57]: set Alternatively we can write a set literal using the { and } brackets. In [58]: X = {1, 2, 3, 4} type(x) Out[58]: set 8

9 25 Sets are mutable Sets are mutable like lists: In [59]: X.add(5) X Out[59]: {1, 2, 3, 4, 5} Duplicates are automatically removed In [60]: X.add(5) X Out[60]: {1, 2, 3, 4, 5} 26 Sets are unordered Sets do not have an ordering. Therefore we cannot index or slice them: In [61]: X[0] TypeError Traceback (most recent call last) <ipython-input-61-1d61f6e5db90> in <module>() ----> 1 X[0] TypeError: set object does not support indexing 27 Operations on sets Union: X Y In [ ]: X = {1, 2, 3} Y = {4, 5, 6} X.union(Y) Intersection: X Y : In [ ]: X = {1, 2, 3, 4} Y = {3, 4, 5} X.intersection(Y) Difference X Y : In [ ]: X - Y 9

10 28 Arrays Python also has fixed-length arrays which contain a single type of value i.e. we cannot have different types of value within the same array. Arrays are provided by a separate module called numpy Modules correspond to packages in e.g. Java. We can import the module and then give it a shorter alias. In [ ]: import numpy as np We can now use the functions defined in this package by prefixing them with np. The function array() creates an array given a list. In [ ]: x = np.array([0, 1, 2, 3, 4]) print(x) print(type(x)) 29 Functions over arrays When we use arithmetic operators on arrays, we create a new array with the result of applying the operator to each element. In [ ]: y = x * 2 y The same goes for functions: In [ ]: x = np.array([-1, 2, 3, -4]) y = abs(x) y 30 Populating Arrays To populate an array with a range of values we use the np.arange() function: In [ ]: x = np.arange(0, 10) x We can also use floating point increments. In [ ]: x = np.arange(0, 1, 0.1) x In [ ]: x = np.arange(1, 0, -0.2) x 31 Basic Plotting We will use a module called matplotlib to plot some simple graphs. This module provides functions which are very similar to MATLAB plotting commands. In [ ]: import matplotlib.pyplot as plt %matplotlib inline y = x*2 + 5 plt.plot(x, y) 10

11 32 Plotting a sine curve In [ ]: from numpy import pi, sin x = np.arange(0, 2*pi, 0.01) y = sin(x) plt.plot(x, y) 33 Plotting a histogram We can use the hist() function in matplotlib to plot a histogram In [ ]: # Generate some random data data = np.random.randn(1000) #data ax = plt.hist(data) #ax = plt.hist(data, bins=[-3,-1.5,-0.5,0.5,1.5,3]) # If bins is an int, it defines the number of equal-width bins in the given range (10, by defaul #If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non 34 Computing histograms as matrices The function histogram() in the numpy module will count frequencies into bins and return the result as a 2-dimensional array. In [ ]: np.histogram(data) In [ ]: np.histogram(data, bins=5) 35 Defining new functions In [ ]: def squared(x): return x ** 2 squared(5) 36 Local Variables Variables created inside functions are local to that function. They are not accessable to code outside of that function. In [ ]: def squared(x): result = x ** 2 return result squared(5) In [ ]: print(result) 11

12 37 Functional Programming Functions are first-class citizens in Python. They can be passed around just like any other value. In [ ]: print(squared) In [ ]: y = squared print(y) In [ ]: y(5) 38 Mapping the elements of a collection We can apply a function to each element of a collection using the built-in function map(). This will work with any collection: list, set, tuple or string. This will take as an argument another function, and the list we want to apply it to. It will return the results of applying the function, as a list. In [ ]: map(squared, [1, 2, 3, 4]) # from Python 3 returns an iterator In [ ]: [i for i in map(squared, [1, 2, 3, 4])] 39 List Comprehensions Because this is such a common operation, Python has a special syntax to do the same thing, called a list comprehension. In [ ]: [squared(i) for i in [1, 2, 3, 4]] If we want a set instead of a list we can use a set comprehension In [ ]: {squared(i) for i in [1, 2, 3, 4]} 40 Cartesian product using list comprehensions The Cartesian product of two collections X = A B can be expressed by using multiple for statements in a comprehension. In [ ]: A = { x, y, z } B = {1, 2, 3} {(a,b) for a in A for b in B} 41 Cartesian products with other collections The syntax for Cartesian products can be used with any collection type. In [ ]: first_names = ( Steve, John, Peter ) surnames = ( Smith, Doe ) [(first_name, surname) for first_name in first_names for surname in surnames] 12

13 42 Anonymous Function Literals We can also write anonymous functions. These are function literals, and do not necessarily have a name. They are called lambda expressions (after the λ calculus). In [ ]: list(map(lambda x: x ** 2, [1, 2, 3, 4])) 43 Filtering data We can filter a list by applying a predicate to each element of the list. A predicate is a function which takes a single argument, and returns a boolean value. filter(p, X) is equivalent to {x : p(x) x X} in set-builder notation. In [ ]: list(filter(lambda x: x > 0, [-5, 2, 3, -10, 0, 1])) We can use both filter() and map() on other collections such as strings or sets. In [ ]: list(filter(lambda x: x!=, hello world )) In [ ]: list(map(ord, hello world )) In [ ]: list(filter(lambda x: x > 0, {-5, 2, 3, -10, 0, 1})) 44 Filtering using a list comprehension Again, because this is such a common operation, we can use simpler syntax to say the same thing. We can express a filter using a list-comprehension by using the keyword if: In [ ]: data = [-5, 2, 3, -10, 0, 1] [x for x in data if x > 0] We can also filter and then map in the same expression: In [ ]: from numpy import sqrt [sqrt(x) for x in data if x > 0] 45 The reduce function The reduce() function recursively applies another function to pairs of values over the entire list, resulting in a single return value. In [ ]: from functools import * In [ ]: reduce(lambda x, y: x + y, [0, 1, 2, 3, 4, 5]) 46 Big Data The map() and reduce() functions form the basis of the map-reduce programming model. Map-reduce is the basis of modern highly-distributed large-scale computing frameworks. In [ ]: 13

ENGR (Socolofsky) Week 07 Python scripts

ENGR (Socolofsky) Week 07 Python scripts ENGR 102-213 (Socolofsky) Week 07 Python scripts A couple programming examples for this week are embedded in the lecture notes for Week 7. We repeat these here as brief examples of typical array-like operations

More information

ARTIFICIAL INTELLIGENCE AND PYTHON

ARTIFICIAL INTELLIGENCE AND PYTHON ARTIFICIAL INTELLIGENCE AND PYTHON DAY 1 STANLEY LIANG, LASSONDE SCHOOL OF ENGINEERING, YORK UNIVERSITY WHAT IS PYTHON An interpreted high-level programming language for general-purpose programming. Python

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

Python in Economics and Finance

Python in Economics and Finance Python in Economics and Finance Part 2 John Stachurski, ANU June 2014 Topics Data types OOP Iteration Functions NumPy / SciPy Matplotlib Data Types We have already met several native Python data types»>

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

A. Python Crash Course

A. Python Crash Course A. Python Crash Course Agenda A.1 Installing Python & Co A.2 Basics A.3 Data Types A.4 Conditions A.5 Loops A.6 Functions A.7 I/O A.8 OLS with Python 2 A.1 Installing Python & Co You can download and install

More information

cosmos_python_ Python as calculator May 31, 2018

cosmos_python_ Python as calculator May 31, 2018 cosmos_python_2018 May 31, 2018 1 Python as calculator Note: To convert ipynb to pdf file, use command: ipython nbconvert cosmos_python_2015.ipynb --to latex --post pdf In [3]: 1 + 3 Out[3]: 4 In [4]:

More information

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn Introduction to Machine Learning Useful tools: Python, NumPy, scikit-learn Antonio Sutera and Jean-Michel Begon September 29, 2016 2 / 37 How to install Python? Download and use the Anaconda python distribution

More information

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc. CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

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

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

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

Scientific Programming. Lecture A08 Numpy

Scientific Programming. Lecture A08 Numpy Scientific Programming Lecture A08 Alberto Montresor Università di Trento 2018/10/25 Acknowledgments: Stefano Teso, Documentation http://disi.unitn.it/~teso/courses/sciprog/python_appendices.html https://docs.scipy.org/doc/numpy-1.13.0/reference/

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

MLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University

MLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University MLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University Getting Started There are two different versions of Python being supported at the moment, 2.7 and 3.6. For compatibility

More information

Interactive Mode Python Pylab

Interactive Mode Python Pylab Short Python Intro Gerald Schuller, Nov. 2016 Python can be very similar to Matlab, very easy to learn if you already know Matlab, it is Open Source (unlike Matlab), it is easy to install, and unlike Matlab

More information

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han Lesson 4: Type Conversion, Mutability, Sequence Indexing Fundamentals of Text Processing for Linguists Na-Rae Han Objectives Python data types Mutable vs. immutable object types How variable assignment

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( )

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( ) Tutorial 2 PHY409 Anadi Canepa canepa@triumf.ca Office, TRIUMF MOB 92 B (1-604- 222-7330) Alan Manning mannin2@phas.ubc.ca Mohammad Samani samani@physics.ubc.ca During the 1 st tutorial We learnt What

More information

Introduction to Python: The Multi-Purpose Programming Language. Robert M. Porsch June 14, 2017

Introduction to Python: The Multi-Purpose Programming Language. Robert M. Porsch June 14, 2017 Introduction to Python: The Multi-Purpose Programming Language Robert M. Porsch June 14, 2017 What is Python Python is Python is a widely used high-level programming language for general-purpose programming

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

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

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Python Lists: Example 1: >>> items=[apple, orange,100,25.5] >>> items[0] 'apple' >>> 3*items[:2] Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.

More 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

Exceptions. raise type(message) raise Exception(message)

Exceptions. raise type(message) raise Exception(message) Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

NumPy quick reference

NumPy quick reference John W. Shipman 2016-05-30 12:28 Abstract A guide to the more common functions of NumPy, a numerical computation module for the Python programming language. This publication is available in Web form1 and

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

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

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Python for Scientists

Python for Scientists High level programming language with an emphasis on easy to read and easy to write code Includes an extensive standard library We use version 3 History: Exists since 1991 Python 3: December 2008 General

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

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 Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

MS&E351 Dynamic Programming and Stochastic Control Autumn 2016 Professor Benjamin Van Roy Python Tutorial

MS&E351 Dynamic Programming and Stochastic Control Autumn 2016 Professor Benjamin Van Roy Python Tutorial MS&E351 Dynamic Programming and Stochastic Control Autumn 2016 Professor Benjamin Van Roy 20160927 Python Tutorial In this course, we will use the python programming language and tools that support dynamic

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

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

Week Two. Arrays, packages, and writing programs

Week Two. Arrays, packages, and writing programs Week Two Arrays, packages, and writing programs Review UNIX is the OS/environment in which we work We store files in directories, and we can use commands in the terminal to navigate around, make and delete

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More 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

Lecture 0. Introduction to Python. Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018

Lecture 0. Introduction to Python. Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018 Lecture 0 Introduction to Python Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018 Universidad de Costa Rica SP6534 - Economía Computacional Table of contents 1. Getting Python and

More information

Lecture 15: High Dimensional Data Analysis, Numpy Overview

Lecture 15: High Dimensional Data Analysis, Numpy Overview Lecture 15: High Dimensional Data Analysis, Numpy Overview Chris Tralie, Duke University 3/3/2016 Announcements Mini Assignment 3 Out Tomorrow, due next Friday 3/11 11:55PM Rank Top 3 Final Project Choices

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2 COMP1730/COMP6730 Programming for Scientists Sequence types, part 2 Lecture outline * Lists * Mutable objects & references Sequence data types (recap) * A sequence contains n 0 values (its length), each

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015 Numerical Methods Claus Führer Alexandros Sopasakis Centre for Mathematical Sciences Lund University Spring 2015 Preface These notes serve as a skeleton for the course. They document together with the

More information

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell CSC 108H1 F 2017 Midterm Test Duration 50 minutes Aids allowed: none Last Name: UTORid: First Name: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

More information

Lessons on Python Functions

Lessons on Python Functions Lessons on Python Functions Walter Didimo [ 90 minutes ] Functions When you write a program, you may need to recall a certain block of instructions several times throughout your code A function is a block

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

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

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

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

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

Python Review IPRE

Python Review IPRE Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

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

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing MS6021 Scientific Computing TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing Preliminary Notes on Python (v MatLab + other languages) When you enter Spyder (available on installing Anaconda),

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

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

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

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Python a modern scripting PL. Python

Python a modern scripting PL. Python Python a modern scripting PL Basic statements Basic data types & their operations Strings, lists, tuples, dictionaries, files Functions Strings Dictionaries Many examples originally from O Reilly Learning

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

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

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More 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

STA141C: Big Data & High Performance Statistical Computing

STA141C: Big Data & High Performance Statistical Computing STA141C: Big Data & High Performance Statistical Computing Lecture 1: Python programming (1) Cho-Jui Hsieh UC Davis April 4, 2017 Python Python is a scripting language: Non-scripting language (C++. java):

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

CDO-1 Certificate Program: Foundations for Chief Data Officers. Data Wrangling Lab. David /WEI DAI. Sept 26-29, 2016 (c)

CDO-1 Certificate Program: Foundations for Chief Data Officers. Data Wrangling Lab. David /WEI DAI. Sept 26-29, 2016 (c) CDO-1 Certificate Program: Foundations for Chief Data Officers Data Wrangling Lab David /WEI DAI Sept 26-29, 2016 (c) 2016 icdo@ualr 1 Agenda Basic Python Program MongoDB Lab Clean Data Lab Sept 26-29,

More information

CS 115 Lecture 8. Selection: the if statement. Neil Moore

CS 115 Lecture 8. Selection: the if statement. Neil Moore CS 115 Lecture 8 Selection: the if statement Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 24 September 2015 Selection Sometime we want to execute

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G. Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

Python Crash Course Numpy, Scipy, Matplotlib

Python Crash Course Numpy, Scipy, Matplotlib Python Crash Course Numpy, Scipy, Matplotlib That is what learning is. You suddenly understand something you ve understood all your life, but in a new way. Doris Lessing Steffen Brinkmann Max-Planck-Institut

More information

NumPy. Daniël de Kok. May 4, 2017

NumPy. Daniël de Kok. May 4, 2017 NumPy Daniël de Kok May 4, 2017 Introduction Today Today s lecture is about the NumPy linear algebra library for Python. Today you will learn: How to create NumPy arrays, which store vectors, matrices,

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know? Python Compact February 7, 2018 1 Python Compact 1.0.1 Claus Führer, Lund University Short introduction to Python for participants of the course ** Numerical Methods - Review and Training ** Volvo Cars,

More information

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014)

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014) Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014) modified from Berkeley Python Bootcamp 2013 https://github.com/profjsb/python-bootcamp and Python for Signal Processing http://link.springer.com/book/10.1007%2f978-3-319-01342-8

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation

More information

The Python interpreter

The Python interpreter The Python interpreter Daniel Winklehner, Remi Lehe US Particle Accelerator School (USPAS) Summer Session Self-Consistent Simulations of Beam and Plasma Systems S. M. Lund, J.-L. Vay, D. Bruhwiler, R.

More information

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala Functions, Scope & Arguments HORT 59000 Lecture 12 Instructor: Kranthi Varala Functions Functions are logical groupings of statements to achieve a task. For example, a function to calculate the average

More information

Introduction to Python and NumPy I

Introduction to Python and NumPy I Introduction to Python and NumPy I This tutorial is continued in part two: Introduction to Python and NumPy II Table of contents Overview Launching Canopy Getting started in Python Getting help Python

More information

Programming for Engineers in Python

Programming for Engineers in Python Programming for Engineers in Python Autumn 2016-17 Lecture 11: NumPy & SciPy Introduction, Plotting and Data Analysis 1 Today s Plan Introduction to NumPy & SciPy Plotting Data Analysis 2 NumPy and SciPy

More information

Ch.2: Loops and lists

Ch.2: Loops and lists Ch.2: Loops and lists Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Aug 29, 2018 Plan for 28 August Short quiz on topics from last

More information

Introduction to Python

Introduction to Python Introduction to Python Version 1.1.5 (12/29/2008) [CG] Page 1 of 243 Introduction...6 About Python...7 The Python Interpreter...9 Exercises...11 Python Compilation...12 Python Scripts in Linux/Unix & Windows...14

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

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

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

a name refers to an object side effect of assigning composite objects

a name refers to an object side effect of assigning composite objects Outline 1 Formal Languages syntax and semantics Backus-Naur Form 2 Strings, Lists, and Tuples composite data types building data structures the % operator 3 Shared References a name refers to an object

More information

Python Programming Exercises 3

Python Programming Exercises 3 Python Programming Exercises 3 Notes: These exercises assume that you are comfortable with the contents of the two previous sets of exercises including variables, types, arithmetic expressions, logical

More information

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

Phys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3 Phys 60441 Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3 Tim O Brien Room 3.214 Alan Turing Building tim.obrien@manchester.ac.uk Tuples Lists and strings are examples of sequences.

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

Numerical Calculations

Numerical Calculations Fundamentals of Programming (Python) Numerical Calculations Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Scipy Lecture Notes at http://www.scipy-lectures.org/ Outline

More information