Programming for Engineers in Python. Recitation 3 Functions

Size: px
Start display at page:

Download "Programming for Engineers in Python. Recitation 3 Functions"

Transcription

1 Programming for Engineers in Python Recitation 3 Functions

2 Plan Short review FOR and Lists Python references Mutable vs. immutable data types List references Functions Scope Call by assignment Global variables Other types of functions Modules 1

3 Two ways to iterate list elements lst = [10, 20, 30, 40, 50] # Direct iteration over list elements for elem in lst: print elemt # Iterate using indices index_lst = range(len(lst)) for i in index_lst: print lst[i] Output:

4 Changing Elements in a list lst = [1, 4, 3, 6, 8] # take 1 for elem in lst: if elem % 2 == 0: elem = 0 print lst [1, 4, 3, 6, 8] TASK: Set even list elements to zero # take 2 index_lst = range(len(lst)) for i in index_lst: if lst[i] % 2 == 0: lst[i] = 0 print lst [1, 0, 3, 0, 0] 3

5 Python references Assigning a variable in Python creates: An object storing the value A name variable holding a reference to the object. In code: a = 5 In memory: a 5 name int object name reference int object 4

6 Python references Assigning a new variable to an existing variable copies the reference In code: a = 5 name int object b = a name name a name b name In memory: 5 int object 5

7 Python references Name variables can be redirected to point new objects In code: a = 5 In memory: name int object 6 b = a name name b = 6 name int object a name b name 5 object 6 object

8 Mutable objects can be modified after creation Can we modify an existing list? >>> a_list = [1,2,3] >>> a_list[2] 3 >>> a_list[2] = 'Inigo Montoya' >>> a_list [1,2,'Inigo Montoya'] Yes, the list was mutated (changed)! 7 Note: When referring to mutable/immutable we refer to modifying the object itself! Name variables can always be modified to point to a different object!

9 Immutable objects cannot be changed after creation Can we change an existing String? >>> name = 'Inigo Montoya' >>> name[0] 'I' >>> name[5] ' ' >>> name[3] = 't' Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> name[3] = 't' TypeError: 'str' object does not support item assignment 8 No, Strings are Immutable!

10 Assignments of List Variables >>> orig_list = [1,2,3] >>> copy_list = orig_list >>> orig_list = [6,7,8,9] >>> copy_list [1,2,3] >>> orig_list [6,7,8,9] So far - no surprises 9

11 Assignments of List Variables >>> orig_list = [6,7,8,9] >>> copy_list = orig_list >>> orig_list[0] = 1000 >>> orig_list [1000,7,8,9] >>> copy_list [1000,7,8,9] Surprise! 10

12 List references In code: a = [1,2,3] name list object In memory: a [1,2,3] name reference list object 11

13 List references In code: a = [1,2,3] In memory: name list object b = a a [1,2,3] b 12

14 List references In code: a = [1,2,3] In memory: name list object b = a b = [4,5,6] a b [1,2,3] [4,5,6] 13

15 List references In code: In memory: a = [1,2,3] name list object b = a b = [4,5,6] a = b a b What happens to this list? [1,2,3] [4,5,6] 14

16 Changes to a mutable object will be reflected in all names referencing it In code: In memory: a = [1,2,3] name list object 15 b = a b = [4,5,6] a = b b[0] = 100 a b What happens to this list? [1,2,3] [100,5,6]

17 Memory A list variable is a reference to the information List assignment orig_list = [6,7,8,9] creates: a list object, [6,7,8,9] a reference from the variable name, orig_list, to this object. Memory orig_list [6,7,8,9] 16 See visual example in:

18 Different reference variables, same information The assignment copy_list = orig_list does not create a new object, just a new name variable, copy_list, which now refers to the same object. Memory orig_list [6,7,8,9] copy_list 17

19 Changing list information Mutating list elements, orig_list[0] = 1000, does not create a new object and does not change existing references. Memory orig_list [1000,7,8,9] copy_list 18

20 Changing list information: example 2 a = [1, 2, 3] a b = a a b a.append(4) a b 19

