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


Esercizi e Soluzioni di Laboratorio Python: Funzioni - Prof. Sanna, Esercizi di Fondamenti di informatica

Esercizi pratici e soluzioni per il laboratorio python incentrati sulle funzioni. Una guida chiara e concisa per comprendere e applicare le funzioni in python attraverso esempi concreti. Include esercizi sulla manipolazione di stringhe, calcoli geometrici e applicazioni finanziarie, fornendo spiegazioni dettagliate per ogni soluzione. Ideale per studenti e appassionati che desiderano migliorare le proprie competenze di programmazione in python. Gli esercizi coprono il conteggio di vocali e parole in una stringa, il calcolo di volumi e superfici di solidi geometrici, la gestione di bilanci bancari con interessi e la determinazione di sussidi finanziari basati sul reddito familiare. Ogni esercizio è accompagnato da una spiegazione chiara del codice, rendendo il documento uno strumento didattico efficace e completo. Perfetto per chi cerca di approfondire la propria conoscenza delle funzioni in python attraverso la pratica e l'analisi di esempi reali.

Tipologia: Esercizi

2025/2026

In vendita dal 05/12/2025

simone_altaserse
simone_altaserse 🇮🇹

5

(1)

88 documenti

1 / 8

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
def count_vowels(string):
VowelsNumber = 0
for ch in string:
if ch.lower() in 'aeiou':
VowelsNumber += 1
return VowelsNumber
def main():
StringEntered = input("Enter the string: ")
print(f"Number of vowels in your string: {count_vowels(StringEntered)}")
main()
S
o
l
ut
i
on
:
Solution:
Python Lab 06: Functions
Exercises and solutions
Write the function:
def count_words(string)
that returns the number of words in the given string. Words are sequences of characters
separated by spaces (assume that there is exactly one space between two consecutive
words).
For example, count_words("Mary had a little lamb") should return 5.
Extension: How could the function be modified to correctly handle strings where multiple
spaces appear between words?
06.1.2 Word counting
Write the function:
def count_vowels(string)
that returns the number of vowels in the given string. Vowels are the letters a, e, i, o, u,
including their uppercase versions.
06.1.1 Vowel counting
def count_words(string):
counter = 0
for i in range(0, len(string), 1):
if (string[i].isspace() and string[i-1].isalpha()) or i == len(string)-1:
counter += 1
return counter
S
o
l
ut
i
on
:
Solution:
E
xp
la
n
a
t
i
on
Explanation
The program counts how many vowels are in a string. The count_vowels function goes through
each character in the string and, if it is a vowel, it increments a counter. In the main function,
the user enters a string and the program prints the number of vowels found.
pf3
pf4
pf5
pf8

Anteprima parziale del testo

Scarica Esercizi e Soluzioni di Laboratorio Python: Funzioni - Prof. Sanna e più Esercizi in PDF di Fondamenti di informatica solo su Docsity!

def count_vowels(string): VowelsNumber = 0

for ch in string: if ch.lower() in 'aeiou': VowelsNumber += 1

return VowelsNumber

def main(): StringEntered = input("Enter the string: ") print(f"Number of vowels in your string: {count_vowels(StringEntered)}")

main()

SSolution:olution:

Python Lab 06: Functions

Exercises and solutions

Write the function:

def count_words(string)

that returns the number of words in the given string. Words are sequences of characters

separated by spaces (assume that there is exactly one space between two consecutive

words).

For example, count_words("Mary had a little lamb") should return 5.

Extension : How could the function be modified to correctly handle strings where multiple

spaces appear between words?

06.1.2 Word counting

Write the function:

def count_vowels(string)

that returns the number of vowels in the given string. Vowels are the letters a, e, i, o, u,

including their uppercase versions.

06.1.1 Vowel counting

def count_words(string): counter = 0

for i in range(0, len(string), 1): if (string[i].isspace() and string[i-1].isalpha()) or i == len(string)-1: counter += 1

return counter

SSolution:olution:

EExplanationxplanation The program counts how many vowels are in a string. The count_vowels function goes through each character in the string and, if it is a vowel, it increments a counter. In the main function, the user enters a string and the program prints the number of vowels found.

def main(): StringEntered = input("Enter the string: ") print(f"Your string has {count_words(StringEntered)} words.")

main()

Write the functions:

def sphere_volume(r) def sphere_surface(r) def cylinder_volume(r, h) def cylinder_surface(r, h) def cone_volume(r, h) def cone_surface(r, h)

that compute the volume and surface area of: a sphere with radius r, a circular-based cylinder with radius r and height h, a circular-based cone with radius r and height h.

Then write a program that asks the user for the values of r and h, calls the six functions, and displays the results in the output.

06.1.3 Geometric Solids

def sphere_volume(r): volume = (43.14(r**3))/ return volume

def sphere_surface(r): surface = 43.14(r**2) return surface

def cylinder_volume(r, h): volume = (3.14(r2))h return volume

def cylinder_surface(r, h): surface = 23.14(r2) + 23.14r*h return surface

def cone_volume(r, h): volume = (3.14(r2)h)/ return volume

def cone_surface(r,h): apothem = (r2 + h2)**(1/2)

surface = (3.14r)(apothem + r) return surface

SSolution:olution:

EExplanationxplanation

The count_words function goes through each character and increments the counter whenever it finds a space after a letter or reaches the last character. In the main function, the user enters a string, and the program prints the number of words.

def assign_grant(Income, Children): Grant = 0 if Income > 30000 and Income <= 40000 and Children >= 3: Grant = Children* elif Income > 20000 and Income <= 30000 and Children >= 2: Grant = Children* elif Income <= 20000: Grant = Children*

