1ano/fp/aula04: tp04 codecheck exercises added

1ano/fp/aula03/ex12.py: comment added
This commit is contained in:
tiagorg 2022-10-19 09:47:23 +01:00
parent 4170198f85
commit 08fb059994
4 changed files with 85 additions and 0 deletions

View File

@ -3,6 +3,9 @@ def main():
for n in countdown(num): for n in countdown(num):
print(n) print(n)
# Creates a range() function with the format range(n:0:-1)
# The statement yield returns a value every repetition
def countdown(n): def countdown(n):
while n > 0: while n > 0:
yield n yield n

View File

@ -0,0 +1,40 @@
# Example: finding and counting leap years
# JMR 2019
def isLeapYear(year):
return year%4 == 0 and year%100 != 0 or year%400 == 0
def printLeapYears(year1, year2):
"""Print all leap years in range [year1, year2[."""
for year in listLeapYears(year1, year2):
print(year)
def numLeapYears(year1, year2):
"""Return the number of leap years in range [year1, year2[."""
return len(listLeapYears(year1, year2))
def listLeapYears(year1, year2):
"""Return a list of leap years in range [year1, year2[."""
# (We'll get back to lists later in the course.)
lst = []
for year in range(year1, year2):
if isLeapYear(year):
lst.append(year)
return lst
# MAIN PROGRAM:
def main():
printLeapYears(1870, 1921)
x = numLeapYears(1679, 2079)
print("In [1679, 2079[ there are", x, "leap years")
print(listLeapYears(1970, 2002))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,19 @@
# Read numbers until a sentinel (an empty string), and return their sum.
# JMR 2018
def inputTotal():
"""Read numbers until empty string is entered and return the sum."""
tot = 0.0
while True:
n = input("valor? ") # input("valor? ")
if n == '': return tot
tot += float(n)
# MAIN PROGRAM
def main():
tot = inputTotal()
print(tot)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,23 @@
# Example: Print a multiplication table
# Like:
# 1 x 1 = 1
# 1 x 2 = 2
# ...
# 10 x 10 = 100
#
# Make the program print an empty line after each group of ten.
# Also, use format specifiers to align the numbers.
#
# JMR 2019
def main():
for i in range (1, 11):
table(i)
print()
def table(n):
for i in range(1, 11):
print(f'{n} x {i} = {n*i}')
if __name__ == "__main__":
main()