21 FUNCTIONS Why should we organize our code using functions? Break the problem into smaller sub-tasks Readability and Maintenance Re-usability Solve bugs once (Unit-testing, later on) 20

22 Functions How to write a new function: def name(arg1, arg2,...): ''' documentation''' #Optional documentation statements 21

23 Example: gcd 22 def gcd(a, b): "Return the greatest common divisor of a and b" while a!= 0: a, b = b%a, a # multiple assignment return b >>> gcd(12, 20) 4 >>> help(gcd) Help on function gcd in module main : gcd(a, b) Return the greatest common divisor of a and b (END)

24 return!= print #!!! def function_that_prints(): print "I printed" def function_that_returns(): return "I returned" ################################## f1 = function_that_prints() f2 = function_that_returns() print "Now let's see what the values of f1,f2 are" print f1 print f2 23

25 Example: phone book def search_book(book, name): '''Run through the repository, search for the name (case insensitive). Return [] if not found''' result = [] for contact in book: if contact[0].lower() == name.lower(): result = contact break return result >>> the_book = [['Nir', 1122], ['Ron', 2233], ['Orna', 3344]] >>> r = search_book(the_book, 'ORnA') >>> r ['Orna', 3344] 24

26 Example: phone book, cont def show_record(record): '''Show the obtained data record''' if len(record)!= 2: print 'Bad data' else: print 'Name: ' + record[0] print 'Phone: ' + str(record[1]) >>> the_book = [['Nir', 1122], ['Ron', 2233], ['Orna', 3344]] >>> r = search_book(the_book, 'ORnA') >>> show_record(r) Name: Orna Phone:

27 Functions Scope When python executes a function it creates a new scope for it: Defined parameters are local They are defined in the scope and then disappear Calling statement sees only the results Calling statement (in the main script or in some other function) input Function scope Local variables return Output 26 20

28 Functions Scope example 1 What will be printed? From the blog

29 28 Functions Scope example 1

30 Functions Scope example 1 What happened? 29

31 Functions Scope example 1 Prints the i of the global scope 30 21

32 Functions Scope example 1 The global i is masked by the local i defined in the function 31 21

33 Simulation i = 1 def foo(): i = 5 print "local",i print "global",i foo() i = 1 Local parameters: i = 5 32

34 Simulation i = 1 def foo(): i = 5 print "local",i print "global",i foo() print "global",i What will this do? 33

35 Simulation i = 1 def foo(): i = 5 print "local",i print "global",i foo() print "global",i What will this do? global 1 local 5 global 1 34

36 Simulation i = 1 def foo(): i = 5 print "local",i print "global",i foo() print "global",i What will this do? global 1 local 5 global 1 After the function ended, we are back to global scope, and the original variable is now unmasked. 35

37 Functions Scope example We will now watch 2 functions that implement the power function: 36

38 Immutable arguments We will now watch 2 functions that implement the power function: def power_for_num(n,pow): n = 5 n = n**pow return n power_for_num(n) 37

39 Immutable arguments We will now watch 2 functions that implement the power function: def power_for_num(n,pow): n = 5 n = n**pow return n power_for_num(n) Traceback (most recent call last): File "test.py", line 8, in <module> power1(n) TypeError: power_for_num() takes exactly 2 arguments (1 given) 38

40 Immutable arguments We will now watch 2 functions that implement the power function: def power_for_num(n,pow): n = 5 n = n**pow return n power_for_num(n) When you call a function, you must assign values to the function s arguments Traceback (most recent call last): File "test.py", line 8, in <module> power1(n) TypeError: power_for_num() takes exactly 2 arguments (1 given) 39

41 Immutable arguments def power_for_num(n,pow): n = n**pow return n n = 5 result = power_for_num(n,2) print n print result 40

42 Immutable arguments def power_for_num(n,pow): n = n**pow return n n = 5 result = power_for_num(n,2) print n print result 5 25 The function used the value in the global variable n, but the global variable didn t change. 41

43 Mutable arguments def power_first_element(l,pow): if len(l) == 0: return #nothing to raise l[0] = l[0]**pow return l[0] l = [5,6] print power_first_element(l,2) 25 42

