Python divmod 帮助初学者进行数学练习

Python Divmod help for a mathematical exercise for beginner

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

# 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: tuple indices must be integers or slices, not tuple"

如有任何帮助,我们将不胜感激!谢谢

你要的是替换这行代码

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)

我建议不要使用单词 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 个元素的切片。

当一个函数returns超过一项时,可以将它们赋值给变量。

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