Python return语句包含括号

问题描述 投票:-1回答:2

我刚刚开始编码并清除了我的大部分基础知识,但我仍然有一个问题,理解'return'语句和python中的无类型变量。

def celtofar(x):
    far= (x*9/5) + 32
    if x<-273.15:
        return("The Value Of Celsius Entered is too low ")
    else:
        return ("Temperature in Fahrenheit Shall Be: ", far)
try :
    cel=int(input("Enter Temperature in celsius: "))
    print(celtofar(cel))
except ValueError :
    print("Please Enter an Integral Value")

我想要输出没有括号和引号,但终端给我以下结果:

PS C:\Users\welcome\Desktop\Work> python .\program1.py

Enter Temperature in celsius: 30
('Temperature in Fahrenheit Shall Be: ', 86.0)

我不希望包含括号和引号。

python
2个回答
1
投票

far转换为str并将其与结果连接:

def celtofar(x):
   far = (x * 9 / 5) + 32
   if x < -273.15:
      return "The Value Of Celsius Entered is too low"
   else:
      return "Temperature in Fahrenheit Shall Be: " + str(far)

try:
    cel = int(input("Enter Temperature in celsius: "))
    print(celtofar(cel))
except ValueError:
    print("Please Enter an Integral Value")

OUTPUT:

Enter Temperature in celsius: 30
Temperature in Fahrenheit Shall Be: 86.0

Process finished with exit code 0

编辑:

但是,我建议使用str.format()

def celtofar(x):
    far = (x * 9 / 5) + 32
    if x < -273.15:
        return "The Value Of Celsius Entered is too low"
    else:
        return "Temperature in Fahrenheit Shall Be: {}".format(far)


def main():
    try:
         cel = int(input("Enter Temperature in celsius: "))
         print(celtofar(cel))
    except ValueError:
         print("Please Enter an Integral Value")

if __name__ == "__main__":
     main()

0
投票

这是因为你的打印是一个元组。使用此示例格式化打印中的字符串

    return ("Temperature in Fahrenheit Shall Be: %s" %far)
© www.soinside.com 2019 - 2024. All rights reserved.