Python - IndexError:元组索引超出范围

2024-01-14

我正在尝试创建一个程序来随机生成 GCSE 修订主题中的每个问题。我的代码在随机问题后生成错误消息。这是我的代码,后面是错误消息:

computing_UNIT4_networks = (["LOCAL AREA NETWORK","A network in one geographical area."],["WIDE AREA NETWORK","A network spanning two or more geographical areas."],["ROUTER","Connects a network to another network, sends and inspects packets of data."],["SWITCH","Channels data to its indented destination, within an internal network."],["NETWORK INTERFACE CARD","A card that allows a computer to connect to the network."],["FIBRE OPTIC CABLE","Uses light to transmit data."],["ETHERNET CABLE","Uses metal wires (usually copper) to transmit data."],["DNS","Used to match IP addresses to URL."],["HOSTING","Storing data for a user, usually a website."],["CLOUD COMPUTING","A remote computer is used to store data and provide services."])
computing_UNIT5_protocols = (["STAR NETWORK","All computers are connected 'individually' to the server.(using switches)"],["FULL MESH NETWORK","Every computer is connected to every other."],["ENCRYPTION","Disguising data so that it can be read with the key."],["DATA PACKET","Small unit of data to be transmitted."],["LATENCY","The delay in receiving data."],["BANDWIDTH","The amount of data that can be transmitted in a set amount of time."],["PACKET SWITCHING","Packets of data are transmitted and are able to take individual routes to their destination."],["CIRCUIT SWITCHING","Packets of data are transmitted along the same route to their destination."])
done = []
def computing():
    unit = int(input("Which UNIT are you revising?\n-"))
    if unit == 4:
        UNIT = computing_UNIT4_networks
        print("Here are",len(UNIT),"questions on UNIT4 - Wired and wireless networks.")
    elif unit == 5:
        UNIT = computing_UNIT5_protocols
        print("Here are",len(UNIT),"questions on UNIT5 - Network topologies, protocols and layers.")
    i=1
    c=0
    while i <= (len(UNIT)):
        import random
        randint=random.randint(0,len(UNIT))
        while randint in done:
            randint=random.randint(0,len(UNIT))
            if randint in done:
                i=i
            else: break
        question = UNIT[randint][1]
        answer = UNIT[randint][0]
        print("\nWhat is this the definition of?:",question)
        b=input("-").upper()
        if b == answer:
            c=c+1
            print("\nCorrect\nCurrent score:",c,"/",i)
        else: print("\nWrong. The answer was",answer,".\nCurrent score:",c,"/",i)
        done.append(randint)
        i = i+1
    print("\nYou scored",c,"/",len(UNIT),".")

computing()

错误信息:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    computing()
  File "[FILELOCATION]", line 22, in computing
    question = UNIT[randint][1]
IndexError: tuple index out of range

