The most common answer for the 4.8.4 Better Sum CodeHS is:
# Enter your code here
firstnum = int(input("What is your frist number?: "))
lastnum = int(input("What is your second number?: "))
sum = 0
for i in range(firstnum, lastnum + 1):
sum += i
print(sum)
It is almost correct, but it seems to lack proper indentation, which is essential in Python. Here’s the corrected version with proper indentation:
firstnum = int(input("What is your first number?: "))
lastnum = int(input("What is your second number?: "))
sum = 0
for i in range(firstnum, lastnum + 1):
sum += i
print(sum)
This code will take two numbers as input from the user and calculate the sum of all the numbers from the first number to the second number, inclusive. The range(firstnum, lastnum + 1)
function generates a sequence of numbers starting from firstnum
and ending at lastnum
. The loop then iterates through this range, adding each number to the sum
variable. After the loop completes, the total sum is printed.
Just make sure that firstnum
is less than or equal to lastnum
. If firstnum
is greater than lastnum
, the range
function will not generate any numbers, and the sum will be 0.