Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Friday, May 3, 2013

Single loop: Print first n odd numbers.


Problem: Print first n odd numbers.

Example:

1 3 5 7 9 11 ...

Solution in Python:


def odd_numbers(n):
    """
    Author: Mayur P Srivastava
    """

    numbers = []

    for i in range(n):
        numbers.append(2*i + 1)

    print " ".join([str(e) for e in numbers])


Concepts learned: Single loop.

No comments:

Post a Comment