Exercise 1. Try the following code segment:

Size: px
Start display at page:

Download "Exercise 1. Try the following code segment:"

Transcription

1 Exercise 1 Try the following code segment: >>> list = [3,4,2,1] >>> for number in list: print 'item %s in list %s' % (number, list) if number > 2: list.remove(number) Pay attention to the print line The "placeholder" %s says that in that position you have to enter a string, which is taken from the variable that follows the second %, outside the first string. You can use more than one placeholder, one for each variable needed. Some common printformats: 1. %d = integer 2. %e = float in scientific notation 3. %11.3e = float with 3 decimals, field of 11 characters 4. %.3f = float in fixed decimal notation, minimum length 3 decimals 5. %s = string 6. %-20s = string with a field of 20 characters, left aligned

2 Exercise 1 >>> list = [3,4,2,1] >>> for number in list: print item %s in list %s' % (number, list) if number > 2: list.remove(number) Now let s analyze better the code: What do you think it should do in the programmer's intentions? After the loop...what list do you obtain, and why? The problem is that in the second iterationof the loop, the for loop uses the index 1, e then skips the second list item, the 4, that now has index 0 The message is simple: never ever change a list (or any mutable object) on which you are iterating! How can you get what you really wanted? With a copy! Write the correct code that removes every item > 2 with a for loop. Write the code that removes all the items > 2 from the original list, but use a while loop and an index that is properly updated on each cycle

3 Exercise 2 Still about the subject of the previous problem, does the following code clear the list? >>> list = ['a','b','c','d'] >>> for item in list: del list[0] Try to understand what happens, printingfor debugthe list and the current item in the loop Write a while loop that using the statement del list[0] is able to correctly delete the list

4 Solutions 1 list=[3,4,2,1] for item in list[:]: if item > 2: list.remove(item) list=[3,4,2,1] maxindex=len(list)-1 index=0 while index <= maxindex: if list[index]>2: list.remove(list[index]) maxindex=maxindex-1 #the list is smaller else: index=index+1 print list #the index is updated #only if the list size #is not changed

5 Solutions 2 list=['a','b','c','d'] i=len(list)-1 #the index starts from 0 while i>=0: del list[0] i=i-1 print list #if an item is removed #the loop index i is #decremented

6 Scope Variable scope = part of the code in which you can use the given variable There are three different scopes, that allow to identify the variables within functions: 1. If a variable is assigned inside a def, it is local to that function. 2. If a variable is assigned outside any def, it is global to the entire code. 3. If a variable is assigned inside a def, that includes a second def, it is nonlocal for the nested function (3.x) def outer(): x = 1 def inner(): nonlocal x x += 1 print(x) return inner global is the keyword for the global scope, in Python 3.x nonlocal is the keyword for the external nearest scope, that is not necessarily the global one. Please AVOID to modify global variables inside a function!

7 LEGB rule Built-in (Python): preassigned names in standard modules: open, range, Syntax Error Global (modul): names assigned to the top-level of a module file, or declared as global in a def within the file Enclosing function locals: names in the local scope of eachfunction that includes the starting function Local(function): names assigned within a function, and not declared global Python looks for the variables in this order: first the local scope, then the scope of the functions that include the starting function, then the global scope and finally the builtin. The first name occurrence WINS, and hides the subsequent ones. Usually the place in which is placed a variable determines its scope.

8 Exercise 3 What do these codes print, and why? >>> x = "prisma" >>> def func(): print x >>> func() >>> x = "prisma" >>> def func(): x='master' print x >>> func() >>> print x >>> x = "prisma" >>> def func(): global x x='master' >>> func() >>> print x prisma Since the variable x is not assigned inside the function, it is considered global (you can use the global variables inside a function) Master prisma The assignment of x inside the function hides the global x, so the x= Master is local to the function and does not modify the global x Master The global statement force the assignment in the function to refer to the variable x in the global scope, that now can be modified.

9 Lambda functions The functions are Python objects to all the effects, and can be used like any other type of data. You can pass a function as an argument to another function, or return a function as a return value from a function, or you can assign it to a variable, or include it in a list >>> def myfunc(x): return x*3 >>> def applier(q,x) return q(x) >>> applier(myfunc,7) 21 You can define a function without giving it an explicit name. It can be useful in examples like the previous one, where you have to pass a "small" function as an argument to another function: >>> applier(lambda z: z*3, 7) 21

10 Lambda functions lambda <args>: <expression> is equivalent to a function with arguments <args> and <expression> as the return value. Note that only functions that have a SINGLE expression can be defined by this notation

