Curso de Programación en Python/CrearFunción-5

De WikiCabal
Ir a la navegación Ir a la búsqueda

CrearFunción-5.py

 1 #!/usr/bin/python3
 2 #-*-coding: utf-8 -*-
 3 # convertir temperatura en Fahrenheit a Celsius
 4  
 5 def print_options( ):
 6   print( "Options:" )
 7   print( " 'p' print options" )
 8   print( " 'c' convert from Celsius" )
 9   print( " 'f' convert from Fahrenheit" )
10   print( " 'q' quit the program" )
11  
12 def celsius_to_fahrenheit( c_temp ):
13   return 9.0 / 5.0 * c_temp + 32
14  
15 def fahrenheit_to_celsius( f_temp ):
16   return ( f_temp - 32.0 ) * 5.0 / 9.0
17  
18 choice = "p"
19 while choice != "q":
20   if choice == "c":
21     c_temp = float( input( "Celsius temperature: " ) )
22     print( "Fahrenheit:", celsius_to_fahrenheit( c_temp ) )
23     choice = input( "option: " )
24   elif choice == "f":
25     f_temp = float( input( "Fahrenheit temperature: " ) )
26     print( "Celsius:", fahrenheit_to_celsius( f_temp ) )
27     choice = input( "option: " )
28   elif choice == "p": #Alternatively choice != "q": so that print when anything unexpected inputed
29      print_options( )
30      choice = input( "option: " )

Resultado

Options:

'p' print options
'c' convert from celsius
'f' convert from fahrenheit
'q' quit the program
option: c
Celsius temperature: 30
Fahrenheit: 86.0
option: f
Fahrenheit temperature: 60
Celsius: 15.5555555556
option: q

Explicación