简体   繁体   中英

How to debug my Python program, which sums positive numbers based on their evenness

I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and does the same thing as before, till the user type 0/negative number.

After that the software should print the number with the maximal sum. Sometimes it works and sometimes not.

Code:

def sum_Digits(n):
    sum = 0
    if n % 2 == 0: #For even numbers
        while n>0:
            if (n%10)%2 == 0:
                sum += n%10
                n = n//10
            else:
                n = n//10
        print("sum: " , sum)
        return sum
    
        
    elif n % 2 != 0 : #For odd numbers
        while n>0:
            if (n%10)%2 != 0:
                sum += n%10
                n = n//10
            else:
                n = n//10
        print("sum: " , sum)
        return sum


def read_Numbers(N):
    maX = 0
    while N > 0:       #while askNum Positive continue summing
        suM = sum_Digits(N)
        if suM > maX:
                maX = N
        N = int(input("Please eneter a Natural number: "))
    if N <= 0:
        return maX
        
        


def main():
    num = int(input("Please enter a Natural number: ")) #asking the user to enter number
    sum_Digits(num)
    askNum = int(input("Please eneter a Natural number: "))
    maxSum = read_Numbers(askNum)
    print("Number with maximal sum: " , maxSum)
main()

Bug:

if user enter a negative number it will continue the loop and print the last entered number because the program doesn't check for negative numbers

Fix:

I have added a condition if N <= 0:

return maX this will return the last entered positive number

Bug:

sum_Digits(num) I have removed this line because it is not needed because we already call the function sum_Digits in the main function

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