11 filter map reduce These are three functions that are useful, when used in conjuction with lambda functions and lists, to build new lists starting from existing ones. filter(function, iterable) builds a list formed from the items of iterable for which the function function returns True(1) map(function, iterable,...) builds a list formed from the values function(item)computed for each item of iterable. reduce(function, iterable) returns a single value computed applying the function on the first two elements of the sequence, then on the pair formed by the first result and the third item, and so on

12 filter This is the "Sieve of Eratostene", that finds the prime numbers from 2 to n included: def eratostene(n): setaccio = range(2, = range(2, n+1) n+1) primi = [] = [] while setaccio: # finché ci sono numeri nel setaccio primi.append(setaccio[0]) setaccio = = filter(lambda x: x: x%primi[-1], setaccio) setaccio) return primi primi It creates a list of all naturalnumbers from 2 to n, then adds the first number of the sieve to the list of prime numbers found, and removes from the sieve all its multiples. Then it continues until all the numbers in the sieve are removed. % is the moduloperator (returns the remainder). Here the filter function builds a new sieve and deletes multiples of the considered prime number (the last one in the list primi) in a single instruction.

13 map reduce We want to calculate the longest string in a sequence: >>> >>>values=('abc','xy','abcdef','xyz') >>> >>>mapped=map(lambda x:len(x),values) >>> >>>max_len=reduce(lambda x,y: x,y: max(x,y),mapped) max(x,y),mapped) The most interesting part of the matter: if the functions are associative and commutative, as in this case, the problem is easily parallelizable. In principle you could send each map operation to a different computing core, and even the reduce may be performed in multiple parallel steps. From Python 2.6 you can use the multiprocessing.pool.map () function: >>> import operator >>> from multiprocessing import Pool >>> strings = ['string 1', 'string xyz', 'foobar'] >>> pool = Pool(processes=2) >>> print reduce(operator.add, pool.map(len, strings)) 24

14 Variable number of arguments In Python you can define functions with a variable number of arguments def somefunc(a, b, *args): # args is a tuple of all supplied positional arguments... for arg in args: <work with arg> A double asterisk indicates a variable length set of named arguments (a dictionary), which must be passed to the function when it is called. def somefunc(a, b, *args, **kwargs): # args is a tuple of all supplied positional arguments # kwargs is a dictionary of all supplied keyword arguments... for arg in args: print arg for key in kwargs.keys(): print key, ' : ', kwargs[key]

15 Example Write a function that compute the average, minimum and maximum of all input arguments. It has as a input a variable number of arguments (must be numbers), and returns as output the tuple (average, min, max). def statistics(*args): avg = 0; n = 0; # avg and n are local variables for number in args: # sum up all numbers (arguments) n += 1 avg += number avg /= float(n) min = args[0]; max = args[0] for term in args: if term < min: min = term if term > max: max = term return avg, min, max >>> average, vmin, vmax = statistics(v1, v2, v3, b) >>> print 'average =', average, 'min =', vmin, 'max=', vmax We are returning local variables??? No, we're returning a reference to an object in memory, which will therefore continue to exist even when the function is finished. By the way, the function can be MUCH simpler: def statistics(*args): return sum(args)/float(len(args)), min(args), max(args)

16 def table_things(**kwargs): for name, value in kwargs.items(): print '%s = %s' % (name, value) >>> table_things(apple = 'fruit', cabbage = 'vegetable') cabbage = vegetable apple = fruit

17 Scripts

18 Script You can turn what is written in IDLE, or directly in the Python interpreter shell, into an executable program On Windows you can use an extension that allows you to get executables that do not require a prior installation of Python on the target computer. On Linux an executable Python program is a script, a textual code.

19 Hello World! Maybe it's a bit late, in the slide 84, to introduce the classic example Hello World but I need it to show you some characteristics of the scripts. Our script, however, is deliberately a bit more complicated than usual. #!/usr/bin/env python import sys,math usage = 'Usage: %s number' % sys.argv[0] try: number=sys.argv[1] except: print usage sys.exit(1) r=float(number) s=math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s)

20 #!/usr/bin/env python import sys,math usage = 'Usage: %s number' % sys.argv[0] try: number=sys.argv[1] except: print usage sys.exit(1) r=float(number) s=math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s) In the first row it should appear the full path to the interpreter of the script, but you can avoid to explicitly write the path leaving to the env program, which should be more standard, to find python in the system PATH. This makes it possible to move the script between multiple systems with python installations homed in different directories As usual to run the script you have to change its permissions

