I’m having a hard time getting the correct result to the problem below:
Goal
Learn to use loops together with variables to accumulate a result.
Assignment
Assume that n
is assigned a positive integer. Write code using the while loop to assign to total the sum of the first n
whole numbers as follows:
If the number is even, halve and add it;
If the number is odd, add it.
For example, if n
is 5, total will be 1 + (2/2) + 3 + (4/2) + 5 = 12.
Reminder: Whole numbers are 1, 2, 3, … (and so on).
This is what I have, but it doesn’t give me a correct answer.
#initialize counter
total = 0
#use loop to sum the numbers
while count <= n:
if n % 2 == 0:
total += (n // 2)
total += n
count += 1
Dinka96 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
In your original code you accumulate total with 2 values whenever n is even.
Better might be:
n = 5
total = 0
for i in range(1, n + 1):
total += i if (i % 2) else i // 2
print(total)
Output:
12
-
Update the
total
based on whethercount
is even or odd. Right nowtotal += n
always runs. -
You need to add the
count
asn
, or reword your variables. -
Initialize the
count
to1
Here is the update:
n = 2 # or however you are reading it.
# Initialize counter and total
count = 1
total = 0
# Use loop to sum the numbers
while count <= n:
if count % 2 == 0:
total += (count // 2)
else:
total += count
count += 1
print(total) # 40
Side note: You could rewrite the whole loop using list comprehension in one line:
n = 10 # or however you are reading it.
# Sum the numbers using list comprehension
total = sum([count // 2 if count % 2 == 0 else count for count in range(1, n+1)])
print(total) # 40
1
I would use a for loop and a range to avoid manually incrementing:
total = 0
for i in range(1, n + 1):
total += i if i % 2 else i // 2
For this specific case an iterator solution is even more applicable, and will give the understanding of Python power:
total = sum((i if i % 2 else i // 2) for i in range(1, n + 1))
makukha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
If you want to have one liner you can do:
total = sum((i // 2 if i % 2 == 0 else i) for i in range(1, n + 1))
where range(1, n + 1)
is used to generate numbers from 1
to n
.
(i // 2 if i % 2 == 0 else i)
checks if the number is even or odd, so if it is even, which is checked as (i % 2 == 0)
, we add i // 2
and in case it is odd we just add i
. and sum()
is used to sum all the items.
The result will return also 12
if n=5
.