外部代码源

2024-05-21 18:09:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在写关于外部代码源的计算机科学作业,这是人们猜测一个问题所需时间的倍数

但是,当我运行它时,我收到以下错误:

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

Tags: toinyoufalsebandtimeexitstart
1条回答
网友
1楼 · 发布于 2024-05-21 18:09:12

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

time = end - start

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

将该变量重命名为不冲突的变量:

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

作为补充说明,您不需要使用sentinel变量(Exit);只需使用while True:并使用break语句退出循环:

while True:
    # ...

    if Guess == 'quit':
        break

    # ...

在其他情况下,您应该使用while not Exit:,而不是测试== False

相关问题 更多 >