Sum Up To
Hello, Today I made a program that calculate the sum of a number, for example if you have the number 5 the program will calculate the sum 1 + 2 + 3 + 4 + 5 which is 15 So heres how to do it.
To do this we can use an if-else function so if the number is equal to 0 it will return 0 else it will minus the number by one and lets pretend our number is 2 so 2 - 1 = 1 and then before the program plus the number it will go back to the first condition and it goes is 1 == 0 no so it goes to the else and then it goes again 1 - 1 = 0 and it goes up again is 0 == 0 yes so it adds everything up and it returns the value.
If you dont get it look at the flow chart:
Here is what the code should look like:
def sum(num):
if num == 0:
return 0
else:
return sum(num -1) + num
print(sum(1))
And here is the sample output
3