44 Mutable arguments def power_first_element(l,pow): if len(l) == 0: return #nothing to raise l[0] = l[0]**pow return l[0] l = [5,6] print power_first_element(l,2) print l 25 [25,6] 43

45 Mutable arguments def power_first_element(l,pow): if len(l) == 0: return #nothing to raise l[0] = l[0]**pow return l[0] l = [5,6] print power_first_element(l,2) print l? 25 [25,6] 44

46 Pass Arguments By Assignment The caller specifies arguments (values) for the function call. These arguments are assigned to the variables, with which the function works. As we saw: assigning a value val to a variable named x makes x a reference to val. In program: x = 8 y = x In memory: x y 8 45

47 Pass Arguments By Assignment Cont. Similarly, function s parameters are references to the same values of the callers arguments. In program: x = -7 print abs(x) In memory, when abs starts running: Argument of abs x -7 Whether or not the function can change these values depends on whether their type is mutable. 46

48 Functions mutable example 1 def increment(lst): for i in range(len(lst)): lst[i] = lst[i]+1 # no value returned Now let us execute it in the following manner >>> list1 = [0, 1, 2, 3] >>> increment(list1) >>> list1 [1, 2, 3, 4] 48 list1 was mutated inside the body of increment(lst)! Such a change occurs only for mutable objects.

49 Functions mutable example 2 Consider the following function: def nullify(lst): lst = [] # no value returned Now let us execute it in the following manner >>> list1 = [0, 1, 2, 3] >>> nullify(list1) >>> list1 [0, 1, 2, 3] list1 has NOT changed! Why? 49

50 Global Variables In Python, a variable is local unless declared otherwise. def f(): print s s = 'bbb' print s >>> s = 'aaa' >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f UnboundLocalError: local variable 's' referenced before assignment 50 Check here for more information

51 Global Variables In Python, a variable is local unless declared otherwise. (Is that so?) Mandatory def f(): global s print s s = 'bbb' print s >>> s = 'aaa' >>> f() aaa bbb >>> print s bbb Optional def f(): global s print s >>> s = 'aaa' >>> f() aaa 51 Check here for more information

52 Global Variables def foo(c, d): global a a = 42 c,d = d,c b = 11 print a,b,c,d >>> a,b,c,d = 1,2,3,4 >>> foo('cccc', 7) cccc >>> print a,b,c,d a = 142 b = 2 c = 3 d = 4 c = cccc 7 d = 7 cccc b = 11 52

53 Functions - Information Flow The ways to pass information from a function back to its caller: Return a value(s) Change a mutable argument Modify a global variable 53

54 Other functions Methods: members of specific types: Call by: variable_name.function_name(arguments) Examples: str.upper(my_string) list.append(my_list, 7) Write variable_name. Then type tab to get the list of variable members (press tab to choose one) Built-in functions (colored in IDLE) abs len my_string.upper() my_list.append(7) 54

55 Exercise merge lists Input: 2 ordered lists Output: merged ordered list How to begin? At each point we decide what item to insert next based on the comparison between the lists :

56 Exercise merge ordered lists Input: 2 ordered lists Output: merged ordered list If we reached the end of one of the lists, we we ll append the end of the list to the merged list Out of bound

57 Question 1 def merge(l_1, l_2): merged = [0] * (len(l_1) + len(l_2)) li_1,li_2,merged_i = 0,0,0 #the green arrows while li_1 < len(l_1) and li_2 < len(l_2): if l_1[li_1] <= l_2[li_2]: merged[merged_i] = l_1[li_1] li_1 += 1 merged_i += 1 else: merged[merged_i] = l_2[li_2] l_i2 += 1 merged_i += 1 57

58 Question 1 cont d #copy remaining merged[merged_i:] = l_1[li_1:] merged_i += len(l_1) li_1 merged[merged_i:] = l_2[li_2:] return merged 58

59 Python Code Hierarchy Statement function Module Package 59

