Answer to Question #240285 in Python for Pavani

Question #240285

You are given the temperature T of an object in one of Celsius, Fahrenheit, and Kelvin scales.

Write a program to print T in all scales viz Celsius, Fahrenheit, and Kelvin.

Formula to convert from Fahrenheit F to Celsius C is C = (F - 32) * 5 / 9.

Formula to convert from Kelvin K to Celsius C is C = K - 273.

Here "C", "F", "K" represent that the temperature scale is in Celsius, Fahrenheit and Kelvin scales respectively.

The input contains the temperature (a number) and the unit of the temperature scale (C, F, K) without any space.

The output contains temperature in Celsius, Fahrenheit and Kelvin scales in each line in the format similar to input and the value of the temperature is rounded to 2 decimal places.


1
Expert's answer
2021-09-22T00:01:47-0400
import re

while True:
   input_message = """Enter a temperature in 
Celsius (e.g., 23C, +5.0C, -5C, 45.C),
Fahrenheit (e.g., 148.78F, -14F, +4F, -67.F)
or Kelvin (e.g, 0.7K, 123K, +27K, 456.K, here all numbers must be positive) units,
'Q' or 'q' to quit: """
   temperature = input(input_message)
   mo = re.match(r'\A([+-]{0,1}\d+\.?\d*[CF]{1})\Z|\A(\+{0,1}\d+.?\d*K{1})\Z|\A([Qq]{1})\Z', temperature)
   # mo - match object
   if mo:
       print(mo.groups())
       if temperature[-1] == 'C':
           tempC = float(temperature[:-1])
           if tempC < -273.0:
               print(f"Warning: Wrong temperature! {tempC}C is below of 'absolute zero' (-273C = -459.4F = 0K). Try again.\n")
               continue
           tempF = tempC * 9/5 + 32
           tempK = tempC + 273
       elif temperature[-1] == 'F':
           tempF = float(temperature[:-1])
           if tempF < -459.4:
               print(f"Warning: Wrong temperature! {tempF}F is below of 'absolute zero' (273C = -459.4F = 0K). Try again.\n")
               continue
           tempC = (tempF - 32) * 5 / 9.
           tempK = tempC + 273
       elif temperature[-1] == 'K':
           tempK = float(temperature[:-1])
           tempC = tempK - 273
           tempF = tempC * 9/5 + 32
       elif temperature in ('Q', 'q'):
           break
       print(f'{tempC:.2f}C\n{tempF:.2f}F\n{tempK:.2f}K\n')

   else:
       print("Error: Wrong input format! Try again.\n")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS