python - 如何在Python 3.5中选择小数点后的第一个数字?

标签 python python-3.x

我目前正在学习 Python(到目前为止很喜欢它)并且制作了一个小华氏/摄氏度转换器。

这是运行时的输出:

Please enter the degrees in Fahrenheit or Celsius to convert: 32

32.0 degrees Celsius is 89.6 degrees Fahrenheit.

32.0 degrees Fahrenheit is 0.0 degrees Celsius.

Do you want to calculate again? (y/n):

这就是我想要的,除非小数点后的尾随数字是 0(整数),否则我想完全删除 .0(即 5.0 到 5)。我猜我想要一个 if 语句来测试它是否等于零,但是我将如何选择该值?

完整代码:

answer = "ERROR"

def calcfc():
""" Calculates F to C and C to F, prints out,
    and asks if user wants to run again """
    try:
        degrees = float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: "))
    except Exception:
        input("\nEnter a valid number next time. Hit enter to terminate.")
        exit()

    ftoc = (degrees - 32) * 5 / 9
    ctof = (degrees * 9) / 5 + 32

    print("\n{} degrees Celsius is {:.1f} degrees Fahrenheit.".format(degrees, ctof))
    print("{} degrees Fahrenheit is {:.1f} degrees Celsius.".format(degrees, ftoc))
    global answer
    answer = input("\n\nDo you want to calculate again? (y/n): ")

calcfc()

# run again?
while answer != "y" and answer != "n":
    answer = input("\nPlease enter y for yes or n for no: ")
while answer == "y":
    calcfc()
if answer == "n":
    exit()

最佳答案

您必须将数字转换为字符串并测试它是否以 .0 结尾:

number = 23.04
text = "{:.1f}".format(number)
if text.endswith(".0"):
    text = text[:-2]

关于python - 如何在Python 3.5中选择小数点后的第一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43828998/

相关文章:

python-3.x - 如何让我的函数返回引用以外的内容?

python - 什么相当于 Python 中的 JavaScript promise.all()?

python-3.x - 在Python中获取维基百科的项目列表

python - 如何防止日志记录代码使实际代码困惑?

python - 包内模块的相对导入

python - 使用 PyObjC 以正常方式打印 python 异常

python-3.x - PyCharm : IDE does not seem to recognise Python 3 even with 3.x interpreter set

python - numpy arange 值意外改变符号

python - 在 python 中转置(旋转)列表字典

python - Matplotlib:将一组散点图数据带到前面