Python Patterns

Here is a quick challenge to focus on the use of loops, nested loops and string manipulation using Python.

Let’s look at the following code:

for i in range(0,9):
    st=""
    for j in  range(0,i):
        st = st + " "
    st = st + "#"
    print st

btnTryCodeOnline_Over

This code uses nested “for” loops (a loop within a loop). The output will be as follows:

PythonPattern-1

Note that there are sometimes more than one solution to the same problem. Look at the following code which makes more effective use of string concatenation techniques:

for i in range(0,9): 
    print (" " * i) + "#"

btnTryCodeOnline_Over

This code would generate exacly the same outcome. It is more effective as it performs the same task using less instructions and iterations.

You can now adapt these techniques to try to produce the following patterns…

Python Patterns

Did you like this challenge?

Click on a star to rate it!

Average rating 2.5 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: , ,