Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programmazione ad alto livello con Python

Similar presentations


Presentation on theme: "Programmazione ad alto livello con Python"— Presentation transcript:

1 Programmazione ad alto livello con Python
Lezione 2: Costrutti iterativi e costrutti per il controllo di flusso. Dr. Gabriele Mencagli Dipartimento di Informatica Università di Pisa 20/11/2018

2 Informazioni Dr. Gabriele Mencagli
Dipartimento di Informatica, Università di Pisa Stanza 287. Ricevimento su appuntamento (mandare una ) web: Organizzazione: corso introduttivo. 16 ore di didattica frontale, 14 di esercizi individuali in laboratorio Durata: 2 mesi Modalità di esame: progetto finale di complessità variabile Importante gli homework!!! (tipicamente uno per settimana) 20/11/2018

3 Topics In this lecture we study:
FOR loops: used when we know the number of times that a loop will be executed WHILE loops: used for conditional loops Express conditions in Python: the IF-ELSE command Built-in functions 20/11/2018

4 Doing things many times...
Often you will be working on problems in which you have to perform a task several times. Say you want to print the first 10 numbers, every number in a new line. Naively, you would write: print 1 print 2 print 10 Not very exiting! For tasks like this, computer languages provide commands, which allow to simplify codes. The concept which is going to be introduced is called loops. 20/11/2018

5 FOR loops The FOR command is used to express an iterative command in which the number of iterations is know a-priori by the programmer e.g. doing a statement for all the elements of a list. The syntax is: In the FOR statement we have: i is the element of the current iteration (e.g. the i-th element of the list) and NAME is the set of elements (e.g. the list NAME). It could be dangerous to modify the set NAME during the iteratations of the FOR loop. A good idea is to iterate on a copy of the set NAME for i in NAME: Statement 1 Statement 2 ... 20/11/2018

6 FOR loops (2) Lets say I want to print the first ten numbers, like above. With the help of a for-loop this would look like this (note the identation!): 20/11/2018

7 FOR loops (3) We have seen the range function already in Lecture 1. It generates lists containing arithmetic progressions: 20/11/2018

8 FOR loops (4) The result of that script is: 20/11/2018

9 FOR loops (5) You don’t need to use the range command, you could do the following too: 20/11/2018

10 Example A simple script for which the for-loop is useful: 20/11/2018

11 Example (2) Output of the previous code: 20/11/2018

12 Series with FOR loops A well known result in mathematics is the series: Lets implement the sum in equation (1) in a Python program and print the result of the sum each time we add a term to it. Since we cannot add an infinite amount of terms, we ask the user to input how many terms she/he wants to sum up. To implement this simple program we need to use an iterarive construct (the for loop in this case, since we know exactly the total number of iterations). 20/11/2018

13 Series with FOR loops (2)
The program calculating the series for a given value N: <----Important!!!! 20/11/2018

14 Series with FOR loops (3)
The output: 20/11/2018

15 Nesting of FOR loops For loops can be nested. In this example, the inner loop will be run each time the outer loop is repeated. An example illustrates this: Please remember the identation to correctly identify the region of code belonging to the innermost (outermost) loop. 20/11/2018

16 Nesting of FOR loops (2) This is the output of the previous script:
20/11/2018

17 Nesting of FOR loops (3) Another example in which I fill the elements of a matrix: 20/11/2018

18 Topics In this lecture we study:
FOR loops: used when we know the number of times that a loop will be executed WHILE loops: used for conditional loops Express conditions in Python: the IF-ELSE command Built-in functions 20/11/2018

19 WHILE loops The syntax of the While command is the following (remember the identation): while(condition): Statement 1 Statement 2 ... The statements 1, 2, ...., etc are executed as long as condition is true. The statements will not be executed if condition becomes false. Note that as in the case with for-loops, the statements to be executed are indented. We will hear about conditional statements soon in this lecture. For now, think about what it is in the bracket as something like: i<5, name==”Bob” etc. 20/11/2018

20 A simple example The user is asked to put in a number less than 10. As long as the number is less or equal than 10, the programme displays the number squared and asks for another number. If, however, the number is bigger than 10, the program quits. 20/11/2018

21 A simple example (2) This is the output of the previous example:
20/11/2018

22 WHILE loops (pitfalls)
Note that in: while(condition): The while loop will run until condition becomes false (or 0, which is the same thing). Thus, if you write: the while loop will never end, since variable never becomes 0 (false), as it is not modified within the while loop body. variable = 1 x = 1 while (variable): x = x+1 print x**2 20/11/2018

23 Series with WHILE loops
Let us write a program computing the series (previously written with a For loop): 20/11/2018

