Skip to content

Temperature Converter

入门 约 10 分钟

你将构建什么

Python script 使用 celsius_to_fahrenheit and fahrenheit_to_celsius 函数, and 小 CLI 那个 asks 用户 for 值 and prints 两者都 conversions.

学习目标

  • 定义函数使用参数 and 返回值
  • Apply temperature conversion formulas 正确地
  • 格式输出使用 f-字符串
  • 读取 and convert 用户输入

前置要求

  • 函数 and 返回值
  • 基础 arithmetic
  • 输入() and float()

步骤

  1. 1

    编写 conversion 函数

    定义 celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f). formulas 是 F = C * 9/5 + 32 and C = (F - 32) * 5/9. 每个函数 takes one 数字 and 返回 one 数字.

    代码
    def celsius_to_fahrenheit(c):
        return c * 9 / 5 + 32
    
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5 / 9

    预期结果

    celsius_to_fahrenheit(0) 返回 32.0; fahrenheit_to_celsius(98.6) 返回关于 37.0.

  2. 2

    读取输入从 用户

    Ask 用户 for temperature in Celsius and convert 输入字符串到 float. float() handles decimal 输入如 36.6.

    代码
    c = float(input("Enter temperature in Celsius: "))

    预期结果

    script waits for 输入 and 存储 numeric 值 in c.

  3. 3

    Print result 使用 f-字符串

    Call conversion 函数 and print result using f-字符串. f-字符串 let 你 embed 表达式 directly 内部字符串使用 curly braces.

    代码
    f = celsius_to_fahrenheit(c)
    print(f"{c}°C = {f}°F")

    预期结果

    输入 25 prints "25.0°C = 77.0°F".

  4. 4

    添加输入验证与异常处理

    在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。

    代码
    def safe_input(prompt, validator=None):
        """Read input with validation and error handling."""
        while True:
            try:
                raw = input(prompt)
                value = float(raw)
                if validator and not validator(value):
                    raise ValueError(f"Value {value} failed validation")
                return value
            except ValueError as err:
                print(f"Invalid input: {err}. Please try again.")
    
    # Usage
    age = safe_input("Enter your age: ", lambda x: x > 0)

    预期结果

    非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。

  5. 5

    编写单元测试

    使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。

    代码
    import unittest
    
    class TestCoreFunc(unittest.TestCase):
        def test_normal(self):
            self.assertEqual(core_func(5), expected_5)
    
        def test_boundary(self):
            self.assertEqual(core_func(0), expected_0)
    
        def test_exception(self):
            with self.assertRaises(ValueError):
                core_func(-1)
    
    if __name__ == "__main__":
        unittest.main()

    预期结果

    运行 python test.py 后输出 OK,三个测试用例全部通过。

自己动手试试

你学到了什么

你 wrote pure 函数那个 encode formula and wired 它们到 command-行接口使用输入 and f-字符串 — 构建块 的大多数小 Python utilities.

相关资源

相关课程

  • 函数

    函数定义, 参数, and 返回 used 这里.

  • 字符串

    f-字符串格式化 used 到 display result.

相关练习

相关工具

相关速查表

相关参考文档

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题