Function Use: To print all the directories in a folder/sub-folder or directory import os def get_list_or_dir(local_dir): for dir_or_file in os.listdir(local_dir): if os.path.isdir(dir_or_file): path = os.path.join(local_dir, dir_or_file) print(dir_or_file, 'This is a directory') get_list_or_dir(path) else: print(dir_or_file) Path = os.getcwd() or define the path from where you need a file Function Call: get_list_or_dir(path)
Welcome to the third post about printing patterns in Python. The first 3 basic patterns were easy to print that we have taught in the first 2 blogspot.
Today we will learn about printing the below pattern.
*
* *
* * *
* * * *
* * * * *
The Program
>>> n = 5
>>> for i in range(0, n):
print((n-i-1)*" "+ i*"* " + "* " + (n-i-1)*" ")
*
* *
* * *
* * * *
* * * * *
The above programme is a simple 3 line programme to print this kind of star pattern. Let's discuss the third line of the code to understand this better.
The Maths & Logic:
- In the first of the output there are 4 spaces" " and then, one star "* " and then again 4 spaces " ". Total of 9 element: 8 spaces and one star.
- In the second line of the output there are 3 spaces " ", then one star "*", again one space " ",again one star and finally 3 spaces " ". Total Element: 3 spaces + one star + one space + one star + 3 spaces. Total 9 element
- In the 3 third line of the output. There are 2 spaces " ",then 2 star and spaces pattern (* * ) and again one one star and finally 2 spaces. Total Element: 2 spaces + 2* Star and space Pattern + one star + 2 spaces. Total 9 element.
Now, the formulae that we have used in the program will make sense.
In the first loop: the value of i = 0, n = 5. In the second loop the value of i = 1, n = 5 and so one. Use these value in the below value you will always get 9 element and that's what we want.
((n-i-1)*" "+ i*"* " + "* " + (n-i-1)*" ")
Example: Let's insert the value for second loop. where i = 1, n = 5.
((n-i-1)* one element + i* two element + one element (there is no in or n) + (n-i-1)* one element.
(5-1-1)*1 + 1*2 + 1 + (5-1-1)*1 = 9
Example: Let's insert the value for third loop where i =2, n = 5.
(5-2-1)*1 + 2*2 + 1 + (5-2-1)*1 = 9
In the beginning you will have problem, but try to read this again and again and you will get to the solution.
Do comment and let me know if you guys have any issues.
Comments
Post a Comment