我目前正在学习 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/