New day, new exercise! I again asked for something simple for Python and JavaScript. Here is what ChatGPT gave me:
Exercise: Sum of Even Numbers
Write a program that calculates the sum of all even numbers from 1 to a given number n
.
For example:
- If
n
is 10, the program should output30
, because the even numbers between 1 and 10 are 2, 4, 6, 8, and 10, and their sum is 30.
This exercise will help you practice basic loop constructs and conditional statements in both Python and JavaScript. Here's the outline of what your program should do:
- Take a number
n
as input. - Iterate through numbers from 1 to
n
. - Check if each number is even. If it is, add it to a sum.
- After the loop, output the sum.
My Code
Alright here is my Python code!
# Exercise: Sum of Even Numbers
def main():
while True:
try:
user_input = int(input('input: '))
break
except ValueError:
print('Please enter a number')
print(f'sum: {addEvenNumbers(user_input)}')
def addEvenNumbers(number):
sum = 0
while number > 0:
if number % 2 == 0:
sum += number
number -= 1
return sum
if __name__ == '__main__':
main()
ChatGPT thought my code is good but pointed out that my while loop is not efficient. It said I can do -2 steps, then the loop will only half als often. Sounds reasonable. Here is how that should look:
def addEvenNumbers(number):
sum = 0
if number % 2 != 0: # If the number is odd, reduce it by 1 to make it even
number -= 1
while number > 0:
sum += number
number -= 2
return sum
Then I asked ChatGPT for the ‘perfect solution’ for this exercise. Here is what I got
# Exercise: Sum of Even Numbers
def main():
try:
user_input = int(input('Input a number: '))
print(f'Sum of even numbers: {addEvenNumbers(user_input)}')
except ValueError:
print('Please enter a valid number')
def addEvenNumbers(number):
# Adjust the number to be the largest even number not greater than the input
number = number if number % 2 == 0 else number - 1
# Use sum formula for even numbers: 2 + 4 + ... + n = 2 * (1 + 2 + ... + n/2)
return (number // 2) * (number // 2 + 1)
if __name__ == '__main__':
main()
Yea… it’s obviously much better than my code. So much more concise! A lot to get inspired about.
Well with that done lets move on to JavaScript!
Here is as far as I get without any help. Can’t make it work because somehow it treats user_input as a string and I don’t know out of my head how to change that. So let’s start fixing this code with ChatGPT
let user_input = prompt("Input: ");
if (user_input % 2 !== 0) {
user_input--;
};
let sum = 0;
while (user_input > 0) {
sum += user_input;
user_input -= 2;
console.log(user_input);
}
console.log(`Sum: ${sum}`)
turns out what I was missing was parseInt()
. So here is the fixed code that actually works
let user_input = prompt("Input: ");
user_input = parseInt(user_input); // Convert the input to a number
if (isNaN(user_input)) {
console.log("Please enter a valid number");
} else {
if (user_input % 2 !== 0) {
user_input--;
}
let sum = 0;
while (user_input > 0) {
sum += user_input;
user_input -= 2;
}
console.log(`Sum: ${sum}`);
}
And finally again, here is what ChatGPT thinks would be the perfect answer to the exercise
function promptForNumber(message) {
let num;
do {
num = Number(prompt(message));
if (!isNaN(num) && num >= 0) {
return num;
}
console.log("Please enter a valid positive number.");
} while (true);
}
function sumOfEvenNumbers(n) {
// Adjust the number to be the largest even number not greater than n
n = n % 2 === 0 ? n : n - 1;
// Use the sum formula for the series of even numbers
return (n / 2) * (n / 2 + 1);
}
let user_input = promptForNumber("Input a number: ");
console.log(`Sum of even numbers: ${sumOfEvenNumbers(user_input)}`);
wow promptForNumber(messege)
is kind of cool. Not sure how useful it is in real life since I never see these kind of prompts in the ‘real internet’, but at least the functionality is exactly what is needed here.
Also the rest of the code super concise and nice to see.
Cool that’s it again for today. Still so much to learn. Thanks for cheering me on! 😊
Top comments (2)
About the code being much more concise (the ChatGPT generated answer for Python), it's also much less readable. One of the Python conventions is to keep you code readable. If you want to see the official poem about it, type
import this
:)Hey @kaamkiya thanks for the comment, very helpful!
And wow
import this
is cool 😄. Will keep this in mind! :)