Force type to be integer and not float in python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Force type to be integer and not float in python



I am writing a simple program that will calculate the sum of the digits. So for example 123 would be 1 + 2 + 3 = 6 simple. When I write my code


123


1 + 2 + 3 = 6


def sumOfNumber(number):
sum = 0

while(number >= 1):
temp = number % 10
sum += temp
number /= 10

return sum

main():
sumOfNumber(123)
# 6.53



Can anyone explain this?





This code works in Python2, you are most likely using Python3 where the behaviour of /= is different.
– Olivier Melançon
Aug 10 at 13:50




2 Answers
2



You seem to be using Python3 where division / outputs floats. Replace the inplace division /= with integer division //= to get rid of decimals.


/


/=


//=


number //= 10



Although, if you want to manipulate a number digit by digit, it is better to cast it to a str. This allows to loop over its digits and sum them.


str


def sumOfNumber(number):
digits = str(number)
sum_ = 0

for d in digits:
sum_ += int(d)

return sum_

sumOfNumber(123) # 6



Using the builtin sum function, you can even rewrite this function in a single line.


sum


def sumOfNumber(number):
return sum(int(x) for x in str(number))





I changed my code to use this double // thanks.
– Ely
Aug 11 at 1:20


//



I ended up just casting it, but if someone has a better solution please post as well.


def sumOfNumber(number):
sum = 0
while(number >= 1):
temp = int(number % 10)
sum += temp
number = int(number / 10)

return sum

main():
sumOfNumber(123)
# 6






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS