我如何根据Python中的输入输出整数和浮点数?

时间:2016-04-17 02:31:17

标签: python python-3.x

我是Python 3的初学者。我试图将输出打印为整数或浮点数,具体取决于使用的类型。我怎么能够格式化代码,这样如果他们输入3作为半径输出“3”,如果他们输入3.5,它会输出半径为“3.5”?有什么建议吗?

print("Do you want to find the area of a circle? ")
again=input("Enter 'y' for yes, or enter 'n' to exit the program: ")

while (again=='y'):
    pi = 3.14
    radius = raw_input(" Input the radius of the circle: ")

    area = pi * radius * radius
    print("A circle with a radius of " + str(float(radius)) + " has an area of " +  "{0:.2f}".format(area))
    print()
    print("Would you like to run another? ")
    again = input("Enter 'y' to run another, enter 'n' to exit: ")

print("Have a nice day :) ")

2 个答案:

答案 0 :(得分:0)

用于调试或只是知道您可以使用的值的类型

print(type(some_var))

是否要在if语句中使用isinstance函数

if isinstance(radius, int):
   print("int")
if isinstance(radius, float):
    print("float")

这里有更多信息 Differences between isinstance() and type() in python

答案 1 :(得分:0)

首先,一些事情:

"输入"之间的区别和" raw_input"是输入将返回一个数字值而raw_input将返回一个字符串值。如果您打算在数值运算中使用raw_input,则必须将其转换为int或float。同样,如果您希望用户输入单词或短语,则必须使用raw_input。

其次,print function将输出自动放在新行上。如果您想在输出中添加另一个新行,请使用' \ n'在你的字符串中。

最后,将半径转换为浮点数确保它将作为浮点打印出来。如果你在将它转换为字符串之前没有将它转换为浮点数,python将为你做格式化。

下面我拿了你的代码,注释掉了有缺陷的部分,并将我的修补程序直接放在它们下面:

print("Do you want to find the area of a circle? ")

# again = input("Enter 'y' for yes, or enter 'n' to exit the program: ")
again = raw_input("Enter 'y' for yes, or enter 'n' to exit the program: ")

while (again == 'y'):

    pi = 3.14

    # radius = raw_input(" Input the radius of the circle: ")
    radius = input("Input the radius of the circle: ")

    area = pi * radius * radius

    # print("A circle with a radius of " + str(float(radius)) + " has an area of " +  "{0:.2f}".format(area))
    print("A circle with a radius of " + str(radius) + " has an area of " +  "{0:.2f}".format(area))

    # print()
    # print("Would you like to run another? ")

    print("Would you like to run another? ")

    # again = input("Enter 'y' to run another, enter 'n' to exit: ")
    again = raw_input("Enter 'y' to run another, enter 'n' to exit: ")

print("Have a nice day :) ")

希望这有帮助!

使用它代替python 3:

print("Do you want to find the area of a circle?")
again = input("Enter 'y' for yes, or enter 'n' to exit the program: ")

while (again == 'y'):

    pi = 3.14

    radius = input("Input the radius of the circle: ")
    area = pi * (float(radius) ** 2)

    print("A circle with a radius of " + str(radius) + " has an area of " + "{0:.2f}".format(area))

    print("Would you like to run another?")
    again = input("Enter 'y' to run another, enter 'n' to exit: ")

print("Have a nice day :)")