return Grant

def main(): FamilyIncome = float(input("\nEnter the income: ")) NumberOfChildren = int(input("Enter the number of children in the family: ")) i = 1

while FamilyIncome != -1 and NumberOfChildren != -1:

print(f"Grant Family No. {i}: {assign_grant(FamilyIncome, NumberOfChildren)}") FamilyIncome = float(input("\nEnter the income: ")) NumberOfChildren = int(input("Enter the number of children in the family: ")) i += 1

main()

SSolution:olution:

A non-governmental organization needs a program to calculate the amount of financial aid to

assign to each family in need of assistance. The formula is as follows:

I. If a family’s annual income is between $30,000 and $40,000 and the family has at least 3 children,

the subsidy is $1,000 for each child.

II. If a family’s annual income is between $20,000 and $30,000 and the family has at least 2 children,

the subsidy is $1,500 for each child.

III. If a family’s annual income is less than $20,000, the subsidy is $2,000 for each child.

Write a function that performs these calculations. Then write a program that, in a loop, asks the user

to provide the annual income and the number of children for each family applying for aid, displaying

the corresponding value returned by the function. Use –1 as a sentinel value to terminate data entry.

06.2.1 ONG

EExplanationxplanation

The program calculates financial aid for families based on income and the number of

children. The assign_grant function determines the amount to give according to the given

rules. In the main function, the user enters income and number of children for each family,

and the program prints the corresponding grant until –1 is entered to stop. F-strings are

used here to print datas.

Write a program that converts a Roman numeral, like MCMLXXVIII, into its decimal representation. Hint : first, write a function that returns the numeric value of each single letter, then use the following algorithm:

total = 0 s = string representing the Roman numeral While s is not empty: If s has length 1, or the value of its first character is greater than or equal to the value of its

Add the value of the first character of s to total Remove the first character from s Else: difference = value of the second character of s - value of the first character of s Add difference to total Remove the first two characters from s

06.2.2 Roman numbers

second character

RomanLetters = 'IVXLCDM' CorrispondentValues = [1, 5, 10, 50, 100, 500, 1000]

def ValueRomLett(lett): Position = RomanLetters.find(lett) return CorrispondentValues[Position]

def ConvertToArabicNum(RomanNumber):

Total = 0 s = RomanNumber while len(s) != 0:

if len(s) == 1 or ValueRomLett(s[0]) >= ValueRomLett(s[1]): Total = Total + ValueRomLett(s[0]) s = s[1:]

else: Total = Total + ValueRomLett(s[1]) - ValueRomLett(s[0]) s = s[2:]

return Total

def main():

RomNum = input("Enter the Roman number: ") print(f"The value of the entered Roman number is: {ConvertToArabicNum(RomNum)}")

main()

SSolution:olution:

EExplanationxplanation I define two lists, which are related by their indexes. Then I define a function that returns the value of a Roman letter. Next, I define the main function that converts a Roman numeral into an Arabic number. I keep converting until the Roman numeral is fully processed. If there is only one letter or the value of the first letter is greater than or equal to the second, I add its value and remove the first character. If the value increases, I calculate the difference and add it to the total, then remove the first two characters. Finally, I define main and run it.

An electric wire is a cylindrical conductor covered by an insulating material. The resistance of a

wire is given by the formula:

where ρ is the resistivity of the conductor, and L, A, and d are the length, cross-sectional area,

and diameter of the wire, respectively.

The resistivity of copper is 1.678e-8 Ωm. The wire diameter d is commonly specified by the

American Wire Gauge (AWG), an integer n.

The diameter of an AWG nnn wire is given by:

Write a function

def diameter(wire_gauge)

that takes the wire gauge and returns its diameter.

Write another function

def copper_wire_resistance(length, wire_gauge)

that takes the length and gauge of a copper wire and returns its resistance.

The resistivity of aluminum is 2.82e-8 Ωm.

Write a third function

def aluminum_wire_resistance(length, wire_gauge)

that takes the length and gauge of an aluminum wire and returns its resistance.

Finally, write a program to test these functions.

06.2.4 Electric wire

p_copper = 1.678(10*(-8))

p_aluminum = 2.82(10*(-8))

def diameter(wire_gauge):

d = (0.127(92*((36-wire_gauge)/39)))/

return d

def copper_wire_resistance(length, wire_gauge):

r_copper = (4p_copperlength)/(3.14(diameter(wire_gauge)*2))

return r_copper

def aluminum_wire_resistance(length, wire_gauge):

r_aluminum = (4p_aluminumlength)/(3.14(diameter(wire_gauge)*2))

return r_aluminum

SSolution:olution:

def main(): awg = int(input("1) Enter an AWG value: "))

length_copper = float(input("\n2) Enter the length of the copper wire: ")) awg_copper = float(input("Enter the AWG value of the copper wire: "))

length_aluminum = float(input("\n3) Enter the length of the aluminum wire: ")) awg_aluminum = float(input("Enter the AWG value of the aluminum wire: "))

print(f'\n\n1) Diameter value: {diameter(awg)}') print(f'2) Copper Wire Resistance: {copper_wire_resistance(length_copper, awg_copper)}') print(f'3) Aluminum Wire Resistance: {aluminum_wire_resistance(length_aluminum, awg_aluminum)}')

main()

EExplanationxplanation The program computes the diameter of a wire from its AWG value and uses that diameter to calculate electrical resistance. One function returns the diameter based on the AWG formula, another computes copper resistance, and a third computes aluminum resistance. In the main function, the user enters lengths and gauges, and the program prints the corresponding diameter and resistance values.

Thank you Simone Altaserse