【问题标题】:Python Divmod help for a mathematical exercise for beginnerPython Divmod 帮助初学者进行数学练习
【发布时间】:2020-03-28 11:24:15
【问题描述】:

所以基本上我要做的就是从一组数字中取出第三个和第四个数字:

# Number Set
num_set = (28,54,79,37,2,9,0)

把它们都分开(79和37),这是我写的代码:

# Division of third and fourth digits
# Seperating the digits
div_num = ((num_set[2,3]))
print("we are going to divide", div_num)
ans = (divmod(div_num))
print("the answer for 79 divide by 37 is", ans)

这给了我错误

"TypeError: 元组索引必须是整数或切片,而不是元组"

任何帮助将不胜感激!谢谢

【问题讨论】:

    标签: python numbers int division divmod


    【解决方案1】:

    你想要的是替换这行代码

    ans = (divmod(div_num))
    

    与:

    ans = divmod(num_set[2], num_set[3])
    

    你不需要div_num,所以删除它的所有引用。


    为什么会出现错误?

    num_set[2,3]num_set[(2,3)] 相同。你试图用一个元组索引一个元组,而它应该是整数或切片。


    代码

    ans = divmod(num_set[2], num_set[3])
    print("the answer for 79 divide by 37 is", ans)
    

    【讨论】:

    • 感谢@Austin,代码确实有效,但我确实需要显示我正在划分的数字,这就是使用div_num 的原因,那么我该怎么做呢?
    • 您好,您可以使用print("we are going to divide", num_set[2], num_set[3])。请不要忘记按答案左侧的勾号来接受有用的答案。
    【解决方案2】:

    我建议不要使用单词set,因为它是python中的一种类型

    使用 f 字符串

    num_list = [28, 54, 79, 37, 2, 9, 0]
    
    n, p = num_list[2:4]
    print(f"we are going to divide {n} by {p}")
    q, r = divmod(n, p)
    print(f"the answer for {n} divide by {p} \
    is {q} and a remainder of {r}")
    

    编辑: [2:4] 是 4-2=2 个元素的切片。

    当函数返回多个项目时,您可以将它们分配给变量。

    f-strings(以f为前缀的字符串)将用它们的值替换大括号之间的变量。

    【讨论】:

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