简体   繁体   中英

Finding the Sum of integers in a list between numbers from user input in Python 3.xx

num1 = int(input("Please enter the first number: "))
num2 = int(input("Please enter the second number: "))

numbers = []

even = 0
odd = 0

for x in range(num1, num2 + 1):
    numbers.append(x)

    if(x % 2 == 0):
        even += x
    elif(x % 2 == 1):
        odd += x

print("Even Sum =", even)
print("Odd Sum =", odd)

So far I have it to where it finds the sum when the user puts their input, if the first number is lower than the second number. I've been trying to solve it by putting the inputs into a list.

example: Please enter the first number: 3 Please enter the second number: 9

But when I put in a lower number first - Please enter the first number: 8 Please enter the second number: 2

It outputs - Even Sum = 0 Odd Sum = 0

I've tried everything to my knowledge so far, but can't seem to figure it out. Any advice/input would be appreciated. Thanks

You could just add an if statement to check if num1 is greater than num2. And if num1 is greater than num2, change num1 to num2 and num2 to num1.

    num1 = int(input("Please enter the first number: "))
    num2 = int(input("Please enter the second number: "))
    ##-----------##
    if num1 > num2:
         num1,num2 = num2,num1

That'll fix your problem.

Here is a solution assuming you want to preserve the values of num1/num2,

num1 = int(input("Please enter the first number: "))
num2 = int(input("Please enter the second number: "))

numbers = []

even = 0
odd = 0

start,end = (num1,num2) if num1 < num2 else (num2,num1)

for x in range(start, end + 1):
    numbers.append(x)

    if x%2 == 0:
        even += x
    else:
        odd += x

print("Even Sum =", even)
print("Odd Sum =", odd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM