开发者

finding numbers that end in 5

开发者 https://www.devze.com 2023-03-14 15:33 出处:网络
I am trying to print out all the numbers from 1 to 100 that end in 5. This is what开发者_JAVA百科 I have:

I am trying to print out all the numbers from 1 to 100 that end in 5. This is what开发者_JAVA百科 I have:

 for i in range (1, 100):
      if (i/10) == 5:
           print(i)

Why does this print out 50?


You want to use modulo % as oppose to division. Modulo gets the remainder.

for i in range (1, 100):
    if (i % 10) == 5:
        print(i)


Because 50 / 10 is 5. What you really want is probably this:

for i in range(100):
    if i % 10 == 5:
        print i

% is the modulo operation and gives you the remainder of the integer division of two numbers.


Why test the values at all? Just generate the ones you want in the first place.

for i in range(5, 101, 10):
    print (i)


This is a great way to become familiar with itertools

From IPython shell:

In [5]: import itertools

In [6]: fives = itertools.count(start=5, step=10)

In [7]: fives.next()
Out[7]: 5

In [8]: fives.next()
Out[8]: 15

In [9]: fives.next()
Out[9]: 25

In [10]: fives.next()
Out[10]: 35

In [11]: fives = itertools.count(start=5, step=10)

In [12]: tmp = itertools.takewhile(lambda x: x <= 100, fives)

In [13]: tmp
Out[13]: <itertools.takewhile at 0x171f65f0>

In [14]: list(tmp)
Out[14]: [5, 15, 25, 35, 45, 55, 65, 75, 85, 95]

It's also a fun history lesson, because list comprehensions and generators in Python have a lot in common with their motivating ancestors from Haskell. Search this page for infinite lists to see what I mean: (link).

0

精彩评论

暂无评论...
验证码 换一张
取 消