60 60 Modules: Functions and Constants All standard modules and their contents (functions, constants) can be found at >>> import math # mathematical functions >>> dir(math) [' doc ', ' name ', ' package ', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] >>> math.pi # a constant >>> math.sqrt(16) # a function 4.0 >>> math.log(8, 2) 3.0

61 More Function Examples 61

62 Example: the beauty of functions When one team keeps writing informative functions, another team can use it even without knowing how they work The Robot example: Our robot can move forwards or backwards forward(robot, time) backward(robot, time) It can also wait wait (robot, time) 62

63 Example: the beauty of functions This modularity enables writing complex functions although we don t really know how the robot works. def yoyo(robot, time, yoyo_repeats): count_repeats = 0 while count_repeats < yoyo_repeats: forward(robot,time) wait(time) backward(robot,time) wait(robot,time) count_repeats = count_repeats

64 Question 1 Input: a list of grades Output: maximum grade, without using built-in max. def max_value_in_list(grades): '''Given a list of grades between 0 and 100, return the maximum grade''' max_grade = -1 for grade in grades: if max_grade < grade: max_grade = grade return max_grade 64 >>> x = [78, 88, 95, 92] >>> print max_value_in_list(x) 95

65 Question 2 Input: a list of grades, and a list of student names Output: a list of students with maximal grade def students_with_max_grade(grades,names): '''return a list of the students with the maximal grade''' max_grade = max_value_in_list(grades) max_grade_students = [] for i in range(len(names)): if max_grade == grades[i]: max_grade_students.append(names[i]) return max_grade_students >>> grades = [99, 80, 92, 99, 97] >>> names = ["Tom", "Ron", "Benny", "Adi", "Livnat"] >>> print students_with_max_grade(grades, names) ['Tom', 'Adi'] 65

66 Question 3 Input: a list of grades Goal: give non-failed grades a factor of y (>0) (No return!) def give_factor(grades,y): for i in range(len(grades)): if grades[i] >= 60: grades[i] += y if grades[i] > 100: grades[i] = 100 >>> print grades [99, 80, 92, 99, 97] >>> give_factor(grades, 5) >>> print grades [100, 85, 97, 100, 100] We can also use: min(grade[i]+y,100) 66

Programming for Engineers in Python. Recitation 3

Programming for Engineers in Python. Recitation 3 Programming for Engineers in Python Recitation 3 Plan Modules / Packages Tuples Mutable / Imutable Dictionaries Functions: Scope Call by Ref / Call by Val Frequency Counter Python Code Hierarchy Statement

More information

Programming for Engineers in Python. Recitation 2

Programming for Engineers in Python. Recitation 2 Programming for Engineers in Python Recitation 2 Plan Range For loop While loop Lists Modules Operations Arithmetic Operations: + plus - minus * multiply / divide (int / float) % modulo (remainder) **

More information

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 7: Reading Files, Importing, Bigram Function Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Importing Reading text files range() Bigram function More sorting with sorted() sorted()

More information

Chap 6 Function Define a function, which can reuse a piece of code, just with a few different values.

Chap 6 Function Define a function, which can reuse a piece of code, just with a few different values. Chap 6 Function Define a function, which can reuse a piece of code, just with a few different values. def tax(bill): """Adds 8% tax to a restaurant bill.""" bill *= 1.08 print "With tax: %f" % bill return

More information

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

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in. Basics of Python by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 13 February 2014 11:59 AM Topics to be Covered (Not in any specific order.) Basic I/O in

More information

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial High Level Scripting Part I Gino Tosti University & INFN Perugia What is a script? Scripting Languages It is a small program able to automate a repetitive and boring job; It is a list of commands that

More information

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

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October :50 PM Basics of Python by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October 2014 03:50 PM Topics to be Covered (Not in any specific order.) Basic I/O in Python

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ Operator Precedence expressions are evaluated left-to-right

More information

Python. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016

Python. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016 Exercises Center of Atmospheric Sciences, UNAM August 24, 2016 NAND Make function that computes the NAND. It should receive two booleans and return one more boolean. logical operators A and B, A or B,

More information

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp. DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! CALLING FUNCTIONS 2 Calling Functions so far we have seen three different

More information

Standard Library. Built-in Functions

