如何在Python中用if语句实现弧度与角度互转的角度转换器?
Angle Converter Program in Python
Let's put together this angle converter properly—first, we need to fix the missing import for π (since your original functions reference pi but don't pull it from the math module, which would cause an error otherwise). Here's the complete, working implementation:
Full Code
import math def degree_to_radian(in_degree): angles_in_radian = (in_degree * math.pi) / 180 return angles_in_radian def radian_to_degree(in_radian): angles_in_degree = in_radian * 180 / math.pi return angles_in_degree def angle_converter(in_num, in_type): # Check input type and route to the right conversion function if in_type == 'Degree': converted_val = degree_to_radian(in_num) return f"Degree {in_num} is equal to {converted_val} Radian" elif in_type == 'Radian': converted_val = radian_to_degree(in_num) return f"Radian {in_num} is equal to {converted_val} Degree" # Handle invalid input types with a clear message else: return "Not a valid type."
How It Works
- We start by importing
mathto access the precise, pre-defined value of π (math.pi). - The
degree_to_radianandradian_to_degreefunctions stick exactly to your original conversion logic—no changes there. - The
angle_converterwrapper function checks thein_typeparameter to decide which conversion to run, then returns a neatly formatted string with the result. If the input type isn't 'Degree' or 'Radian', it returns an error message as specified.
Test Examples
Run these calls to confirm the output matches your requirements:
angle_converter(2.5, 'Degree')→Degree 2.5 is equal to 0.04363323129985824 Radianangle_converter(2.5, 'Radian')→Radian 2.5 is equal to 143.2394487827058 Degreeangle_converter(2.5, 'Float')→Not a valid type.
内容的提问来源于stack exchange,提问作者user9276239
相关产品推荐
相关产品推荐