21 #!/usr/bin/env python import sys,math usage = 'Usage: %s number' % sys.argv[0] try: number=sys.argv[1] except: print usage sys.exit(1) number = sys.argv[1] r=float(number) s=math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s) The first item of the list sys.argv[] contains the script name (remember: the starting index is ALWAYS 0), the other items contain the script arguments, passed from the command line. r = float(number) You can not make a calculation directly with the string, so you need to convert it to a floating-point number. Remember that the type of Python variables are dynamically assigned, and the type is strong: you cannot multiply a string and a float number without an explicit casting. s = math.sin(r) At this point the function that calculates the sin(r) is called, and that function is defined inside the math module. Note that the variable s, as well as the other variables used, has not been declared before using it, and it will contain the floating point calculation result.

22 #!/usr/bin/env python import sys,math usage = 'Usage: %s number' % sys.argv[0] try: number=sys.argv[1] except: print usage sys.exit(1) r=float(number) s=math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s) try: <code that might cause a runtime error> except: <error recovering code> The keyword try identifies a block of code to try", and that can be the source of a runtime error. The keyword except identifies a block of code that is executed if the try block raises an error As usual the code must be indented below the keywords.

23 #!/usr/bin/env python import sys,math usage = 'Usage: %s number' % sys.argv[0] try: number=sys.argv[1] except: print usage sys.exit(1) r=float(number) s=math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s) A moduleis simplya text file containing the Python code, and ending with the extension.py How can you use a modulein a script? You can use the keyword import followed by the name of the file without the extension py. The import command includes in the script namespace, from that moment on, all the functions defined within the module. If you want to add your own module's directory to Python use: >>> module_dir=os.path.join(os.environ['home'],'my','modules') >>> sys.path.insert(0,module_dir)

24 Built-in modules and extensions The standard Python distribution alreadyhas manymodules available, and manyothers can be found with internet: The Python Package Index (PyPI) for example is a place where you can find other modules, and you can also publish your custom module. To install the "manager" of the repository, you need to install the package python-pip. When you havefind the right module, you can install it with: root@sl64 ~# pip install <package name>

25 Custom modules To be able to transform your function in a module, you have no choice but to save it in a file with an appropriate name. Let s go back to our example, to the recursive function we wrote that prints the items of nested lists. Save the function in the file nester.py in your home directory. >>> def print_lol(the_list): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item) else : print each_item Now try to import the module, and use the function print_lol(test_list). What happens? >>> import nester >>> test_list=['1','2','3'] >>> print_lol(test_list)

26 Namespaces The problem is that every Python code has an associated namespace. In the IDLE shell, and generally in the main program, the active namespaceis main When you create a new module, a new namespacewith the same modulename is automaticallycreated, and the functions defined in the moduleare availablein that namespace. The function print_lol defined in the nester modulecan be used, after the import command seen above, only making an explicit reference to the right namespace: >>> import nester >>> test_list=['1','2','3'] >>> nester.print_lol(test_list)

27 import 1. import modulename Any function (or class) defined in the module file modulename.py is imported and useable in the script, but you must prepend modulename to the name of the function modulename.myfunction (34) 2. from modulename import * Any function (or class) defined in the module file modulename.py is imported and useable in the script with its name: myfunction(34) 3. from modulename import myfunction Only the myfunction is imported from the modulename, directly in the main namespace: myfunction(34)

28 What is the best method? There isn t a best method. Be warned that the methods 2 and 3 make the main namespace "dirty", with the inclusion of new functions in it. If in the module is defined a function with a name already used by another function defined in the main namespace, this last function is "overwritten"! If you write the module with IDLE, and save and run it with F5, the module functions are imported in the main namespace and you can easily debug them.

29 Documentation Back to our file nester.py, surely you have realized that something is missing: the documentation. In Python, a standard technique to write the documentation of functions and modules is to use a string delimited by three consecutive quotes, double or single: if the stringis not assignedto a variable, everything that is bordered by triple quotes is a comment. All the lines that begin with # are also comments; this can be very useful for example to temporarily disable a line of code

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

OOP and Scripting in Python Advanced Features

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

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

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

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

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion CSC 148 Lecture 3 Dynamic Typing, Scoping, and Namespaces Recursion Announcements Python Ramp Up Session Monday June 1st, 1 5pm. BA3195 This will be a more detailed introduction to the Python language

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

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

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

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

Extending Jython. with SIM, SPARQL and SQL

Extending Jython. with SIM, SPARQL and SQL Extending Jython with SIM, SPARQL and SQL 1 Outline of topics Interesting features of Python and Jython Relational and semantic data models and query languages, triple stores, RDF Extending the Jython

More information

LECTURE 2. Python Basics

LECTURE 2. Python Basics LECTURE 2 Python Basics MODULES ''' Module fib.py ''' from future import print_function def even_fib(n): total = 0 f1, f2 = 1, 2 while f1 < n: if f1 % 2 == 0: total = total + f1 f1, f2 = f2, f1 + f2 return

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

Introduction to Python Part 2

Introduction to Python Part 2 Introduction to Python Part 2 v0.2 Brian Gregor Research Computing Services Information Services & Technology Tutorial Outline Part 2 Functions Tuples and dictionaries Modules numpy and matplotlib modules

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

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19 Control Flow 1 / 19 Outline 1 If Statement 2 While Statement 3 For Statement 4 Nesting 5 Applications 6 Other Conditional and Loop Constructs 2 / 19 If Statement Most computations require different actions

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

Python Programming Exercises 1

Python Programming Exercises 1 Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them

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

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Name: Partner: Python Activity 9: Looping Structures: FOR Loops

Name: Partner: Python Activity 9: Looping Structures: FOR Loops Name: Partner: Python Activity 9: Looping Structures: FOR Loops Learning Objectives Students will be able to: Content: Explain the difference between while loop and a FOR loop Explain the syntax of a FOR

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

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

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

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

More information

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

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

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

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

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

\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

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

Your First Ruby Script

Your First Ruby Script Learn Ruby in 50 pages Your First Ruby Script Step-By-Step Martin Miliauskas @mmiliauskas 1 Your First Ruby Script, Step-By-Step By Martin Miliauskas Published in 2013 by Martin Miliauskas On the web:

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

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

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

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

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

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Python Programming, bridging course 2011

Python Programming, bridging course 2011 Python Programming, bridging course 2011 About the course Few lectures Focus on programming practice Slides on the homepage No course book. Using online resources instead. Online Python resources http://www.python.org/

More information

PYTHON DATA SCIENCE TOOLBOX I. Scope and user-defined functions

PYTHON DATA SCIENCE TOOLBOX I. Scope and user-defined functions PYTHON DATA SCIENCE TOOLBOX I Scope and user-defined functions Crash course on scope in functions Not all objects are accessible everywhere in a script Scope - part of the program where an object or name

More information

CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 5 Jan. 25, 2019 CS1 Lecture 5 Jan. 25, 2019 HW1 due Monday, 9:00am. Notes: Do not write all the code at once before starting to test. Take tiny steps. Write a few lines test... add a line or two test... add another line

More information

https://lambda.mines.edu Why study Python in Principles of Programming Languages? Multi-paradigm Object-oriented Functional Procedural Dynamically typed Relatively simple with little feature multiplicity

More information

Introduction to Python

Introduction to Python Introduction to Python EECS 4415 Big Data Systems Tilemachos Pechlivanoglou tipech@eecs.yorku.ca 2 Background Why Python? "Scripting language" Very easy to learn Interactive front-end for C/C++ code Object-oriented

More information

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

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

More information

Computer Lab 1: Introduction to Python

Computer Lab 1: Introduction to Python Computer Lab 1: Introduction to Python 1 I. Introduction Python is a programming language that is fairly easy to use. We will use Python for a few computer labs, beginning with this 9irst introduction.

More information

Python debugging and beautification

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

More information

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

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

Execution order. main()

Execution order. main() Functions Execution order When you load and run a Python module (file), the statements and definitions in the file are executed in the order in which they occur Executing a def defines a function, it doesn

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

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

Object Model Comparisons

Object Model Comparisons Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until

More information

Idioms and Anti-Idioms in Python

Idioms and Anti-Idioms in Python Idioms and Anti-Idioms in Python Release 2.6.3 Guido van Rossum Fred L. Drake, Jr., editor October 06, 2009 Python Software Foundation Email: docs@python.org Contents 1 Language Constructs You Should Not

More information

Try and Error. Python debugging and beautification

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

More information

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

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

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

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

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

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

The current topic: Python. Announcements. Python. Python

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

More information

Part III Appendices 165

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

More information

Mastering Python Decorators

Mastering Python Decorators Mastering Python Decorators One of the hallmarks of good Python is the judicious use of decorators to optimize, simplify and add new functionality to existing code. Decorators are usually seen as an advanced

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

Introduction to Python Programming