Standard Library. Built-in Functions 2 The Standard Library Lab Objective: Python is designed to make it easy to implement complex tasks with little code. To that end, every Python distribution includes several built-in functions for accomplishing

More information

Extended Introduction to Computer Science CS1001.py. Lecture 4: Functions & Side Effects ; Integer Representations: Unary, Binary, and Other Bases

Extended Introduction to Computer Science CS1001.py. Lecture 4: Functions & Side Effects ; Integer Representations: Unary, Binary, and Other Bases Extended Introduction to Computer Science CS1001.py Lecture 4: Functions & Side Effects ; Integer Representations: Unary, Binary, and Other Bases Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants:

More information

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING SECOND EDITION SECOND EDITION Covers Python 3 SAMPLE CHAPTER First edition by Daryl K. Harms Kenneth M. McDonald Naomi R. Ceder MANNING The Quick Python Book Second Edition by Naomi R. Ceder Chapter 4

More information

Module 01: Introduction to Programming in Python

Module 01: Introduction to Programming in Python Module 01: Introduction to Programming in Python Topics: Course Introduction Introduction to Python basics Readings: ThinkP 1,2,3 1 Finding course information https://www.student.cs.uwaterloo.ca/~cs116/

More information

SAMPLE CHAPTER. Naomi Ceder MANNING. Foreword by Nicholas Tollervey

SAMPLE CHAPTER. Naomi Ceder MANNING. Foreword by Nicholas Tollervey SAMPLE CHAPTER Naomi Ceder Foreword by Nicholas Tollervey MANNING The Quick Python Book Third Edition by Naomi Ceder Sample Chapter 4 Copyright 2018 Manning Publications brief contents PART 1 STARTING

More information

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return

More information

Computing and Statistical Data Analysis Lecture 3

Computing and Statistical Data Analysis Lecture 3 Computing and Statistical Data Analysis Lecture 3 Type casting: static_cast, etc. Basic mathematical functions More i/o: formatting tricks Scope, namspaces Functions 1 Type casting Often we need to interpret

More information

Lecture 6: A step back

Lecture 6: A step back Lecture 6: A step back Last time We introduced a scripting language known as Python -- We started with the barest of motivation in terms of historical context and then jumped right in, focusing mainly

More information

CIS192 Python Programming

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

More information

Data Parallel Execution Model

Data Parallel Execution Model CS/EE 217 GPU Architecture and Parallel Programming Lecture 3: Kernel-Based Data Parallel Execution Model David Kirk/NVIDIA and Wen-mei Hwu, 2007-2013 Objective To understand the organization and scheduling

More information

Download Python from Any version will do for this class

Download Python from  Any version will do for this class Let s Start Python Let s Start! Download Python from www.python.org Any version will do for this class By and large they are all mutually compatible Recommended version: 2.1.1 or 2.2 Oldest version still

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

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Robert Rand University of Pennsylvania February 03, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 03, 2016 1 / 23 Outline 1 Function Arguments

More information

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

