21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Respostas dos exercícios I 329

Respostas dos exercícios I

1. Implementar duas funções:

▪ Uma que converta temperatura em graus Celsius para Fahrenheit.

▪ Outra que converta temperatura em graus Fahrenheit para Celsius.

Lembrando que:

F = 9 ⋅C 32

5

Solução:

def celsius_fahrenheit(c=0):

# round(n, d) => arredonda n em d casas decimais

return round(9. * c / 5. + 32., 2)

def fahrenheit_celsius(f=0):

return round(5. * (f - 32.) / 9., 2)

# Testes

print celsius_fahrenheit(123.0)

print fahrenheit_celsius(253.4)

2. Implementar uma função que retorne verdadeiro se o número for primo

(falso caso contrário). Testar de 1 a 100.

Solução:

# -*- coding: latin1 -*-

# Testa se o número é primo

def is_prime(n):

if n < 2:

return False

for i in range(2, n):

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!