r/pythonhelp • u/[deleted] • Oct 16 '20
Help
If someone chose the number 3, how would I make a code that chooses all the positive integers from 1 to n (3), and displays the sum of the numbers? So for example 3, 1+2+3=6(sum)
1
u/HobbesTheDireTiger Oct 16 '20
You could create a program that accepts an input or parameter of n and uses a for loop to add each consecutive integer in the range of the n that you chose to a general variable that you could call sum that you could then return. I'm new to python myself so I don't know if this is the best way but I was able to do it like that.
1
u/drollia Oct 16 '20
You are going to want to use the built-in functions, Range() , sum() and input ()
pseduocode:
var_1 = input("please enter a number")
var_2 = int(var_1)
range(1, var_2)
That should get you the range with the number from 1 to n. Then you will just to sum the numbers. This might be a good reference for summing a range: https://stackoverflow.com/questions/20455977/sum-up-all-the-integers-in-range
1
5
u/WhenRedditFlies Oct 16 '20
For anyone who wants a quick answer:
n = int(input("enter a number: "))numbers = range(1, n+1)total = sum(numbers)print(total)