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

De WikiCabal
Saltar a: navegación, buscar

CrearFunción-5.py

#!/usr/bin/python3
#-*-coding: utf-8 -*-
# convertir temperatura en Fahrenheit a Celsius
 
def print_options( ):
  print( "Options:" )
  print( " 'p' print options" )
  print( " 'c' convert from Celsius" )
  print( " 'f' convert from Fahrenheit" )
  print( " 'q' quit the program" )
 
def celsius_to_fahrenheit( c_temp ):
  return 9.0 / 5.0 * c_temp + 32
 
def fahrenheit_to_celsius( f_temp ):
  return ( f_temp - 32.0 ) * 5.0 / 9.0
 
choice = "p"
while choice != "q":
  if choice == "c":
    c_temp = float( input( "Celsius temperature: " ) )
    print( "Fahrenheit:", celsius_to_fahrenheit( c_temp ) )
    choice = input( "option: " )
  elif choice == "f":
    f_temp = float( input( "Fahrenheit temperature: " ) )
    print( "Celsius:", fahrenheit_to_celsius( f_temp ) )
    choice = input( "option: " )
  elif choice == "p": #Alternatively choice != "q": so that print when anything unexpected inputed
     print_options( )
     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