Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli


Appunti su Python ( Inglese ), Appunti di Programmazione Avanzata

Argomenti presenti: • Introduction to computer programming • Variables and data types • Decision-making and iterative structures • Functions • Sequences

Tipologia: Appunti

2021/2022

In vendita dal 06/05/2022

Alicefrag
Alicefrag 🇮🇹

2 documenti

1 / 24

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
!
Lessons 9: Introduction to computer programming (Traditional classroom) ---->Chapters 1, 2.1, 2.2, 2.3!
The computer programming process!
Programming languages !
Python: what is it!
!
Lessons 10: Variables and data types (Traditional classroom) ---->Chapters 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, 4 [exercises: all the exercises of unit 1]!
Python: how to install it !
IDLE: editor and shell!
Variables!
Data types!
Strings and mathematical operators !
Built-in functions!
Introduction to standard library!
!
Lab 7: Summary exercise (Computer room)!
!
Lessons 11: Decision-making and iterative structures (Traditional classroom)---->Chapters 5, 6[exercises: all the exercises of units 2, 3 and 4]!
Decision-making structures!
Logical operators!
Iterative structures !
!
Practice session 5: Programming in Python (Traditional classroom)!
!
Lab 8: Summary exercise (Computer room)!
!
Lessons 12: Functions (Traditional classroom)---->Chapters 7, 10.4, 10.5, 10.6[exercises: all the exercises of units 5 and 6]!
What functions are and what they are useful to!
Python functions !
How to use a function!
How to create a custom function !
Handling exceptions!
!
Practice session 6: Programming in Python. (Traditional classroom)!
!
Lab 9: Summary exercise (Computer room)!
!
Lessons 13: Sequences (Traditional classroom))---->Chapters 8 (except 8.12), 9 [exercises: all the exercises of units 7, 8 and 10]!
Managing strings!
Managing lists!
Managing tuples!
Managing dictionaries!
!
Practice session 7: Programming in Python (Traditional classroom)!
!
Lab 10: Summary exercise (Computer room)!
!
Lessons 14: Classes, attributes and methods (Traditional classroom)!
Classes, attributes, methods!
Accessing files!
Python libraries!
!
Practice session 8: Programming in Python (Traditional classroom)!
!
Lab 11: Summary exercise (Computer room)!
!
!
!
LESSON 9-10: Introduction to computer programming and variables and data types!
WHAT IS PROGRAMMING? => It is basically teaching a machine how to perform a certain task or solve a certain problem (may it be simple or very complex)!
To do it, the computer needs precise instructions!
To provide these instructions the programmer must possess a series of technical skills (know the logic of programming and the specific language) and soft skills
(computational thinking, problem solving, creative thinking)!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
Example: cake recipe!
!
!
!
!
!
DATA MANAGEMENT IN A COMPUTER [VON NEUMANN]!
!
!
!
!
!
!
!
!
!
!
!
!
Programming languages enables the communication between man and machine (CPU), like natural languages do between individuals!
BUS IS THE FOURTH ELEMENT THAT KEEPS ALL THE OTHER THREE CONNECTED-> SET OF CONNECTING WIRES WHICH CONNECT DATAS-> ALL WRITTEN IN A CODE OF 0 AND 1!
Alphabeth made of 2 letters called Binary notation which is the machine language!!!
Example:!
A number: 10011101=2ˆ0 +2ˆ2 +2ˆ3 +2ˆ4 +2ˆ7 =1+4+8+16+128=157 !
A character: 01000001 = 65 = A (ASCII code)!
A pixel: 10100011 = yellow screen pixel!
!
SOFTWARE PROGRAM => It is a sequence of statements through which a computer executes an elaboration (ex. polynomial equations, mobile apps, autonomous driving cars, ...)!
The computer receives inputs (from a keyboard, a file, ...) and provides outputs (to screen, file, network, ...) by means of simple operations:!
mathematical (add, subtract, multiply, ...)!
conditional (if-then-else, ...)!
loops (while, for, ...)!
!
You can think of programming as the process of breaking a large complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of
these basic instructions!
!
!
t
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Anteprima parziale del testo

Scarica Appunti su Python ( Inglese ) e più Appunti in PDF di Programmazione Avanzata solo su Docsity!

Lessons 9: Introduction to computer programming (Traditional classroom) ---->Chapters 1, 2.1, 2.2, 2.

  • The computer programming process
  • Programming languages
  • Python: what is it Lessons 10: Variables and data types (Traditional classroom) ---->Chapters 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, 4 [exercises: all the exercises of unit 1]
  • Python: how to install it
  • IDLE: editor and shell
  • Variables
  • Data types
  • Strings and mathematical operators
  • Built-in functions
  • Introduction to standard library Lab 7: Summary exercise (Computer room) Lessons 11: Decision-making and iterative structures (Traditional classroom)---->Chapters 5, 6[exercises: all the exercises of units 2, 3 and 4]
  • Decision-making structures
  • Logical operators
  • Iterative structures Practice session 5: Programming in Python (Traditional classroom) Lab 8: Summary exercise (Computer room) Lessons 12: Functions (Traditional classroom)---->Chapters 7, 10.4, 10.5, 10.6[exercises: all the exercises of units 5 and 6]
  • What functions are and what they are useful to
  • Python functions
  • How to use a function
  • How to create a custom function
  • Handling exceptions Practice session 6: Programming in Python. (Traditional classroom) Lab 9: Summary exercise (Computer room) Lessons 13: Sequences (Traditional classroom))---->Chapters 8 (except 8.12), 9 [exercises: all the exercises of units 7, 8 and 10]
  • Managing strings
  • Managing lists
  • Managing tuples
  • Managing dictionaries Practice session 7: Programming in Python (Traditional classroom) Lab 10: Summary exercise (Computer room) Lessons 14: Classes, attributes and methods (Traditional classroom)
  • Classes, attributes, methods
  • Accessing files
  • Python libraries Practice session 8: Programming in Python (Traditional classroom) Lab 11: Summary exercise (Computer room)

