Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
We develop some exercises in Python in order to consolidate what we have studied so far.
First exercise in Python
Calculate the area of a circle by taking the radius as input.
So here is the solution to the simple problem in Python:
>>> radius = float(input())
>>> PiGreco = 3.14
>>> area = PiGreco*radius *radius
>>> print(‘the area of the circle of radius’, radius, ‘ is:’, area)
the area of the circle of radius 5.5 is 94,985.
The data to be taken as input is therefore only the radius. PiGreco is a constant value to which I assign the approximate value 3.14.
In Python there is no significant difference between declaring a constant or a variable.
Recall that the constant represents data that does not change during the execution of the program, unlike the variable.
Later we will use the math library and therefore the constant math.pi.
Second exercise in Python
Among the Python exercises that we will deal with today, there is also this very simple one:
Take the price of a product as input and discount it by 30%.
>>> price = float(input())
>>> price -= price *30/100
The expression price -= price * 30/100 is nothing more than the abbreviated form of price = price – price * 30/100, as we explained in the lesson on assignment operators.
You could also write price * = 70/100 or price * = 0.7.
I did everything using a single variable because the price variable is no longer used within the program. If, on the other hand, it is necessary, it would be advisable to create another variable.
Third exercise in Python
We continue with other exercises in Python and therefore I propose the following:
Calculate the area of a trapezoid by taking as input the major base, the minor base and the height.
The resolution of this algorithm is therefore very simple:
>>> B = int(input()) #I take the major base as input.
>>> b = int(input()) #I take the minor base as input.
>>> h = int(input()) #I take the height as input.
>>> area=(B+b)*h/2 #calculating the area of the trapezium
>>> print(‘the trapezius area is: ‘, area) #I view the area
the trapezius area is 704.0.
In this tutorial I have explained some very simple exercises in Python, in the next lessons we will practice again.
Some useful links
How to find the maximum of N numbers