0

I'm trying to solve this problem:

Enter two numbers from keyboard with at least three digits.

Print the number that have the digits sum greater.

Inside of a function I have tried to print the values of variables. The values of those variables is not printed, so I think that the function is not being executed.

a = input('\n Enter the first number : ' )
x = sum([a])
print('\n The sum of the digits number ' +str(x)+ ' este : %d' %x)
b = input('\n Enter the second number : ')
y = sum([b])
print('\n The sum of the digits number ' +str(y)+ ' este : %d' %y)
def sum(param):
 var = 0
 while(param != 0):
 var += (param % 10)
 print(var)
 param /= 10
 print(param)
 return var
asked Apr 18, 2016 at 19:09
2
  • 1
    Rename your function to something other than sum and watch what happens. That'll help you figure out the problem. Commented Apr 18, 2016 at 19:11
  • Why are you trying to pass the number in as a list? also Python has a built in sum so its poor form to redefine it Commented Apr 18, 2016 at 19:12

1 Answer 1

2

The calls to the function happen before the function is defined. Move it to the start of your program.

def mysum(param):
 var = 0
 while(param != 0):
 var += (param % 10)
 print(var)
 param /= 10
 print(param)
 return var
a = input('\n Enter the first number : ' )
x = mysum([a])
print('\n The sum of the digits number ' +str(x)+ ' este : %d' %x)
b = input('\n Enter the second number : ')
y = mysum([b])
print('\n The sum of the digits number ' +str(y)+ ' este : %d' %y)

Oh, and don't override the builtin sum (that's why I used mysum).

Also, the sum of digits can be computed by using map and sum:

sum_of_digits = sum(int(x) for x in str(123) if x.isdigit())

Or as a function:

def sum_of_digits(numstr):
 return sum(int(x) for x in str(numstr) if x.isdigit())
answered Apr 18, 2016 at 19:11
Sign up to request clarification or add additional context in comments.

2 Comments

Will while(param != 0) ever exit? param is a list. Also, you might want to cast a and b to int
@cricket_007 there are more quirks than that in the code. I'm only helping him with a single step. If he needs it as a one-off thing there is the last part of my answer where I provide a why to calculate the sum of a number's digit nicely.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.