▶LESSON 9-10: Introduction to computer programming and variables and data types

WHAT IS PROGRAMMING? => It is basically teaching a machine how to perform a certain task or solve a certain problem (may it be simple or very complex)

  • To do it, the computer needs precise instructions
  • To provide these instructions the programmer must possess a series of technical skills (know the logic of programming and the specific language) and soft skills

(computational thinking, problem solving, creative thinking)

Example: cake recipe

DATA MANAGEMENT IN A COMPUTER [VON NEUMANN] Programming languages enables the communication between man and machine (CPU), like natural languages do between individuals BUS IS THE FOURTH ELEMENT THAT KEEPS ALL THE OTHER THREE CONNECTED-> SET OF CONNECTING WIRES WHICH CONNECT DATAS-> ALL WRITTEN IN A CODE OF 0 AND 1 Alphabeth made of 2 letters called Binary notation which is the machine language!! Example:

  • A number: 10011101=2ˆ0 +2ˆ2 +2ˆ3 +2ˆ4 +2ˆ7 =1+4+8+16+128=
  • A character: 01000001 = 65 = A (ASCII code)
  • A pixel: 10100011 = yellow screen pixel SOFTWARE PROGRAM => It is a sequence of statements through which a computer executes an elaboration (ex. polynomial equations, mobile apps, autonomous driving cars, ...) The computer receives inputs (from a keyboard, a file, ...) and provides outputs (to screen, file, network, ...) by means of simple operations:
  • mathematical (add, subtract, multiply, ...)
  • conditional (if-then-else, ...)
  • loops (while, for, ...) You can think of programming as the process of breaking a large complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions t

EXAMPLE OF A PROGRAM IN PHYTON THERE ARE TWO MODALITIES OF TRANSLATING LANGUAGE INTO MACHINE LANGUAGE (0/1) TO BE UNDERSTOOD BY THE MACHINE: WHAT IS PYTHON?

  • Python is a high-level interpreted, interactive (YOU CAN INTERACT ANY SINGLE LINE), object-oriented (WE CAN CREATE SCRIPT TO BE REUSED IN OTHER PROGRAMS) programming language
  • It was conceived by Guido Van Rossum in 1989 and released in 1991, with the aim to correct the defects present in other languages and to take their strengths. The name Python derives from the passion of Guido for the group of British comedians Monty Python
  • Since then Python has grown and has found increasing popularity, first in Web development and, especially in recent years, in the field of data science
  • It is an open source language, constantly improved by the developer community, and completed by several libraries
  • It is a CASE SENSITIVE environment IDLE => (Integrated Development and Learning Environment) is the Python programming environment, which includes two different components:
  • shell (or interpreter, or console), which is used in the interactive mode (or "command line")
    • editor which is used in the script mode >>> 3+2 (Addition) 5 >>> 3-2 (Subtraction) 1 >>> 32 (Multiplication) 6 >>>3/2 (Division) 1. >>> 3//2 (Floor division or integer division) 1 >>> 3%2 (Modulus) => GIVES WHAT REMAINS FROM THE DIVISION 1 >>> 32 (Exponentiation) 9 (*) when the result is negative it is rounded down to the nearest whole number!! MATHEMATICAL EXPRESSIONS: In mathematical expressions, the operations enclosed in parentheses are executed first and then the operator with the highest precedence is applied first:
  • Exponentiation RIGHT TO THE LEFT PRECEDENCE
  • Multiplication and division LEFT TO THE RIGHT PRECEDENCE
  • Addition and subtraction PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) >>> (6 - 3)* (2 + 7) / 3

>>> 6 - 3 * 2 + 7 / 3 2. >>> 5(3-1) 10 >>>23* 512 >>> (22 % 3 + 1)** 4 >>>32* 24 >>>(23) 64 >>> (42//32 + 42%32)** 100 Affetfoo B

ASSIGNMENT STATEMENTS => NEW VARIABLE => GIVES IT A VALUE --------------> Model: Variable name is always on the left, assigned value on the right and the

assignment operator (=) in the middle!!

Examples: >>> surname_professor = 'Wilson' >>> number_students = 86 >>> g = 9.8 1

▻REASSIGNMENT OF VALUES TO VARIABLES (operation of replacing one value with another)

Examples: >>> a=1 => assignment >>> a 1 >>> a=2 => reassignment >>> a 2

▻UPDATING VARIABLES => here, the new value of the variable depends on the previous one!!

Examples: >>> a=1 => previous assignment >>> a 1 >>> a=a+1 => updated assignment (it is necessary to set a value for a, before setting a=a+1) >>> a 2

▻MULTIPLE ASSIGNMENT (also called unpacking ) => allows acting on multiple variables directly on the same line of code

Examples: >>> a,b,z=1,2,3 => previous assignment >>> a 1 >>> b 2 >>> z 3

▶LAB 7 (about lessons 9-10)

DATA TYPES---> To know which type of data a value belongs to, you can use the type function

Examples: >>> x=1 0 >>> type(x)

>>> x=3. 5 >>> type(x)

>>> x=3< 5 >>> type(x)

>>> x='Python' >>> type(x)

*NOTICE: Python has dynamic typing => It means that once we reassign a value, the output given by the function will change as well: Examples: >>> price=10 0 >>> type(price)

>>> price='Depends on the applied discount percentage' => reassigning a value to the variable "price"

>>> type(price)

CONVERSION BETWEEN DATA TYPES---> Sometimes it is impossible to concatenate ore make operations between different types of data (for example between 4 and

"Bocconi"), through conversion it is possible to do it even with variable!!

Examples: >>> 4+"Bocconi" Traceback (most recent call last): File "", line 1, in 4+"Bocconi" TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> "4"+"Bocconi" '4Bocconi'

>>> x= >>> x +"Bocconi" Traceback (most recent call last): File "", line 1, in 4+"Bocconi" TypeError: unsupported operand type(s) for +: 'int' and 'str'

These ERRORS can be solved by using the conversion, in the second example in particular it is possible to use conversion in this way:

>>> str(x)+"Bocconi"=> we convert the content of x to a string with str to concatenate the content of x with "Bocconi"

'4Bocconi'

  • int function: converts to an integer 1) If the conversion is impossible, an error message appears EX. int ('Python') 2) int function does not round the fraction part, but chops it of EX. int (9.9999) gives 9
  • float function: converts to a floating-point number
  • str function: converts to a string

