-1

I'm doing a project, but it is too hard to explain the project here, so I'm giving a simpler example here. Like I tell python :

 n = 1999.0

but python don't know that n is an integer. So how do I tell python "n is an integer"?

Note: I can't use the int() method. Let me give you another example:

>>> # A code to calculate the sum of all integers below 100 that can be divided by 7.
>>> n = 0
>>> for i in range(1,101):
    if i / 7 == int(): # if it is a integer after being divided by 7
        n += i
>>> print(n)
0

I'm asking how to tell python that although this number is in float form, but it is an integer, not other ways to solve this question, so please don't misunderstand this question. Thanks for your help. :)

J.Doe
  • 81
  • 1
  • 5

1 Answers1

1

To check if a float is an int, there is several ways, you can either use the int division and check if both division are equals, or take the %1 and check if it is 0:

n=0
for i in range(1,101):
    if i / 7 == i // 7: # Compute division two times, one in float, the other in int
        n += i
print(n)

or

n=0
for i in range(1,101):
    if i / 7 % 1 == 0: # Compute the decimals and check if it is null
        n += i
print(n)

both print 735

As Sam Mason suggested, the best way to compute the sum of all numbers that can be divided by 7, you should just test if i%7 == 0

BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42
  • why is the second version not `i % 7 == 0`? would seem more intuitive to me… – Sam Mason Jan 26 '19 at 11:32
  • @SamMason You are totally right, for the purpose of the for loop, this is better, but the question was how to check if a number is a float or an int, not if it can be divided by 7 ! (I will update my answer to include your comment) – BlueSheepToken Jan 26 '19 at 11:36
  • @SamMason I just noticed the OP asked to not show another way to solve the problem, but only to check if it is an integer – BlueSheepToken Jan 26 '19 at 11:38
  • 2
    given that the OP likely learning to program, I generally think it's better to say "you're asking the wrong question" nicely. i.e. "dividing and then asking if the remainder is a whole number" is what we'd do a as human, but for a computer it's generally better to "calculate the remainder after division, and check if that's zero" – Sam Mason Jan 26 '19 at 11:40