24 WHILE loops (conditions)
The condition in a while-loop doesn’t need to compare numbers. 20/11/2018

25 Nesting of While loops Another example in which I fill the ements of a matrix: 20/11/2018

26 More about loops As it is clear, the for–loop and the while–loop can control the flow of a program. Certain commands will be executed only a limited number of times, sometimes not at all. When to use which loops? These are general rules valid for any programming language: If you know how many times you need to loop, use the FOR loop. WHILE loops are used until an event occurs (in the last example until the user does not type ”y”). In general we don’t know the total number of iterations that will be executed. But in general, FOR and WHILE loops are equivalent (they have the same “expressive power”) as the series–example shows. 20/11/2018

27 Topics In this lecture we study:
FOR loops: used when we know the number of times that a loop will execute WHILE loops: used for conditional loops Express conditions in Python: the IF-ELSE command Built-in functions 20/11/2018

28 Conditions Often you will find yourself in a situation that a certain part of your program should only be executed if a certain condition is met. If the condition is not met, that part of the code will not be executed. For example, if a number is greater than 100, say, you want to do a certain calculation with that number. But if it is smaller than 100, you don’t want to do that calculation. We have seen an example earlier of such a case. 20/11/2018

29 Conditions (2) Calculation only executed if the number is less or equal 10. 20/11/2018

30 Equal (NOTE: two equal signs!!)
Conditions (3) The table shows a list of unary and binary operators used in conditions: Operator Meaning < Less than > Greater than <= Less or equal than >= Greater or equal than == Equal (NOTE: two equal signs!!) != Not equal For example, while(i<=j) means that the condition i<=j will be checked first and a result will be returned - either True (or equivalently 1) or False (or equivalently 0) - and if the result is True, the while loop will be performed. It will not be performed if the result is False. 20/11/2018

31 The IF command The IF command allows the programmer to execute a code only if a certain condition is met. Syntax: if(condition): Statement 1 Statement 2 ... 20/11/2018

32 The IF command (2) This is the output of the previous code: 20/11/2018

33 The IF-ELSE command The if-else-command is a slight extension of the if-command. Syntax: If condition is TRUE, Statement 1, Statement 2 will be executed and the statements after the ELSE command will not be executed. If condition is FALSE, Statements 1 and 2 will not be executed, but Statement 3 and 4 will be executed. if(condition): Statement 1 Statement 2 else: Statement 3 Statement 4 20/11/2018

34 The IF-ELSE command (2) Example of a conditional statement using the IF-ELSE command. 20/11/2018

35 BREAK command Note first the WHILE command: “while True:” This is always true, so the loop itself would never stop! However, within the WHILE loop a IF-ELSE statement is performed. If the answer is “yes”, a new input is read and attached to the string already entered. If the answer is “no”, then the commands behind the ELSE command are performed. In this case, it is the BREAK command. The break command stops the inner most loop. Here the loop is the WHILE loop. So the BREAK command can be used to force the termination of a loop (all the statements of the innermost loop after the break are not executed). 20/11/2018

36 CONTINUE command As in other programming languages, the CONTINUE command is a variant of the break. The CONTINUE statement exits the current iteration of a loop and transfers control to the next iteration of the current loop. In the FOR loop we iterate in a list of numbers from 2 to 9. For each iteration we print the numbers. The last print is executed only for odd numbers. 20/11/2018

37 CONTINUE command (2) This is the output of the previous script with the CONTINUE command executed in a FOR loop: 20/11/2018

38 The IF-ELIF-ELSE variant
The IF-ELSE command can be modified in order to include several nested conditions: if(condition1): Statement 1 Statement 2 else: if(conditions2): Statement 3 Statement 4 Statement 5 if(condition1): Statement 1 Statement 2 else: if(conditions2): Statement 3 Statement 4 Statement 5 if(condition1): Statement 1 Statement 2 elif (condition2): Statement 3 Statement 4 else: Statement 5 The IF-ELIF-ELSE variant simplifies the program (avoiding too identation spaces) and the identification of the different branches of the conditional command. 20/11/2018

39 Even or Odd? Even or odd? First version. 20/11/2018

40 Even or Odd? Even or odd? Second version. 20/11/2018

41 More Conditions… You can combine conditions as well with and and or. For example: 20/11/2018

42 More Conditions… The output of the previous code is: 20/11/2018

43 The PASS command The PASS statement is a null operation; nothing happens when it executes. The PASS is also useful in places where your code will eventually go, but has not been written yet: The PASS statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. 20/11/2018

