如何检查浮动

时间:2017-08-31 17:12:06

标签: python python-3.x loops

我正在尝试创建一个嵌套循环来检查用户的输入是应该是整数还是浮点数。 在我的计算器中,每个化合物的速率存储在基于文本输入的整数中,但是我想添加else语句的功能以检查输入是整数还是小数。如果它是一个整数,我希望文本产生没有.0的数字,但是如果它是一个浮点数,比如6.5,我想把这个变量保存为浮点数。

rerun = True

while (rerun):
    print ("Welcome to the interest calculator")
    balance = input ("\nPlease enter your account balance: ")
    interest = input ("\nWhat is the interest rate on the account? (decimal): ")
    rate = input ("\nWhat is the rate that interest is applied? "
                  "\n(Monthly, Quarterly, Annually, Biannually): ")
    balance = float(balance)
    interest = float(interest)
#Convert text to rate variable

    if (rate == "Monthly" or rate == "monthly"):
        compounds = 12
    elif (rate == "Quarterly" or rate == "quarterly"):
        compounds = 4
    elif (rate == "Annually" or rate == "annually"):
        compounds = 1
    elif (rate == "Biannually" or rate == "biannually"):
        compounds = 2

这是我认为检查应该

的地方
    else:
        compounds = float(rate)
#Display Data
    print ('interest = ',  type(interest))
    print ('balance = ',  type(balance))
    print ('compounds = ', type(compounds))

    if (compounds == 1):
        print ("\nYour account has a balance of $" + str(balance), "dollars with an interest rate \n"
               "of ", str(interest) + "%", " being applied", str(compounds), "time per year")
    else:
        print ("\nYour account has a balance of $" + str(balance), "dollars with an interest rate \n"
               "of ", str(interest) + "%", " being applied", str(compounds), "times per year")

    total = interest * balance * compounds

    if (total < 1):
        print ("Calculated total = $" + "{:.2f}".format(total) + " cents")
    else:
        print ("Calculated total = $" + "{:.2f}".format(total) + " dollars")
    #while loop to rerun program

    answer = input ("\nType (y) to rerun the program: ")
    if (answer == "y" or "Y"):
        rerun = True
        print ("\n")
    else:
        rerun = False

因此,如果用户输入1作为费率,这将落入else语句,因为它不是我预定义的单词之一,&#34;您的帐户余额......&#34;应该将化合物显示为int。 如果用户输入1.5作为费率,这将落在else语句中,因为它不是我预定义的单词之一,&#34;您的帐户余额.......&#34;应将化合物显示为浮点数。

任何人都可以就如何处理此问题向我提供一些意见吗?我尝试使用余数写出来,减去并添加数字以检查化合物是否>而不是一个整数,但我似乎无法正确写。

1 个答案:

答案 0 :(得分:2)

最初只使用float,然后检查是否is_integer并进行相应处理:

>>> f = float(input())
3
>>> f
3.0
>>> f.is_integer()
True

甚至更好,请使用g format specifier

>>> f = 1.000
>>> f
1.0
>>> print("{:g}".format(f))
1
>>> f = 3.14
>>> print("{:g}".format(f))
3.14
  

一般格式。对于给定的精度p> = 1,这将对该数字进行舍入   p有效数字然后格式化结果   定点格式或科学记数法,取决于它   大小

     

准确的规则如下:假设结果格式化   使用表示类型“e”和精度p-1将具有指数exp。   然后,如果-4&lt; = exp&lt; p,使用演示文稿类型格式化数字   'f'和精度p-1-exp。否则,数字格式化为   演示类型'e'和精度p-1。 在这两种情况下都是微不足道的   从有效数字和小数点中删除尾随零   如果其后没有剩余数字,也会被删除。