1 class Lecture5 { 2 3 Methods / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize

More information

Introduction to MATLAB

Introduction to MATLAB Outlines January 30, 2008 Outlines Part I: Part II: Writing MATLAB Functions Starting MATLAB Exiting MATLAB Getting Help Command Window Workspace Command History Current Directory Selector Real Values

More information

A. Matrix-wise and element-wise operations

A. Matrix-wise and element-wise operations USC GSBME MATLAB CLASS Reviewing previous session Second session A. Matrix-wise and element-wise operations A.1. Matrix-wise operations So far we learned how to define variables and how to extract data

More information

CUDA Toolkit 5.0 Performance Report. January 2013

CUDA Toolkit 5.0 Performance Report. January 2013 CUDA Toolkit 5.0 Performance Report January 2013 CUDA Math Libraries High performance math routines for your applications: cufft Fast Fourier Transforms Library cublas Complete BLAS Library cusparse Sparse

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

Object-Based Programming. Programming with Objects

Object-Based Programming. Programming with Objects ITEC1620 Object-Based Programming g Lecture 8 Programming with Objects Review Sequence, Branching, Looping Primitive datatypes Mathematical operations Four-function calculator Scientific calculator Don

More information

CS116 - Module 5 - Accumulative Recursion

CS116 - Module 5 - Accumulative Recursion CS116 - Module 5 - Accumulative Recursion Cameron Morland Winter 2018 1 Cameron Morland CS116 - Module 5 - Accumulative Recursion Types of Recursion Structural Recursion Generative Recursion Accumulative

More information

Statistical Data Analysis: Python Tutorial

Statistical Data Analysis: Python Tutorial 1 October 4, 2017 Statistical Data Analysis: Python Tutorial Dr A. J. Bevan, Contents 1 Getting started 1 2 Basic calculations 2 3 More advanced calculations 4 4 Data sets 5 4.1 CSV file input.............................................

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Functions and Functional Programming Harry Smith University of Pennsylvania January 25, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 3 January 25, 2018 1 / 39

More information

The Red Hat newlib C Math Library

The Red Hat newlib C Math Library The Red Hat newlib C Math Library libm 1.17.0 December 2008 Steve Chamberlain Roland Pesch Red Hat Support Jeff Johnston Red Hat Support sac@cygnus.com pesch@cygnus.com jjohnstn@redhat.com Copyright c

More information

The Cygnus C Math Library

The Cygnus C Math Library The Cygnus C Math Library libm 1.4 December 1995 Steve Chamberlain Roland Pesch Cygnus Support Cygnus Support sac@cygnus.com pesch@cygnus.com Copyright c 1992, 1993 Cygnus Support libm includes software

More information

The Red Hat newlib C Math Library

The Red Hat newlib C Math Library The Red Hat newlib C Math Library libm 1.11.0 July 2002 Steve Chamberlain Roland Pesch Red Hat Support Jeff Johnston Red Hat Support sac@cygnus.com pesch@cygnus.com jjohnstn@redhat.com Copyright c 1992,

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

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

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

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

Essentials for Scientific Computing: Introduction to Python Day 11 & 12 Essentials for Scientific Computing: Introduction to Python Day 11 & 12 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Conditionals 1.1 if Construct In python blocks of code are created by indentation. That

More information

tag 220 tan[f l] struct { int i; double d; } sa, sb; struct { int i; double d; } s1, s2;

tag 220 tan[f l] struct { int i; double d; } sa, sb; struct { int i; double d; } s1, s2; tag 220 T tag The identifier that may optionally follow the keyword struct, union, or enum in a structure, union, or enumerated type definition, respectively. The tag is used later to refer to that particular

More information

Introduction to MATLAB

Introduction to MATLAB Outlines September 9, 2004 Outlines Part I: Review of Previous Lecture Part II: Part III: Writing MATLAB Functions Review of Previous Lecture Outlines Part I: Review of Previous Lecture Part II: Part III:

More information

Matlab Workshop I. Niloufer Mackey and Lixin Shen

Matlab Workshop I. Niloufer Mackey and Lixin Shen Matlab Workshop I Niloufer Mackey and Lixin Shen Western Michigan University/ Syracuse University Email: nil.mackey@wmich.edu, lshen03@syr.edu@wmich.edu p.1/13 What is Matlab? Matlab is a commercial Matrix

More information

Script started on Thu 25 Aug :00:40 PM CDT

Script started on Thu 25 Aug :00:40 PM CDT Script started on Thu 25 Aug 2016 02:00:40 PM CDT < M A T L A B (R) > Copyright 1984-2014 The MathWorks, Inc. R2014a (8.3.0.532) 64-bit (glnxa64) February 11, 2014 To get started, type one of these: helpwin,

More information

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

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

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

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

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

Version default Titre : Opérateur FORMULE Date : 07/04/2018 Page : 1/5 Responsable : COURTOIS Mathieu Clé : U Révision : 0b486e897e73

Version default Titre : Opérateur FORMULE Date : 07/04/2018 Page : 1/5 Responsable : COURTOIS Mathieu Clé : U Révision : 0b486e897e73 Titre : Opérateur FORMULE Date : 07/04/2018 Page : 1/5 Operator FORMULA 1 Goal To define a formula in actual value or complex starting from its mathematical expression. The formula will be usable in a

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

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

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

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

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

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

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 2 Basic MATLAB Operation Dr Richard Greenaway 2 Basic MATLAB Operation 2.1 Overview 2.1.1 The Command Line In this Workshop you will learn how

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

Introduction to Programming in Python (2)

Introduction to Programming in Python (2) Introduction to Programming in Python (2) Steve Renals s.renals@ed.ac.uk ICL 29 September 2005 Conditionals Loops Function basics Variables and functions Functional programming Designing functions Python

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

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

Computational Physics

Computational Physics Computational Physics Python Programming Basics Prof. Paul Eugenio Department of Physics Florida State University Jan 17, 2019 http://hadron.physics.fsu.edu/~eugenio/comphy/ Announcements Exercise 0 due

More information

RETURN VALUE The acos() function returns the arc cosine in radians and the value is mathematically defined to be between 0 and PI (inclusive).

RETURN VALUE The acos() function returns the arc cosine in radians and the value is mathematically defined to be between 0 and PI (inclusive). ACOS(3) Linux Programmer s Manual ACOS(3) acos, acosf, acosl arc cosine function double acos(double x); float acosf(float x); long double acosl(long double x); The acos() function calculates the arc cosine

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

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

CUDA Toolkit 4.0 Performance Report. June, 2011

CUDA Toolkit 4.0 Performance Report. June, 2011 CUDA Toolkit 4. Performance Report June, 211 CUDA Math Libraries High performance math routines for your applications: cufft Fast Fourier Transforms Library cublas Complete BLAS Library cusparse Sparse

More information

Short Introduction to Python Machine Learning Course Laboratory

Short Introduction to Python Machine Learning Course Laboratory Pattern Recognition and Applications Lab Short Introduction to Python Machine Learning Course Laboratory Battista Biggio battista.biggio@diee.unica.it Luca Didaci didaci@diee.unica.it Dept. Of Electrical

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

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

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

Problem 1 (a): List Operations

Problem 1 (a): List Operations Problem 1 (a): List Operations Task 1: Create a list, L1 = [1, 2, 3,.. N] Suppose we want the list to have the elements 1, 2, 10 range(n) creates the list from 0 to N-1 But we want the list to start from

More information

Mentor Graphics Predefined Packages

Mentor Graphics Predefined Packages Mentor Graphics Predefined Packages Mentor Graphics has created packages that define various types and subprograms that make it possible to write and simulate a VHDL model within the Mentor Graphics environment.

More information

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

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

More information

Some elements for Matlab programming

Some elements for Matlab programming Some elements for Matlab programming Nathalie Thomas 2018 2019 Matlab, which stands for the abbreviation of MATrix LABoratory, is one of the most popular language for scientic computation. The classical

More information

CSE 591: GPU Programming. Programmer Interface. Klaus Mueller. Computer Science Department Stony Brook University

CSE 591: GPU Programming. Programmer Interface. Klaus Mueller. Computer Science Department Stony Brook University CSE 591: GPU Programming Programmer Interface Klaus Mueller Computer Science Department Stony Brook University Compute Levels Encodes the hardware capability of a GPU card newer cards have higher compute

More information

OpenCL Overview. Tim Mattson Intel Labs. Copyright Khronos Group, Page 1

OpenCL Overview. Tim Mattson Intel Labs. Copyright Khronos Group, Page 1 OpenCL Overview Tim Mattson Intel Labs Copyright Khronos Group, 2009 - Page 1 Programming Heterogeneous Platforms CPUs Multiple cores driving performance increases Emerging Intersection GPUs Increasingly

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Python for Finance. Introduction and Basics of Python. Andras Niedermayer

Python for Finance. Introduction and Basics of Python. Andras Niedermayer Python for Finance Introduction and Basics of Python Andras Niedermayer Outline 1 Introduction 2 Why Python? 3 Python installation and environments 4 First Steps in Python 5 Variables 6 Basic Operations

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

Introduction to GNU-Octave

Introduction to GNU-Octave Introduction to GNU-Octave Dr. K.R. Chowdhary, Professor & Campus Director, JIETCOE JIET College of Engineering Email: kr.chowdhary@jietjodhpur.ac.in Web-Page: http://www.krchowdhary.com July 11, 2016

More information

Blair, Steven Macpherson (2015) Beckhoff and TwinCAT 3 System Development Guide. [Report], Strathprints

Blair, Steven Macpherson (2015) Beckhoff and TwinCAT 3 System Development Guide. [Report], Strathprints Blair, Steven Macpherson (2015) Beckhoff and TwinCAT 3 System Development Guide. [Report], This version is available at https://strathprints.strath.ac.uk/55254/ Strathprints is designed to allow users

More information

Introduction to GPGPUs and to CUDA programming model: CUDA Libraries

Introduction to GPGPUs and to CUDA programming model: CUDA Libraries Introduction to GPGPUs and to CUDA programming model: CUDA Libraries www.cineca.it Marzia Rivi m.rivi@cineca.it NVIDIA CUDA Libraries http://developer.nvidia.com/technologies/libraries CUDA Toolkit includes

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

GRAPH 4.4. Megha K. Raman APRIL 22, 2015

GRAPH 4.4. Megha K. Raman APRIL 22, 2015 GRAPH 4.4 By Megha K. Raman APRIL 22, 2015 1. Preface... 4 2. Introduction:... 4 3. Plotting a function... 5 Sample funtions:... 9 List of Functions:... 10 Constants:... 10 Operators:... 11 Functions:...

More information

Lecture 8 Mathematics

Lecture 8 Mathematics CS 491 CAP Intro to Competitive Algorithmic Programming Lecture 8 Mathematics Uttam Thakore University of Illinois at Urbana-Champaign October 14, 2015 Outline Number theory Combinatorics & probability

More information

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

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

More information

MTH 337 Introduction to Scientific and Mathematical Computing. Fall Instructor: Adam Cunningham University at Buffalo Department of Mathematics

MTH 337 Introduction to Scientific and Mathematical Computing. Fall Instructor: Adam Cunningham University at Buffalo Department of Mathematics MTH 337 Introduction to Scientific and Mathematical Computing Fall 2015 Instructor: Adam Cunningham University at Buffalo Department of Mathematics Contents 1 Getting Started 4 1.1 Course Description.....................................

More information

MEIN 50010: Python Flow Control

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

More information

Variable and Data Type 2

Variable and Data Type 2 The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists

More information

LAB 7 FUNCTION PART 2

LAB 7 FUNCTION PART 2 LAB 7 FUNCTION PART 2 School of Computer and Communication Engineering Universiti Malaysia Perlis 1 OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To

More information

Modules and Programs 1 / 14

Modules and Programs 1 / 14 Modules and Programs 1 / 14 Python Programs Python code organized in modules, packages, and scripts. We ve already used some modules, now we ll learn what they are, how they re orgainized in packages,

More information

PyCUDA. Continued...

PyCUDA. Continued... PyCUDA Continued... gpuarray Vector Types pycuda.gpuarray.vec All CUDA vector types are supported: float3, int3, long4, etc, Available as numpy data types Field names x, y, z, and w as in CUDA Construct

More information

1 Strings (Review) CS151: Problem Solving and Programming

1 Strings (Review) CS151: Problem Solving and Programming 1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote

More information

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans Computer Science 121 Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans 3.1 The Organization of Computer Memory Computers store information as bits : sequences of zeros and

More information

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions. Handout 2 Functions, Lists, For Loops and Tuples [ ] Functions -- parameters/arguments, "calling" functions, return values, etc. Please make sure you understand this example: def square(x): return x *

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

LAB 1 General MATLAB Information 1

LAB 1 General MATLAB Information 1 LAB 1 General MATLAB Information 1 General: To enter a matrix: > type the entries between square brackets, [...] > enter it by rows with elements separated by a space or comma > rows are terminated by

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 2 Procedural Programming Camelia Chira Last time Programming process What is programming? Basic elements of Python Python programs Data types: string, number Variables

More information