Python return语句包括方括号

时间:2019-04-03 08:18:30

标签: python

我刚刚开始编码并且已经清除了大部分基础知识,但是在理解python中的“ return”语句和None类型变量时仍然遇到问题。

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)

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

2 个答案:

答案 0 :(得分: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")

输出

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()

答案 1 :(得分:0)

这是因为您的打印是元组。使用此示例在打印文件中设置字符串格式

    return ("Temperature in Fahrenheit Shall Be: %s" %far)