外部代码来源作业

时间:2015-11-21 14:50:01

标签: python time while-loop return

我一直在编写关于外部代码源的计算机科学作业,这需要人们猜错一段时间。

然而,当我运行它时,我收到此错误:

Traceback (most recent call last):
  File "E:/Documents/Guess band member.py", line 14, in <module>
    start = time.time()
AttributeError: 'float' object has no attribute 'time'

如果有人能帮我解决这个问题,我将非常感激。

import time
print("You can type 'quit' to exit")
Exit = False

Band = ["harry", "niall", "liam", "louis" ]

while Exit == False:
    print("Guess a band member")
    start = time.time()
    Guess = input(":")
    end = time.time()
    Guess = Guess.lower()
    if Guess == 'quit':
        Exit = True
    elif Guess in Band:
        print("You're right")
    elif Guess == "zayn":
        print("Wrong")
        print("He left.")
    else:
        print("Fool!")
    time = end - start
    print("You took", time, "seconds to guess.")

1 个答案:

答案 0 :(得分:3)

您在此处使用浮点值替换了您在顶部导入的time模块:

time = end - start

while循环的下一次迭代中,time现在是float对象,而不是模块对象,因此time.time()调用失败。

将该变量重命名为不会发生冲突的内容:

elapsed_time = end - start
print("You took", elapsed_time, "seconds to guess.")

作为旁注,您不需要使用哨兵变量(Exit);只需使用while True:并使用break语句退出循环:

while True:
    # ...

    if Guess == 'quit':
        break

    # ...

在其他情况下,您使用while not Exit:而非测试== False