randint 应该来自0 to len(UNIT)-1。该值可能随机达到len(UNIT)并且该索引超出范围。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python - IndexError:元组索引超出范围 的相关文章

  • 如何使用 cython 编译扩展?

    我正在尝试从示例页面编译一个简单的 cython 扩展here http docs cython org src userguide tutorial html在我安装了 Python 2 6 64 位版本的 Windows 7 64 位计
  • Django:如何测试“HttpResponsePermanentRedirect”

    我正在为我的 django 应用程序编写一些测试 在我看来 它使用 HttpResponseRedirect 重定向到其他一些网址 那么我该如何测试呢 姜戈TestCase类有一个方法assertRedirects https docs d
  • 从正在运行的 python 脚本检测优化标志是否为 -O 或 -OO

    有时我想生成一个子进程 其优化标志与启动父进程时使用的优 化标志相同 我可以使用类似的东西 optimize not debug 但这样我就可以匹配两者 O and OO flags 是否有一些 python 内部状态包含该信息 经过一番深
  • 为什么 .setGeometry() 不改变 QWidget 实例的大小?

    我想使用 QWidget 更改 QPushButton 的大小 setGeometry https doc qt io qtforpython 5 PySide2 QtWidgets QWidget html PySide2 QtWidge
  • 在python中将文本文件解析为列表

    我对 Python 完全陌生 我正在尝试读取包含单词和数字组合的 txt 文件 我可以很好地读取 txt 文件 但我正在努力将字符串转换为我可以使用的格式 import matplotlib pyplot as plt import num
  • Python BeautifulSoup XML 解析

    我编写了一个简单的脚本来使用 BeautifulSoup 模块解析 XML 聊天日志 标准 soup prettify 工作正常 只是聊天日志中有很多绒毛 您可以在下面看到我正在使用的脚本代码和一些 XML 输入文件 Code import
  • PIL Image.size 返回相反的宽度/高度

    使用PIL确定图像的宽度和高度 在特定图像上 幸运的是只有这一个 但这很麻烦 从 image size 返回的宽度 高度是相反的 图片 http storage googleapis com cookila 533ebf752b9d1f7c
  • sudo pip install python-Levenshtein 失败,错误代码 1

    我正在尝试在 Linux 上安装 python Levenshtein 库 但每当我尝试通过以下方式安装它时 sudo pip install python Levenshtein 我收到此错误 命令 usr bin python c 导入
  • 无法打开 Python。错误 0xc000007b

    我最近一直在学习 Python 3 我在我的上网本 32 位 Windows 7 上创建简单的小程序没有任何问题 当我将它安装在我的上网本上时 我没有遇到任何问题 但现在我已经开始使用它了 我想将它安装在我的台式机上 并且我有一个 我的桌面
  • 将输入发送到 python 子进程而不等待结果

    我正在尝试为一段代码编写一些基本测试 该代码通常通过 stdin 无休止地接受输入 直到给出特定的退出命令 我想检查程序是否在给出一些输入字符串时崩溃 经过一段时间来考虑处理 但似乎无法弄清楚如何发送数据而不是陷入等待我不知道的输出关心 我
  • 在 MacO 和 Linux 上安装 win32com [重复]

    这个问题在这里已经有答案了 我的问题很简单 我可以安装吗win32com蟒蛇API pywin32特别是 在非 Windows 操作系统上 我一直在Mac上尝试多个版本pip install pywin32 都失败了 下面是一个例子 如果你
  • Airflow Python 单元测试?

    我想为我们的 DAG 添加一些单元测试 但找不到任何单元测试 有 DAG 单元测试框架吗 有一个端到端的测试框架存在 但我猜它已经死了 https issues apache org jira browse AIRFLOW 79 https
  • 如何在与应用程序初始化文件不同的文件中迭代 api 路由

    我有一个 apiroutes py 文件 其中定义了许多路由 例如 api route api read methods GET api route api write methods POST 其中 api 是导入 from import
  • 如何通过字符串匹配加速 pandas 行过滤?

    我经常需要过滤 pandas 数据框df by df df col name string value 并且我想加快行选择操作 有没有快速的方法可以做到这一点 例如 In 1 df mul df 3000 2000 3 reset inde
  • 为什么实现 __iter__ 的对象不被识别为可迭代的?

    假设您使用包装对象 class IterOrNotIter def init self self f open tmp toto txt def getattr self item try return self getattribute
  • Python 3.2 中 **kwargs 和 dict 有什么区别?

    看起来Python的很多方面都只是功能的重复 除了我在 Python 中的 kwargs 和 dict 中看到的冗余之外 还有什么区别吗 参数解包存在差异 许多人使用kwargs 并通过dict作为论据之一 使用参数解包 Prepare f
  • 全局变量是 None 而不是实例 - Python

    我正在处理Python 中的全局变量 代码应该可以正常工作 但是有一个问题 我必须使用全局变量作为类的实例Back 当我运行应用程序时 它说 back is None 这应该不是真的 因为第二行setup 功能 back Back Back
  • 如何禁止 celery 中的 pickle 序列化

    Celery 默认使用 pickle 作为任务的序列化方法 如中所述FAQ http ask github com celery faq html isn t using pickle a security concern 这代表一个安全漏
  • 检查字符串是否只有字母和空格 - Python

    试图让 python 返回一个字符串仅包含字母和空格 string input Enter a string if all x isalpha and x isspace for x in string print Only alphabe
  • Django South - 将 null=True 字段转换为 null=False 字段

    我的问题是 转变的最佳做法是什么null True场变成null False使用 Django South 的字段 具体来说 我正在与ForeignKey 你应该先写一个数据迁移 http south aeracode org docs t

随机推荐