Introduction to Python Programming advances IN SYSTEMS AND SYNTHETIC BIOLOGY 2018 Anna Matuszyńska Oliver Ebenhöh oliver.ebenhoeh@hhu.de Ovidiu Popa ovidiu.popa@hhu.de Our goal Learning outcomes You are familiar with simple mathematical

More information

Splitting text. Split string into words: Can split wrt other characters: Very useful when interpreting files

Splitting text. Split string into words: Can split wrt other characters: Very useful when interpreting files Splitting text Split string into words: >>> files = case1.ps case2.ps case3.ps >>> files.split() [ case1.ps, case2.ps, case3.ps ] Can split wrt other characters: >>> files = case1.ps, case2.ps, case3.ps

More information

7. MODULES. Rocky K. C. Chang October 17, (Based on Dierbach)

7. MODULES. Rocky K. C. Chang October 17, (Based on Dierbach) 7. MODULES Rocky K. C. Chang October 17, 2016 (Based on Dierbach) Objectives Explain the specification of modules. Become familiar with the use of docstrings in Python. Explain the use of modules and namespaces

More information

CSC Software I: Utilities and Internals. Programming in Python

CSC Software I: Utilities and Internals. Programming in Python CSC 271 - Software I: Utilities and Internals Lecture #8 An Introduction to Python Programming in Python Python is a general purpose interpreted language. There are two main versions of Python; Python

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1 What to add next time you are updating these slides Update slides to have more animation in the bullet lists Verify that each slide has stand alone speaker notes Page 1 Python 3 Running The Python Interpreter

More information

Lecture 16: Static Semantics Overview 1

Lecture 16: Static Semantics Overview 1 Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

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

T H E I N T E R A C T I V E S H E L L

T H E I N T E R A C T I V E S H E L L 3 T H E I N T E R A C T I V E S H E L L The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. Ada Lovelace, October 1842 Before

More information

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif Input, Processing and Output Bonita Sharif 1 Review A program is a set of instructions a computer follows to perform a task The CPU is responsible for running and executing programs A set of instructions

More information

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

More information

Welcome to Python 3. Some history

Welcome to Python 3. Some history Python 3 Welcome to Python 3 Some history Python was created in the late 1980s by Guido van Rossum In December 1989 is when it was implemented Python 3 was released in December of 2008 It is not backward

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information

Scientific Python. 1 of 10 23/11/ :00

Scientific Python.   1 of 10 23/11/ :00 Scientific Python Neelofer Banglawala Kevin Stratford nbanglaw@epcc.ed.ac.uk kevin@epcc.ed.ac.uk Original course authors: Andy Turner Arno Proeme 1 of 10 23/11/2015 00:00 www.archer.ac.uk support@archer.ac.uk

More information

Programming with Python

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

More information

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

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS VARIABLES, EXPRESSIONS AND STATEMENTS João Correia Lopes INESC TEC, FEUP 27 September 2018 FPRO/MIEIC/2018-19 27/09/2018 1 / 21 INTRODUCTION GOALS By the end of this class, the

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

Introduction to Python

Introduction to Python Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code

More information

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics CS2304: Advanced Function Topics Functions With An Arbitrary Number of Parameters Let s say you wanted to create a function where you don t know the exact number of parameters. Python gives you a few ways

More information

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CS 1110, LAB 3: MODULES AND TESTING   First Name: Last Name: NetID: CS 1110, LAB 3: MODULES AND TESTING http://www.cs.cornell.edu/courses/cs11102013fa/labs/lab03.pdf First Name: Last Name: NetID: The purpose of this lab is to help you better understand functions, and to

More information

Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters

Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters What is a function? Function declaration and parameter passing Return values Objects as parameters Reading: Writing Functions Dawson, Chapter 6 Abstraction Data scoping Encapsulation Modules Recursion

More information

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala Relational Operators These operators compare the value of two expressions and returns a Boolean value. Beware of comparing across

More information

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation. Table of Contents: 1. Integers and floats 2. for vs. while loops 3. Checking boolean conditions with if/else 4. Docstrings 5. Changing collections while iterating over them 6. Directly Accessing Instance

More information

redis-lua Documentation

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

More information

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

VLC : Language Reference Manual

VLC : Language Reference Manual VLC : Language Reference Manual Table Of Contents 1. Introduction 2. Types and Declarations 2a. Primitives 2b. Non-primitives - Strings - Arrays 3. Lexical conventions 3a. Whitespace 3b. Comments 3c. Identifiers

More information

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions. COMP1730/COMP6730 Programming for Scientists Data: Values, types and expressions. Lecture outline * Data and data types. * Expressions: computing values. * Variables: remembering values. What is data?

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