【问题标题】:External Code Sources Homework外部代码源作业
【发布时间】:2016-02-24 00:05:32
【问题描述】:

我一直在编写关于外部代码源的计算机科学作业,计算出有人猜一个问题需要多长时间。

但是当我运行它时,我收到了这个错误:

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.")

【问题讨论】:

  • time = end - start?

标签: python time while-loop return


【解决方案1】:

您在此处将顶部导入的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多