Code to find the sum of multiple of Python novice 3

Asked 2 years ago, Updated 2 years ago, 20 views

num=int (input ("Enter a number")
i=1
sum=0
while i <= num:
    i=i+1
    if (i%3) != 0 :
        continue
    sum=sum+i

print("The sum of the multiples of 3 from 1 to",num", is :",sum)

Please tell me why i initializes to 1 and why sum initializes to 0.

python

2022-09-20 08:56

2 Answers

I don't think you know what initialization is.

What do you think is the first thing we do when we count? Should I fold my thumb and pick one? No. The first thing we do when we count our hands is to make sure we have them. Next, make sure that you have your fingers, then make sure that neither finger is crossed. It's only after that unconscious confirmation that we can fold our thumbs and start counting 1. It's an unexpected truth that's hard to realize unless you're physically handicapped.

Now let's look at the code. What should I do first to find the sum of multiples of 3 from 1 to num? Should we just count the numbers and check and add more? No, The first thing you need to do to get a sum of something is to declare a variable to store the sum.I'm giving my hand to Python, who didn't have one. Then Python doesn't know if it really fits (ex. whether a variable has been declared), and whether a number can be stored there (ex. Only after checking if there is memory space) can you count 1, 2, 3, ... and add a number to the variable. Oh? I guess I need to pick a number other than the sum What should I pick? Does Python know this? I don't know. You didn't put your hands on me again! Python needs to count the numbers that need to be added to the sum or not, so I'll have to declare another variable and add another hand.

In short, initialization is the step of resetting the value you want to get so that it is possible just before you actually get it. Usually, you assign 0, " (empty string), [] (empty list), None, or the first element of something. Here it's i=1 because checking whether it's a multiple of 3 is done from the smallest natural number 1. That way, Python can count from 1 to num and say, "Is i a multiple of 3?" If it's a multiple of 3, I'll put it in sum.

I'm embarrassed that I gave you a low level of explanation. Did you understand?


2022-09-20 08:56

Thank you so much I needed this easy solution, sir Black black


2022-09-20 08:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.