我现在正在学习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
结尾,则必须将其转换为字符串并进行测试:数字的小数部分如下:
Thispost探讨了一个类似的问题。在
输出
^{pr2}$相关问题 更多 >
编程相关推荐