1

I have an assignment to create a counting down for loop. The instructions are to get the results to be as follows:

12345
1234
123
12
1

I'm probably making this to be more difficult than it actually is, but I'm quite new to Python.

So far, my script is as follows:

def print_figure():
    for i in range(5, 0, -1):
        for count in range(i):
            print(12345, end='')
        print()

Which is resulting in:

1234512345123451234512345
12345123451234512345
123451234512345
1234512345
12345

I'm not asking for an answer, just a pointer in the right direction of where I can make a fix.

3 Answers 3

1

You were almost there; you are printing the number 12345 over and over again, instead of using count, which ranges from 0 through to 4 in the first loop, 0 to 3 in the second, etc.

You want to print count itself, but either add one or adjust the range in which it loops to run from 1 to i + 1:

def print_figure():
    for i in range(5, 0, -1):
        for count in range(1, i + 1):
            print(count, end='')
        print()

or use:

def print_figure():
    for i in range(5, 0, -1):
        for count in range(i):
            print(count + 1, end='')
        print()

Demo:

>>> def print_figure():
...     for i in range(5, 0, -1):
...         for count in range(1, i + 1):
...             print(count, end='')
...         print()
... 
>>> print_figure()
12345
1234
123
12
1

The other approach would be to use a string '12345' and indexing into that; '12345'[0] is '1', etc:

def print_figure():
    for i in range(5, 0, -1):
        for count in range(i):
            print('12345'[count], end='')
        print()

but then you can just use slicing and get rid of the nested loop altogether:

def print_figure():
    for i in range(5, 0, -1):
        print('12345'[:i])

because '12345'[:3] returns the first 3 characters of the string, printing 123.

Sign up to request clarification or add additional context in comments.

2 Comments

I have the feeling the OP was halfway between that and "12345"[count]
This was great. Thanks guys. I was trying to explain it to someone earlier while I was out and the idea of an index and a slice came to mind. I just wasn't sure how to input that. Fantastic! Thanks again!
1

replace the last 2 lines :

        print(12345, end='')
    print()

with

        print(count),
    print ''

Comments

0

A more generic approach would be to take a string a remove the last item at every iteration :

value = '12345'
while value:
    print value
    value = value[:-1]

The upside is that you can easily replace 12345 with any string, of any length.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.