You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 math to access the precise, pre-defined value of π (math.pi).
  • The degree_to_radian and radian_to_degree functions stick exactly to your original conversion logic—no changes there.
  • The angle_converter wrapper function checks the in_type parameter 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 Radian
  • angle_converter(2.5, 'Radian') → Radian 2.5 is equal to 143.2394487827058 Degree
  • angle_converter(2.5, 'Float') → Not a valid type.

内容的提问来源于stack exchange,提问作者user9276239

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:38:05