社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

我的Python温度转换器不工作

Nineteenn • 4 年前 • 1651 次点击  

我试着做一个温度转换器,但由于某种原因它不能工作,这是我的代码

def getinput():
    print("Enter the temperature")
    a = float(input())
def Converter():
    print("Press 1 for Fahrenheit to Celsius\nPress 2 for Celsius to Fahrenheit")
    x = int(input())
    if x == 1:
       a = getinput()
       return (a - 32) * 5/9
    if x == 2:
        a = getinput()
        return (a + 32) * 9/5

Converter()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132340
文章 [ 1 ]  |  最新文章 4 年前
Patrick
Reply   •   1 楼
Patrick    4 年前

这里有两个问题,第一个是 getinput() 不返回导致错误的内容

TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

第二个问题是代码不打印结果,您可以从函数内部打印结果,也可以像这样调用函数调用的print

def getinput():
    print("Enter the temperature")
    a = float(input())
    return a
def Converter():
    print("Press 1 for Fahrenheit to Celsius\nPress 2 for Celsius to Fahrenheit")
    x = int(input())
    if x == 1:
       a = getinput()
       return (a - 32) * 5/9
    if x == 2:
        a = getinput()
        return (a + 32) * 9/5

print(Converter())

输出示例:

Press 1 for Fahrenheit to Celsius
Press 2 for Celsius to Fahrenheit

1
Enter the temperature

23
-5.0

作为一个需要注意的小问题 input() 将消息作为参数

def getinput():
    return float(input("Enter the temperature: "))
def Converter():
    x = int(input("Press 1 for Fahrenheit to Celsius\nPress 2 for Celsius to Fahrenheit\n"))
    if x == 1:
       a = getinput()
       return (a - 32) * 5/9
    if x == 2:
        a = getinput()
        return (a + 32) * 9/5

print(Converter())

现在 getinput() 这是相当多余的

def Converter():
    x = int(input("Press 1 for Fahrenheit to Celsius\nPress 2 for Celsius to Fahrenheit\n"))
    if x == 1:
       a = float(input("Enter the temperature: "))
       return (a - 32) * 5/9
    if x == 2:
        a = float(input("Enter the temperature: "))
        return (a + 32) * 9/5

print(Converter())