0
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0

    while M <= N:
        if M % 2 == 1:
            sum = sum + M
            M = M + 1
            print(sum)

This is my python code, every time I run the program, it prints the number twice. (1 1 4 4 9 9 etc.) Just confused on why this happening - in intro to computer programming so any help is appreciated (dumbed down help)

Xantium
  • 11,201
  • 10
  • 62
  • 89

3 Answers3

0

My guess is the print statement is not indented inside the if statement properly. As the sum wont increase for an even number and every other number is even

Make sure you have everything indented properly

M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0

while M <= N:
    if M % 2 == 1:
        sum = sum + M
        print(sum)
    M = M + 1
Mitch
  • 3,342
  • 2
  • 21
  • 31
  • Yeah that was exactly it, thank so much for the help - still getting a hang on the syntax –  Feb 12 '18 at 00:51
0

My best bet would be to add M++ line after the scope of if statement. What really is happening that your increment only works when it is inside the if statement but this is logically incorrect because it should increment everytime loop executes.

0

Get rid of eval() you really do not need it. and replace it with int(). By default input() is a string by default so int() converts it to an integer.

You are using a reserved keyword sum

Try running sum.__doc__. You will see that sum is actually an inbuilt function. You should not create a variable the same name as an inbuilt function. However you can use an underscore (described in pep8) and this will create a working variable.

Corrected code:

M = int(input("Input the first number "))
N = int(input("Input the second number(greater than M) "))
sum_ = 0

while M <= N:
    if M % 2 == 1:
        sum_ = sum_ + M
        M = M + 1

        print(sum_)
Xantium
  • 11,201
  • 10
  • 62
  • 89