如何在导入的Python温度转换脚本中传入输入值并执行转换
温度转换交互脚本实现方案
首先需要将已有的c2f.py、f2c.py中的转换逻辑封装为可调用函数,避免导入模块时直接执行原有脚本的运行逻辑:
1 调整现有转换脚本结构
c2f.py参考代码(摄氏转华氏)
def celsius_to_fahrenheit(celsius): # 此处替换为你原有转换逻辑即可 return celsius * 9 / 5 + 32 # 保留单独运行脚本的能力,导入时不会执行下方代码 if __name__ == "__main__": input_temp = int(input("请输入摄氏温度:")) print(f"转换后华氏温度为:{celsius_to_fahrenheit(input_temp)}")
f2c.py参考代码(华氏转摄氏)
def fahrenheit_to_celsius(fahrenheit): # 此处替换为你原有转换逻辑即可 return (fahrenheit - 32) * 5 / 9 # 保留单独运行脚本的能力,导入时不会执行下方代码 if __name__ == "__main__": input_temp = int(input("请输入华氏温度:")) print(f"转换后摄氏温度为:{fahrenheit_to_celsius(input_temp)}")
2 编写tempconversion.py交互逻辑
# 获取用户输入的待转换温度 input_temp = int(input("请输入待转换的整数温度值:")) # 询问转换方向 print("请选择转换方向:") print("1 - 摄氏温度转华氏温度") print("2 - 华氏温度转摄氏温度") choice = input("请输入选项编号:") # 按选择导入对应模块执行转换 if choice == "1": from c2f import celsius_to_fahrenheit res = celsius_to_fahrenheit(input_temp) print(f"转换结果:{input_temp}℃ = {res}℉") elif choice == "2": from f2c import fahrenheit_to_celsius res = fahrenheit_to_celsius(input_temp) print(f"转换结果:{input_temp}℉ = {res}℃") else: print("输入选项无效,请重新运行程序输入1或2")
3 注意事项
- 三个脚本需要放在同一个文件夹下运行,否则需要额外配置Python模块搜索路径才能正常导入
- 导入的函数名需要和
c2f.py、f2c.py中定义的函数名完全一致,避免出现导入报错 - 若需要支持小数温度输入,可将代码中的
int()修改为float()
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

