Write a program that computes the sum of all numbers up to a input number n

There are multiple approaches we can take to this: we could for instance use iteration in a loop or even use a recursive function. But since we want an arbitrary input n we probably should make sure that the user can input a value use type conversion to ensure that this value is an integer for our sum function. We can start by defining our sum function, i'll use recursion so we'll need a step case and a break case:def sum(n): if n == 0: //this is the break case, this prevents the function from infinitely calling itself and it provides an output for trivial case. return 0 else: //this is the step case, here the function slowly gets to the answer with divide and conqueor, here the recursive call happens return 1+sum(n-1) Lets work on the input now:num = int(input("Enter a number greater than 0: "))now we can call our function with this variable:sum(num)

Answered by Larbi E. Python tutor

1058 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

How do you define a class in python


Write a function that takes a string, and outputs that string formatted in camelcase. (alternating upper and lower case for each character, e.g. cAmElCaSe)


Write a recursive function that takes any integer n and prints the nth Fibonacci number.


What is the difference between DFS and BFS? Where can I apply each?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences