【问题标题】:How do I concatenate a float or a interger? [duplicate]如何连接浮点数或整数? [复制]
【发布时间】:2020-09-07 18:34:30
【问题描述】:

我是一个非常初学者,只知道非常基本的语法。我正在尝试制作一个圆周计算器,用户输入半径。这就是我现在所拥有的,但我希望能够有一个文本答案,比如“这个圆的周长是____”。目前只能输出答案。

rad = input("Enter the radius of circle: ")
radius = float(rad)
circumference = 2 * 3.14 * radius
print(circumference)

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    Python 3

    使用f-string 格式化结果:

    rad = input("Enter the radius of circle: ")
    radius = float(rad)
    circumference = 2 * 3.14 * radius
    print(f'The circumference of this circle is {circumference}')
    

    Python 2

    Format string:

    rad = input("Enter the radius of circle: ")
    radius = float(rad)
    circumference = 2 * 3.14 * radius
    print('The circumference of this circle is {0}'.format(circumference))
    

    另一种选择:直接连接字符串

    不太优雅,但仍然有效:

    rad = input("Enter the radius of circle: ")
    radius = float(rad)
    circumference = 2 * 3.14 * radius
    print('The circumference of this circle is ' + str(circumference))
    

    【讨论】:

    • 或者你也可以只做"..." + str(circumference),但这肯定不会那么优雅。
    • 确实@flakes 谢谢:)
    【解决方案2】:

    你可以使用

    print(f"The circumference of this circle is {circumference}")
    

    但您也不想将 3.14 用于 pi。你可以这样做

    import math
    

    然后使用math.pi 获得更准确的数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-14
      • 2014-04-25
      • 2016-03-17
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多