V Shaped Pattern Printer
Section 3 | Problem 2
๐จ๏ธ “V” Shaped Pattern Printer
Let’s create a fun program that prints a “V” shaped pattern using slashes and a 'v' at the bottom! ๐
๐ฉ Problem Description
- Input: An integer
n(n > 0) representing the number of rows. - Output: Print a “V” shaped pattern:
- Use
\(backslash) and/(forward slash) for each row. - The bottom row (last row) is just a lowercase
v. - There should not be trailing spaces on the right side of any line.
- Use
๐งโ๐ป Full Solution
n = int(input())
for i in range(1, n):
# Print spaces for left padding
left_spaces = ' ' * (i - 1)
# Print backslash, spaces in the middle, and forward slash
mid_spaces = ' ' * (2 * (n - i) - 1)
if mid_spaces:
print(left_spaces + '\\' + mid_spaces + '/')
else:
# When mid_spaces is zero, the slashes touch; only for n=2, i=1
print(left_spaces + '\\/')
# Print the bottom 'v'
print(' ' * (n - 1) + 'v')๐ Step-by-Step Explanation
- Input:
- Read integer
n.
- Read integer
- Loop for rows 1 to n-1:
- Print spaces on the left:
i-1spaces. - Print a backslash:
\. - Print spaces in the middle:
2*(n-i)-1spaces. - Print a forward slash:
/. - No trailing spaces after the slash!
- Print spaces on the left:
- Last row:
- Print
'v'withn-1left spaces.
- Print
๐งช Practice Examples
Example 1
Input:
3Output:
\ /
\ /
vExample 2
Input:
5Output:
\ /
\ /
\ /
\ /
vExample 3
Input:
1Output:
v๐ก Tips
- Backslash needs to be escaped in Python: use
'\\'in strings. - No extra spaces should be on the right side of any lineโonly left spaces for indentation.
โจ Try It Yourself!
- Test with various values of
nto see beautiful “V"s of different sizes. - Make sure to check the code for both even and odd values of
n.
Happy Coding! ๐