Dec-21-2019, 07:58 PM
The prompt: Write a function that takes three integer parameters: a starting integer, an ending integer, and the string "even" or the string "odd". If oddeven == "even", it will return the sum of all the even numbers from the starting integer to the ending integer (including endpoints). If oddeven == "odd", then it will return the sum of all the odd integers from the starting integer to the ending integer (including endpoints). (Hint: the modulus (%) operator may be very helpful here)
Update: I tried separating the prompt into two separate codes, and it worked. I just don't know how to combine them.
def consecutivesum(start, end, oddeven): ototal = 0 etotal = 0 #ototal means odd total, etotal means even total for i in range(start, end + 1): if oddeven == "even": if i%2 == 0: etotal = etotal + i return etotal if oddeven == "odd": if i%2 == 1: ototal = ototal + i return ototal print (consecutivesum(1, 8, "odd"))
Error:Traceback (most recent call last):
File "python", line 31
if oddeven == "odd":
^
IndentationError: unexpected indent
But when I do unindent it, the code becomes "unreachable." I also tried using elif but it returned a syntax error. I think I messed up something conceptually too...Update: I tried separating the prompt into two separate codes, and it worked. I just don't know how to combine them.
def consecutivesum(start, end, oddeven): etotal = 0 for i in range(start, end + 1): if oddeven == "even": if i%2 == 0: etotal = etotal + i return etotal print (consecutivesum(1, 8, "even")) def suM(start, end, oddeven): total = 0 for i in range(start, end + 1): if oddeven == "odd": if i%2 == 1: total = total + i return total print (suM(3, 7, "odd"))BTW I'm using the repl.it IDE