python 3 - math.sqrt - 需要一个浮点数

时间:2016-04-13 19:10:39

标签: python python-3.x

我试图使用平方根作为计数循环的计数,但我一直得到错误"需要浮点数。"我已经尝试了各种方法,我可以想到将math.sqrt提供的值转换为float,但我仍然收到消息。

代码:

from random import randrange
import math


def getInfo():

    tilesNum = float(input("Please enter number of tiles now: "))



def procedure(tilesNum):

    countX = 0

    SqRoot = float(math.sqrt(tilesNum))

    print(SqRoot)

    for i in range(float(SqRoot)):

        countX = countX + 1
        countY = 0


        for i in range(float(SqRoot)):
            countY = countY + 1
            terrain = randrange(1, 5)

            if terrain == 1:
                print("terrain on tile", countX, countY, "is frozen")

            elif terrain == 2:
                print("terrain on tile", countX, countY, "is flooded")

            elif terrain == 3:
                print("terrain on tile", countX, countY, "is impeded by   rocks")

            else:
                print("terrain on tile", countX, countY, "is overgrown")




def main():

    tilesNum = getInfo()

    procedure(tilesNum)

main()

错误:

Traceback (most recent call last):
  File "C:\Users\Rainy\AppData\Local\Programs\Python\Python35\PBA prototype (problem).py", line 50, in <module>
    main()
  File "C:\Users\Rainy\AppData\Local\Programs\Python\Python35\PBA prototype (problem).py", line 48, in main
    procedure(tilesNum)
  File "C:\Users\Rainy\AppData\Local\Programs\Python\Python35\PBA prototype (problem).py", line 15, in procedure
    SqRoot = float(math.sqrt(tilesNum))
TypeError: a float is required

非常感谢任何帮助!

  • 下雨天

1 个答案:

答案 0 :(得分:4)

您缺少return声明。试试这个:

def getInfo():
    tilesNum = float(input("Please enter number of tiles now: "))
    return tilesNum

由于您的getInfo()没有明确的return语句,因此它会隐式返回None。然后,您的main()会将None传递给procedure()。在procedure()内,您将None传递到math.sqrt()math.sqrt()抱怨TypeError