44 The PASS command (2) The output of the previous script is the following: 20/11/2018

45 More about conditions The conditions used in the IF command and in the WHILE loop can use other predicates and operators. Very useful are in and not in operators that check the presence (or the not presence) of and element inside an iterable object (list, tuples, etc.). The is and not is operators check whether two iterable objects are the same (this is meaningful for modifiable operators like lists). 20/11/2018

46 More about conditions (2)
This is the output of the previous script (is and in operators inside a condition used in a IF command): 20/11/2018

47 More about conditions (3)
Let us try to write the function is by our own using conditional commands and WHILE loop. 20/11/2018

48 More about conditions (4)
Let us try to write the function is by our own using conditional commands and FOR loop (note the ZIP built-in function)! 20/11/2018

49 Topics In this lecture we study:
FOR loops: used when we know the number of times that a loop will be executed. WHILE loops: used for conditional loops. Express conditions in Python: the IF-ELSE command. Built-in functions 20/11/2018

50 Iterables and Iterators
Iterable: an object capable of returning its members one at a time. Examples (list, str, and tuple) and some non-sequence types like dict and file and user-defined with an __iter__() or __getitem__() method. Iterators: an object representing a stream of data. Repeated calls to the iterator’s next() method return successive items in the stream. Iterables can be used in a FOR loop. When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The FOR loop does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. 20/11/2018

51 Built-in functions The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. You can find an explanation (with source code) of all of these functions at: 20/11/2018

52 Enumerate function The built-in function enumerate will make certain loops a bit clearer. Enumerate(thing), where thing is an iterable object (a string, list, tuple etc.), returns a iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth. Example: 20/11/2018

53 Enumerate function (2) This is the output of the previous script with the enumerate function used with a FOR loop: 20/11/2018

54 ZIP function The built-in ZIP function makes an iterator that aggregates elements from each of the iterables. It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. Example: 20/11/2018

55 ZIP function (2) The output of the previous script is the following:
20/11/2018

56 Reversed function The reversed function inverts the order of an iterable object passed as an argument. It returns a new iterable object. Example: 20/11/2018

57 Reversed function (2) This is the output of the previous script:
20/11/2018

58 Map function map(function, iterable, ...): apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. 20/11/2018

59 Map function (2) Another example of map. The None function is a special one (the identity function). It can be used to combine elements in tuples! 20/11/2018

60 Map function (3) In a map we can use a user-defined function not only built-in functions. In this example we define an anonymous lambda function: 20/11/2018

61 Map function (4) Another example of map with a different use of functions (functions are common citizens in Python)! 20/11/2018

62 Reduce function reduce(function, iterable): apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. Reduce a list to a single value by applying a binary operator. 20/11/2018

63 Map-Reduce Map and Reduce can be combined together. Given a list of items we firstly apply a function F on each element of the list, then we apply a reduce function G on the result of the previous step. 20/11/2018

64 Filter function filter(function, iterable): construct a list from those elements of iterable for which function returns true. 20/11/2018

65 List comprehension Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do. The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics: In Python, you can write these expression almost exactly like a mathematician would do, without having to remember any special cryptic syntax. 20/11/2018

66 List comphrension List comphrension is very powerful. Please refer to the Pyton book (suggested in the course’s homepage) for a full description of the syntax. The general syntax is: [expression for item in list if conditional]. 20/11/2018

67 Sieve of Eratosthenes A set comprehension is similar to a list comprehension, but returns a set and not a list. Syntactically, we use curly brackets instead of square brackets to create a set. Example (“Sieve of Eratosthenes”): calculate all the prime number between 2 and an integer N. The algorithm consists in four steps: Create a list of consecutive integers from 2 through N; Initially, let p equal 2, the first prime number; Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked); Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3. Calculate this set in Python in two ways: Using a classic iterative algorithm; Using the set comphrension. 20/11/2018

68 Sieve of Eratosthenes (2)
This is the first solution based on the iterative algorithm: 20/11/2018

69 Sieve of Eratosthenes (3)
This is the very compact and elegant solution available with Python by exploiting the set comphrension feature of the language: 20/11/2018

70 END 20/11/2018

71 Example Let us suppose we want to check whether a number is even or odd. An even number can be divided by 2 without remainder, but an odd number cannot divided by 2. The %-operator is the modulus operator and checks for the remainder: So, the modulus operator can help us to decide whether a number, call it y, is even or odd: if y%2=0, then y is even. If not, it is odd. Example of modulus: 4%2 = 0 7%2 = 1 572%89 = 38 20/11/2018


Download ppt "Programmazione ad alto livello con Python"

Similar presentations


Ads by Google