INPUT FUNCTION---> A function which reads what we type, by asking the user to enter some data on the keyboard, and returns it to the program as a string => useful to

assign values to the variables

Example: (We want to know the age of a person) >>> input("What's your age? ")=> there's a space between? and " since we need the space to insert the age What's your age? 25 '25' >>> age= input("What's your age? ") What's your age? 25 >>> age '25'=> written in quotes since whatever the user types it is returned to the program as a sting!!

In fact, if I want to continue by saying how old I'll be next year...

>>> print("Next year I'll be",age+1) => It gives ERROR because the age at the moment is a string, so we need to insert the conversion to an integer of the age

Traceback (most recent call last): File "", line 1, in print("Next year I'll be",age+1) NameError: name 'age' is not defined >>> print("Next year I'll be",int(age)+1) Next year I'll be 26 >>> age= int(input("What's your age? ")) This has the same effect of what we have done before, we simply convert immediately the result of an input to an integer >>> What's your age? 25 >>> age 25 *NOTICE: Here, the limitation is the fact that whatever we write that is not a value, returns an error massage because the int function cannot convert the input we provided!!! Example: >>> age= int(input("What's your age? ")) What's your age? Alice Traceback (most recent call last): File "", line 1, in age= int(input("What's your age? ")) ValueError: invalid literal for int() with base 10: 'Alice'

FORMAT FUNCTION---> A function which allows to convert any type of value to the format we want

Examples: >>> format(10000/7, '.2f')=> The result of 10000/7 to the floating-point with two decimals '1428.57' >>> format(10000/7, ',.2f')=>The result of 10000/7 to the floating-point with two decimals and the comma for the thousands '1,428.57' >>> format(10000/7, ',.2%')=> The result of 10000/7 as a percentage '142,857.14%' SHELL VS EDITOR

  • SHELL : The first thing that appears opening IDLE is the Shell with the prompt of the comment line. In the Shell, we interact directly with Python so, everything we write is immediately executed and we verify the result of an operation or the effect of a command.
  • EDITOR : If we want to write a sequence of lines of code to be executed all together as a program, we need to open the editor and to write our lines of code; in this case, the most efficient approach is to go to FILE TAB of the shell > New File > a new window will open where we can write whatever we want!!!

➤ If I write this on the editor:

NewMate=input ("What's your name? ")=> If we click on ENTER KEY, nothing is executed since we're not on the shell

print("Hello", NewMate)=> CONCATENATE "Hello"with NewMate and there will be a space in between since the default separator is the space

➤ Then it is possible to save it as our first program: FILE TAB > Save as > Decide where to save it and how to call it [the type of file will be a

Python Files whose extention is .py]

