Python Divmod help for a mathematical exercise for beginner

63 views Asked by At

So basically all I am trying to do is take the third and forth digits from a set of numbers:

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

and divide them both(79 and 37), This is the code I have written:

# 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)

which gives me the error

"TypeError: tuple indices must be integers or slices, not tuple"

Any help would be appreciated ! Thanks

2

There are 2 answers

2
Austin On BEST ANSWER

What you want is to replace this line of code

ans = (divmod(div_num))

with:

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

You don't need div_num so remove all its references.


Why do you get your error?

num_set[2,3] is same as num_set[(2,3)]. You are trying to index a tuple by a tuple when it should be by integers or slices.


Code:

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

I suggest not to use word set as it is a type in python

With f-strings

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

edit: [2:4] is a slice of 4-2=2 elements.

When a function returns more than one items, you can assign them to variables.

f-strings (strings prefixed with f) will replace variables in between braces with their values.