➤ If we double click on the file we saved, Python Launcher will open (we will not be very familiar with that window since we got the prompt of

what we are supposed to do, but once we've inserted the data and clicked on the enterkey, the window will close)

✓THE RIGHT WAY TO OPEN THE PHYTON FILE : RIGHT CLICK ON THE FILE > OPEN IT WITH "EDIT WITH IDLE" > RUN > RUN MODULE

The interact window (Shell) will open and there we can elaborate our operations!!!

HOW TO MANAGE ERRORS:

The line which contains the error will be highlighted in RED => Just solve it in order to clear the red string!

❋ EXERCISE 1: Calculate the sum of num1 and num

num1 = 3 num2 = 5 print(total)

SOLUTION=> Define total as total=num1+num2 > Run module > 8

❋ EXERCISE 2: You are asked to write the code necessary to complete the program

'''This program makes the multiplication of two numbers''' a = 10 b = 2 print("The result is:",c)

SOLUTION=> Define c as c=a*b > Run module > The result is: 20

❋ EXERCISE 3: Create a new Python file called Exercise 3.py, in which you are asked to write a program that, after asking the user to separately enter the first name and the

last name (for example John and Snow), shows on the screen the following sentence: Nice to meet you, John Snow!

SOLUTION=> I can rename it by suddenly save it as 'Exercise 3', then I can write:

first_name=input("What is your first name? ") last_name=input("What is your last name? ") print("Nice to meet you,",first_name,last_name+"!")=> At the end we make a sum since we don't want a space between the last name and the"!"

At the end, we will get:

What is your first name? Alice What is your last name? Fragale Nice to meet you, Alice Fragale!

▶LESSON 11: Decision-making and iterative structures

What's the difference between sequential and decision-making structure?

-SEQUENTIAL STRUCTURE= one after the other: that is a set of statements which are executed in the order they occur

Example:

-DECISION-MAKING STRUCTURE= [similar to the if function in Excel] a certain action is performed only when specific conditions occur, in this case, we can specify one or

more instructions that are executed if a condition is true (and others if it is false);

There are several types of decision-making structures:

  • Simple decision-making structure (or conditional execution, or single alternative)---->EX. Is it cold outside? TRUE (put on tour coat, put on your hat...'statements') or

FALSE

  • Alternative execution (or double alternative)
  • Chained conditionals [INDENTATION= If a line is indented significa che il margine è spostato rispetto al limite sinistro: nel caso dell'if statement, quando la line è indented si tratta di una statement del body]!!! Decision-making structures are implemented in the code by conditional statements , which in Python are: if, else and elif!!! ◦ IF statement: used to implement a decision-making structure. In the case of a single-alternative structure, the syntax will be: if condition: => Heading (if clause) statement statement => Body (intended statement block) etc. [rest of the script] *NOTICE: If the condition is false, the statement block is skipped and the program continues with the rest of the script

BOOLEAN EXPRESSIONS---> The conditions of the if statement are implemented by means of Boolean expressions (EX. expressions that can be true or false), they use

comparison operators (<, > etc.) and return True , whether they are true, or False

*NOTICE: (True and False are special values of bool type, and they must be typed with a capital letter. They are NOT strings!!)

Example: >>> 5> 3 True >>> 3> 5 False >>> type(True)

COMPARISON OPERATORS---> The comparison can include values (integers, floats, strings etc.), variables or functions

Example: a>= 5 length<=width name=='goofy' x>=average(y,z)

>>>3==4 =>with "=" and "!=" we can compare any kind of data

False

True

>>>"a"== 3

False

>>>"a"!= 3

True

>>>4<5 =>with "<, >, <=, >=" we can compare data of the same kind

True

>>>"a"<"b"

True =>because of the alphabetical order

True

False =>since if you take a list of strings and you sort it anything which sarts with 0 comes before

>>>"a"<"3"

False =>since if you sort strings of digits and letters, digits comes before letters!! (in order: punctuation symbols, digits, letters)

>>>"a"<3 =>since it is a comparison with "<" between two different kinds of data

Traceback (most recent call last):

File "", line 1, in

"a"< 3

TypeError: '<' not supported between instances of 'str' and 'int'

✹ EXAMPLE OF IF STATEMENT

x=int(input('Enter the value of x: '))

if x>0:

print('x is positive')

Enter the value of x: 12

x is positive

Enter the value of x: -

LOGIC=> START > ASK FOR THE VALUE OF X > X>0 > PRINT 'X is positive' (IF TRUE) OR END (IF FALSE)

IF-ELSE statement: enables to print a double alternative decision-making structure, which implies two possible execution paths, depending on whether the condition is true or false!! In the case, the general syntax for the if-else statement is as follows: if condition: statement statement etc. else: statement statement etc. [rest of the script]

✹ EXAMPLE OF IF-ELSE STATEMENT

One statement-> x=int(input('Enter the value of x: '))

if x>0: =>once I write :, the new line will be already indented!!

print('x is positive')

else:

print

('x is negative or 0')

Enter the value of x: 12

x is positive

Enter the value of x: -

x is negative or 0

LOGIC=> START > ASK FOR THE VALUE OF X > X>0 > PRINT 'X is positive' (IF TRUE) OR PRINT 'X is negative or 0' (IF FALSE) > END

More statements-> x=int(input('Enter the value of x: '))

if x>0:

print('x is positive')

print('Thank you! Have a good day.')

Enter the value of x: 12

x is positive

Thank you! Have a good day.

Enter the value of x: - 3

x=int(input('Enter the value of x: '))

if x>0:

print('x is positive')

Without indentation-> print('Thank you! Have a good day.')

Enter the value of x: 12

x is positive

Thank you! Have a good day.

Enter the value of x: - 3

Thank you! Have a good day.

❋ EXERCISE slide 13

Set up a program which:

  • Requires the user to enter a password (“Enter the password:”)
  • Defines whether the entered password is correct, by comparing it to the one saved into the code (i.e. “5ecure”)
  • Prints “Password accepted”, if the password which has been typed is correct
  • Prints “Sorry, wrong password”, if the password is not correct

password=input('Enter a password: ')

if password=='5ecure':

print('Password accepted.')

else:

print('Sorry, the password is wrong.')

Enter a password: 5ecure

Password accepted.

Enter a password: Star 2

Sorry, the password is wrong.

NESTED conditions: when more difficult situations occur (more conditions with more possible outputs), it is possible to nest different if-else statements In order to verify two conditions with three possible outputs, the syntax is the following:

if condition1:

statements

else:

if condition2:

statements

else:

statements

[rest of the script]

✹ EXAMPLE OF NESTED CONDITIONS

x=int(input('Enter the value of x: '))

if x>0:

print('x is positive')

else:

if x<0:

print('x is negative')

else:

print('x is 0')

❋ EXERCISE slide 17

Set up a program which:

  • Requires the user to enter how tall he/she is (“How tall are you (in cm)?”)
  • Requires the user to enter how tall is the person on his/her right (“How tall is the person on your right (in cm)?”)
  • Prints one of the following outputs:
  • “You are taller than the person on your right!”
  • “You are shorter than the person on your right!”
  • “What a coincidence: you are tall exactly like the person on your right!”

[...continues in the next page...]

More examples:

rain=input('Is it raining? (Yes or No)') =>Here, if the user will write 'yes' without the upper case it will be considered as false!! (we can solce with the in statement)

temp=int(input('How many degrees are there outside? ºC = '))

if rain=="Yes" and temp<=15:

print("Put on your coat and take the umbrella!")

elif rain=="Yes" and temp>15:

print("Take the umbrella!")

elif rain=="No" and temp<=15:

print("Put on your coat!")

else:

print("Have a nice walk!")

THE if WITH in STATEMENT---> The logical test of the if function can provide a comparison also with a list of values or with a range (SO THE in OPERATOR VERIFIES IF AND ELEMENT BELONGS TO A LIST OF ELEMENTS/VALUES!!) Example (with respect to the previous example):

if rain in ["Yes","yes","YES","y","Y"] and temp <=15:

print('Put your coat and take the umbrella!')

If we need to check if a value is within a range... we can use the range function (range (start, stop [, step])): returns an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by increments of step (integers), so, for example: range (i,j) => produces: i, i+1, i+2, ..., j- 1 range (4) => produces: 0,1,2,3 (if the start is omitted, the default value is 0 ) Example:

a=

if a in range (6,12):

print('The value is OK!')

else:

print('The value is not in the range')

The value is not in the range! =>Since the stop is excluded

ITERATIVE CONSTRUCTS---> Iteration is the ability to execute repeatedly a same block of statements: it is an essential feature of programming languages, which is implemented by means of constructs called loops (portion of code repeatedly executed a number of times that can be reported according to the kind of loop we are dealing with) which are grouped into two categories: loops controlled by a condition [=we can can ignore the number of times it will be repeated, while loop is used] and loops controlled by a counter [=we can know from a counter how many times it will be repeated, for loop is used] (like many other programming languages, Python’s main iterative constructs are while and for loops)

while statement => enables to create a loop controlled by a condition

Syntax:

while condition:

statement =>All these statements will be repeated until the condition becomes false!!

statement

statement

[rest of the script]

Example (1):

x=

while x <=10: =>If x is less or equal to 10, then x will be printed and x will be incremented of 1

print(x)

x=x+1 =>In this case, the result will be 2 , therefore we'll test with x=2 and so on until x>

Variations of the example: ‣ Modify the example to print «bye bye!» one time only, at the end of the list:

x=

while x <=10:

print(x)

x=x+

print('bye bye!')=>In this way it is considered as part of the script and not of the while function

‣ Modify the example to print the same list of numbers, but in a reversed order (from 10 to 1):

x=10 =>The first has to be 10

while x >=0:

print(x)

x=x-

‣ Modify the example to print a sequence of numbers based on the inputs given by the user (e.g. all even numbers from 8 to 24) => WE WON'T USE THE range FUNCTION!!

bottom=int(input("enter the starting integer: "))

top=int(input("enter the ending integer: "))

increment=int(input("enter the increment: "))

x=bottom

while x <=top:

print(x)

x=x+increment

enter the starting integer: 2

enter the ending integer: 10

enter the increment: 2

Example (2):

keep_going= 'y'

while keep_going == 'y':

ID_num=input("\nEnter the student ID number: ")

last_name=input("Enter the last name: ")

name=input("Enter the name: ")

print("\nWelcome",name,last_name,"("+ID_num+")")

keep_going=input("Do you want to enter data for another student? (y/n)")

Enter the student ID number: 3159546

Enter the last name: Fragale

Enter the name: Alice

Welcome Alice Fragale (3159546)

Do you want to enter data for another student? (y/n) y

Enter the student ID number: 3215472

Enter the last name: Doe

Enter the name: Jane

Welcome Jane Doe (3215472)

Do you want to enter data for another student? (y/n) n

for statement => enables to create a loop controlled by a counter.

Syntax:

for variable in [value1, value2, etc.]:

statement =>All these statements will be repeated until the condition becomes false!!

statement

statement

[rest of the script]

Example (1): If I want to greet a group of people...

for name in [Alice, Carmen, Gloria]: =>The for loop doesn't requires the initialization of the variable since it creates an assignment to the variable used in the condition assigning to it

print("Hi",name+"!") each value of the list which is next to it, one after the other: so there is not initialization because the for loop itself takes care of assigning to the

variable used each of the variable contained in the list (IT IS POSSIBLE TO USE THE range FUNCTION, INSTEAD OF USING A LIST OF VALUE)

Hi Alice!

Hi Carmen!

Hi Gloria!

Example (2):

for num in [1,2,3,4,5]:

print(num)

Variations of the example (2): ‣ Modify the example to use range function

for num in range(1,6):

print(num)

‣ Modify the example to use range(5)

for num in range(5):

print(num+1)=>Given range(5)we have not a starting number therefore we'll consider the 0 as default and by writing print(num+1) we'll get the same result as in the range(1,6)!!!

‣ Modify the example to show numbers from 5 to 1 , using range

for num in range(5,0,-1):

print(num)

Example (3): Create a program that asks the user to enter an integer number and that print the multiplication table of that number (i.e all values from n to n*10)

num=int(input("Enter an integer number: "))

for i in range(1,11):

print(num,'x',i,'=',num*i)

Enter an integer number: 8

8x1=

8x2=

8x3=

8x4=

8x5=4 0

8x6=4 8

8x7=5 6

8x8=6 4

8x9=7 2

8x10=8 0

THE BREAK AND CONTINUE STATEMENTS---> They are two statements which can be used within the body of a loop to have two effects:

  • break statement: the effect that the loop is suddenly and immediately interrupted
  • continue statement: the body of the statements within the loop is shortcutted bringing to the next shift The two statements perform, therefore, the exit from the loop (the break) or the immediate execution of the following shift (the continue): in order to have sense, there are condition that if satisfied, the loop goes on with the remaining part of the script or, if not satisfied, the loop ends up immediately!! Among the statements we can insert other tests that might have other condition to evaluate when a running a single shift of the loop and the scheme might become like this Here, we have the sample in which we are both using continue and break: we have to run all the statements of the loop ...in this example...
  • Statement 1>condition>if it is not satisfied it creates a shortcut back to the while condition (continue)
  • Statement 1>condition>if it is satisfied>Statement 2>condition>if it is satisfied>Statement 3
  • Statement 1>condition>if it is satisfied>Statement 2>condition>if it is not satisfied>break (interruption)

income=float(input('Which is your annual income? '))

if income<=10000:

taxes=income* 0

elif income<=29000:

taxes=income*0. 2

elif income<=65000:

taxes=income*0. 3

elif income<=110000:

taxes=income*0. 4

else:

taxes=income*0.4 5

available_income=income-taxes

print('Taxes to be paid amount to',format(taxes,'.2f'),'euros.')

print('The available income is:',format(availabel_income,'.2f'),'euros.')

while True:

savings = float(input('How much of your available income do you want to save? '))

if savings <= available_income * 0.50:

break

else:

print('You cannot save more than 50% of the available income!')

  1. Creation of a program that shows on screen some numbers Create a new Python file called range.py that shows on screen all the numbers between two numbers, excluding the multiples of 3 and 5. In particular, the program must:
  • ask the user two integer numbers, one between 0 and 10 (both included) and the other greater than 10;
  • make sure that if the entered numbers do not meet the requirements, the user is asked again to enter the numbers until they are both correct;
  • show on screen all the numbers between the first and the second entered number (both included), except the multiples of 3 and the multiples of 5.

while True:

integer_1=int(input('Enter an integer between 0 and 10 (both included): '))

if integer_1>=0 and integer_1<=10:

break

else:

print('First number must be between 0 and 10 (both included). Try again!')

while True:

integer_2=int(input('Enter an integer greater than 10: '))

if integer_2>=10:

break

else:

print('The second number must be greater than 10. Try again!')

for n in range(num1, num2+1):

if n % 3 == 0 or n % 5 == 0 :

continue

print(n)

▶LAB 8 (about lessons 11)

❋ EXERCISE 1: Create a new Python file named Exercise 1.py, in which you are asked to write a program that, using a loop controlled by a condition, shows on the screen

all integers between the number entered by the user (and stored in variable a) and 0, both included.

SOLUTION=> a = int(input('Insert an integer number: '))

while a >= 0 :

print(a)

a = a - 1

❋ EXERCISE 2: Create a new Python file named Exercise 2.py, in which you are asked to write a program that:

  • asks the user for two integers (the second one should be greater than the first one),
  • shows on screen all the integers between the lowest and highest number entered (both excluded)

Also consider the case in which the two numbers entered are equal and the case in which the second number is less than the first, showing an explanation message on the

screen in both cases.

SOLUTION=> num_1=int(input('Enter an integer: '))

num_2=int(input('Enter an integer greater than the previous one: '))

if num_1 == num_2:

print("Please, enter two different numbers!")

elif num_1 num1 = int(input("Enter a positive number: "))

num2 = int(input("Enter another positive number greater than the previous: "))

import random

print(abs(random.randint(num1,num2))-num1)

print(abs(random.randint(num1,num2))-num2)

❋ EXERCISE 4: The file Exercise 4.py contains a program written in Python to automatically solve a problem related to triangles. The program must:

  • ask the user for three numbers (with or without decimals), corresponding to the lengths of the sides of a triangle
  • verify that all numbers entered are positive and that, for all possible combinations, each side is less than the sum of the other two (otherwise the lengths provided could not

generate a triangle)

  • in case the previous check is positive, the program prints on screen the message: “With these measures, it is” followed by the typeof triangle: equilateral (when all three

sides are equal), isosceles (when two sides are equal) or scalene (when all sides are different).

The program is incomplete and contains only some instructions. You are asked to complete it by writing the missing lines of code.

SOLUTION=> a = float(input('Insert first side length: '))

b = float(input('Insert second side length: '))

c = float(input('Insert third side length: '))

if a>0 and b>0 and c>0 and a < (b + c) and b < (a + c) and c < (a + b):

if a==b==c:

print("With these measures, it is equilateral")

if a==b or b==c or a==c:

print("With these measures, it is isosceles")

if a!=b!=c:

print("With these measures, it is scalene")

else:

print("These measures cannot represent the sides of a triangle!")

❋ EXERCISE 5: Create a new Python file named Exercise 5.py, in which you are asked to write a program that, using a loop controlled by a counter, shows on the screen all

integers from 0 to a number entered by the user (this last excluded).

The loop must be set to perform a maximum of 100 iterations.

SOLUTION=> num = int(input('Enter a number: '))

for i in range (100):

if i!=num:

print(i)

else:

break

→THINGS LEARNED BY DOING EXERCISES UNIT 3

  • if it is asked to show on screen the square of a series of numbers (by using a loop controlled by a counter) in which the user is asked to insert 10 numbers: for i in range(10): num = float(input('Enter a number: ')) print('The square of', num, 'is:', num * num)
  • if it is asked to show on screen a series of integers in ascending order: num_1=int(input('Enter a number greater than 100 (upper limit): ')) num_2=int(input('Enter a number (lower limit): ')) step=int(input('Enter a number greater than 0 (step): ')) if num_1>100 and step>0: while num_1>=num_2: print(num_1) num_1=num_1-step else: print("Requirements not met!")
  • if it is asked to show on screen the cubed values: num=int(input('Enter an integer: ')) while num<=200: print("The number",num,"raised to the cube is equal to",format(num**3,',.0f'))=> Here the formatting has been made by using thousands separators and without decimals!! num=num+1 0
  • if it is asked to create a program in which your favorite dishes are counted (the ones you enter) until you write certains words: count= 0 while True: fav=input('Enter your favourite dishes (Write STOP, Stop or stop to stop asking): ') if fav in ['STOP', 'stop', 'Stop']: break count=count+ 1 print('You like', count,'dishes')
  • if it is asked to show on screen the results of the sum and the multiplication of a series of numbers, in which the user can enter numbers until he wish to do it (until when he

digits "n"); in the second case you also enter the sum and the product of all the numbers entered:

num=float(input('Enter an integer or a decimal number: ')) pluto = str(input('Enter n if you wish to stop: ')) while pluto != "n": num_1=float(input('Enter an integer or a decimal number: ')) pluto = str(input('Enter n if you wish to stop: ')) num=float(input('Enter an integer or a decimal number: ')) som = num prd = num pluto = str(input('Enter n if you wish to stop: ')) while pluto != "n": num_1=float(input('Enter an integer or a decimal number: ')) som = num + num_ 1 prd = num * num_ 1 pluto = str(input('Enter n if you wish to stop: ')) print("The sum is",som) print("The product is",prd)

  • if it is asked to show on screen a series of numbers in descending order in a range established by two limits and a step entrered by the user: "for i in

range(num_2,num_1-1,- step):"

  • if it is asked to enter n numbers (from a certain value), which have some characteristics...: num_1=int(input('Enter a number: ')) num_2=float(input('Enter a number: ')) i= 0 while i<10: num_1+= 1 if num_1 % num_2==0: i += 1 print(num_1**2)
  • Printing all the factors of an integer greater than 0: num=int(input("Enter an integer greater than 0: ")) while num<0: num=int(input("Invalid number, enter a new number: ")) for i in range(1,num+1): if num%i==0: print(i)

Example: def cheers (FirstName, LastName=""): print('Hi', FirstName, LastName, 'is it everything ok?') gives: >>> cheers('John','Smith') Hi John Smith is it everything ok? >>> cheers('Mary') Hi Mary is it everything ok? => Here, there is an extra space after the name since the default value for the missing LastName is a blank space >>> cheers() => Here, it gives ERROR since the syntax of the function gives at least the FirstName as mandatory!! Traceback (most recent call last): File "", line 1, in cheers() TypeError: cheers() missing 1 required positional argument: 'FirstName'

MORE ON PARAMETERS:

‣ If mandatory parameters are specified when defining a function, a corresponding number of arguments should be provided when the function is called

‣ When a function with parameters is called, it is necessary to specify the arguments by position (in the same order in which the parameters were defined), or

to use the assigned name (keyword arguments)

‣ In the call it is possible to use both arguments by position and keyword arguments, but in this case it is necessary to write first the arguments by position

and then the keyword arguments

‣ It is possible to pass a variable as an argument to a function

Example: def calc (x, y, z=10): total=(x+y)/z return total gives: >>> calc(140, 60 )

  1. 0 >>> calc(140, 60, 5 )
  2. 0 >>> calc(x=140, y=60, z=5)
  3. 0 >>> calc(y=60, z=5, x=140) => Keyword arguments
  4. 0 >>> calc(140, z=5, y=60) => The first argument is defined by position, while the second and the third are defined by keywords!!
  5. 0 >>> calc(z=5, 140, 60 ) SyntaxError: positional argument follows keyword argument => Here, it gives ERROR since we should keep in mind that we can use any of the previous approaches but if we want to use the mixed approach (with keyword and positional arguments) we have to define FIRST THOSE BY POSITION AND THEN THOSE BY KEYWORDS !!!

PRODUCTIVE FUNCTION ===> It is a set of instructions that performs a specific task returning, when it ends, a value to the instruction that called it

Productive functions always end with the return statement, which closes the body of the function (any other instructions after the return statement are not taken

into account...)

VOID FUNCTION ===> A function that performs a specific task, but that when it ends does not return any value to the instruction (in this case, since the value is not returned

to the calling instruction, it cannot be stored or reused)

DIFFERENCE BETWEEN print AND return: def MySqrt1 (val): SqrtVal=val0. 5 print (SqrtVal)=> VOID FUNCTION def MySqrt2 (val): SqrtVal=val0. 5 return (SqrtVal)=> PRODUCTIVE FUNCTION >>> MySqrt1(16) => But if I want to do something more elaborated such as (MySqrt1(16)*5)+120 it gives 4.0 and then Error

>>> MySqrt2(16) => Instedad, if I do the same with (MySqrt2(16)*5)+120 it gives 140.

  1. 0 WHY DOES THIS HAPPEN? ---> Because with the print statement it is just meant to show on the screen the result of the root of val, so it will continue giving MySqrt1(16)even if there are other calculations to do... In this case, it is like I'm trying to multiply in integer ( 5 ) with nothing (MySqrt1(16)) since it just corresponds to the name of the value!! In fact: >>> type(MySqrt1(16))
  2. 0

>>> type(MySqrt2(16))

GLOBAL VARIABLE ===> can be reached by any instruction in a program

LOCAL VARIABLE ===> (= AVAILABLE IN THE BODY OF THE FUNCTION) can be reached only within its scope, that is within the part of the program in which it was

defined, such as a function to the calling instruction, it cannot be stored or reused...[Within a function we can create local variables to facilitate calculations, temporarily store

a value, make the code more readable]

Example: c=100 => c is a global variable def NewCalc (a, b): NewTotal=(a/b)*c => NewTotal is a local variable return NewTotal print ("The value of c is:",c) => Can I print c (which is a global variable)? Yes, we can manage it wherever we want print ("The result of 'NewCalc(20,5)' is:", NewCalc(20,5)) print ("The value of variable 'NewTotal' is:", NewTotal) => Can I print NewTotal (which is a local variable) outside the body of the function? No, it gives Error The value of c is: 100 The result of 'NewCalc(20,5)' is: 400. Traceback (most recent call): File "/Users/alicefrag/Documents/j.py", line 7, in print ("The value of variable 'NewTotal' is:", NewTotal) NameError: name 'NewTotal' is not defined Differently: c= NewTotal= def NewCalc (a, b):

NewTotal=(a/b)*c => If I disable this line and define the variable before the definition of the function, the variable becomes a global variable!!

return NewTotal print ("The value of c is:",c) print ("The result of 'NewCalc(20,5)' is:", NewCalc(20,5)) print ("The value of variable 'NewTotal' is:", NewTotal)

The value of c is: 100 The result of 'NewCalc(20,5)' is: 15 The value of variable 'NewTotal' is: 15 What if I do something like... c= def NewCalc (a, b): c= 50 => I redefine the value of the global variable c in the body of the function NewTotal=(a/b)*c return NewTotal print ("The result of 'NewCalc(20,5)' is:", NewCalc(20,5)) print ("The value of c is:",c) The result of 'NewCalc(20,5)' is: 200 The value of c is: 100

THE DOCSTRING ===> When creating a function it is possible to insert a few lines of explanation or a comment by defining a docstring: it consists of a text string on one or

more lines enclosed in triple quotes ('''...'''), inserted as the first statement immediately after the header, when defining a function.

The docstring content is visible when reading the code, when using the help function or in the call tip

FUNCTIONS WITH LOOPS AND CONDITIONAL STATEMENTS ===> In the body of functions we cannot have just simple calculations but also loops and conditional

functions and more...

Example (1) => What does this function is supposed to do? We consider and integer in the range which goes from 1 to num and return the total... def sum_range (num): total= 0 for n in range(1,num+1) total=total+n return total Example (2) => We have three return statement: the execution of this block brings to just one return def discount (quant, price): if quant > 100 : return quantprice(1-0.4) elif quant > 50 : return quantprice(1-0.2) else: return quant*price Example (3) => Hybrid function since it returns a how many odd and even numbers are included in the range which goes from 1 to num! def odd_even (num): count_odd= count_even= 0 for n in range(1,num+1) if n%2==0: => If it is even count_even=count_even+ 1 else: count_odd=count_odd+ print("Number of even numbers: ",count_even) print("Number of odd numbers: ",count_odd) return count_even *NOTICE: IF I CREATE A FILE IN WHICH THERE ARE FUNCTIONS I CREATED AND SAVE IT, I CAN USE THOSE FUNCTION BY IMPORTING IT IN THE NEW FILE WITH THE SYNTAX :import name

EXCEPTIONS ===> An exception is an event triggered by something which doesn't work and that is showed to the user as an Error

[Errors cannot be cancelled but need to be handled!!]

‣ Syntax errors: there is an error in how the code is written---> Python shows an error message (traceback message) in the shell and indicates the point

in the code where the error occurs, but does not specify how to correct it: the error message always starts with SyntaxError

‣ Runtime errors: indicate that there is an error in the code, even if the syntax is correct---> Python shows an error message (in the shell only) indicating the

part of the code that generates the error and specifying the cause

‣ Semantic errors: these occur when the program is executed without producing error messages, but the results are not the correct ones (they are

inconsistent or not expected)--->They derive from a wrong code design (they are also called logic errors ) and since they are tricky to find, in order to find

them is required a step by step re-reading of the code, or the use of more sophisticated debugging tools ( Debugger )

EXCEPTIONS ===> Python always provides some instructions for handling errors (=means preventing them, instructing the program on what to do in case they should

occur). The most common instruction is try... except that lets you specify how errors should be handled

Example: Let’s create a program that performs a simple division between two integer numbers entered by the user. The program must prevent from any kind of error while entering numbers:

  • Text entered instead of numbers, or decimal numbers (ValueError)
  • A zero entered in the denominator (ZeroDivisionError)
  • Any other error BAE

def present_value(r, N, CF):

total = 0

for years in range(1, N+1):

PV=CV/(1+r)**year

total= total+PV

return total

▶LAB 9 (about lessons 12)

❋ EXERCISE 1: In a new Python file named Exercise 1.py create a function that:

  • has an integer as a mandatory parameter
  • counts how many integers between 0 and the number passed to the function as a mandatory argument are divisible by 3 and by 7 but not by 5
  • returns the result of this count

SOLUTION=> def divisors(num):

counter= 0

for n in range (num+1):

if n%3==0 and n%7==0 and not n%5==0:

counter=counter+ 1

return counter

>>>divisors(10)

>>>divisors(21)

❋ EXERCISE 2: In a new Python file named Exercise 2.py create a function (without parameters) that:

  • asks the user to enter a series of integers (as many as he wishes)
  • calculates the sum and the average of those numbers
  • returns a text string as the following: “Sum: NNN -Average: NNN.NN”, where the value of the average is formatted with two decimals.

SOLUTION=> def sum_avg():

more="yes"

total= 0

counter= 0

while more=="yes":

number=int(input('Please, enter an integer number: '))

total=total+number

counter=counter+ 1

more=input("Do you want to enter another integer? (yes/no): ")

return "Sum: "+str(total)+" - Average: "+format(total/counter,'.2f')

>>>sum_avg()

Please, enter an integer number: 10

Do you want to enter another integer? (yes/no): yes

Please, enter an integer number: 20

Do you want to enter another integer? (yes/no): no

Sum: 30 - Average: 15.

❋ EXERCISE 3: Create a new Python file with the name Exercise 3.py, in which you are asked to write a program that:

  • asks the user to enter two numbers (numerator and denominator) also allowing numbers with decimals
  • assigns the result of the division between these numbers to a variable and shows the result on screen
  • handles specifically exceptions due to entering a text string instead of the numbers requested in input
  • handles specifically any division by zero errors
  • handles all other possible errors with a single instruction

SOLUTION=> try:

numerator=float(input('Enter a number: '))

denominator=float(input('Enter a number: '))

division=print(numerator/denominator)

except ValueError:

print("\nPlease enter a number, not a text string!")

except ZeroDivisionError:

print("\nOne of the two values is 0! \n \

Please try again from the beginning with another number!")

except:

print("\nSomething's wrong: try again with other numbers!")

❋ EXERCISE 4: The file Exercise 4.py, contains a program written in Python to calculate the area of the square, triangle or circle. The program must:

  • have the choice of the geometric figure for which to calculate the area as an optional parameter. If there is no argument passed to the function, the default value should be

1 (circle area). The other possible values are 2 for the triangle or 3 for the square

  • ask the user for the necessary values for calculating the area of the chosen geometric figure (radius for the circle, base and height for the triangle, side for the square),

allowing the decimal values

  • calculate the area of the chosen geometric figure
  • return the area of the chosen geometric figure

SOLUTION=> def geometry(choice=1):

if choice == 1 :

radius = float(input('Enter the radius value: '))

area = radius * radius * 3.

elif choice == 2 :

base=float(input('Enter the base value: '))

height=float(input('Enter the height value: '))

area=base*height/ 2

elif choice == 3 :

side=float(input('Enter the side value: '))

area=side*side

else:

print("The request cannot be processed")

area=

return area

❋ EXERCISE 5: Create a new Python file with the name Exercise 5.py, in which you are asked to write a function that:

  • has two integers as mandatory parameters
  • converts into integers any number with decimals passed to the function as arguments
  • shows on screen all the even numbers between the two integers passed as arguments (both inclusive). Note: the second number should be greater than the first, but also

consider the opposite case

SOLUTION=> def function (num_1,num_2):

n_1=int(num_1)

n_2=int(num_2)

for n in range(n_1,n_2+1):

if n%2==0:

print(n)

>>>function(2,7)

❋ EXERCISE 6: Create a new Python file with the name Exercise 6.py, in which you are asked to write the test_range function that checks if an integer passed as an

argument is included in two ranges of numbers. In particular, the function must:

  • have the integer to be checked as a mandatory parameter
  • check whether an integer passed as an argument is between 1 and 50 (both inclusive) or between 150 and 200 (both inclusive)
  • return the same number passed as an argument, otherwise 0

SOLUTION=> def test_range(num):

if 1<=num<=50 or 150<=num<=200:

return num

else:

num= 0

return num

>>>test_range(3)

>>>test_range(133)