Python OOPE Exam
2024 Sep Oppe 1 Set 1
✨ Print “X” Pattern Program
Let’s write a Python program that prints an “X” shaped pattern using backslashes (\), forward slashes (/), and a lowercase x in the center! 😃
📋 Problem Description
- Input: An integer
n(n >= 0) - Output: An “X” shape with a center
"x"andnidentical rows above and below, built with slashes.- No extra spaces to the right of the pattern.
🧑💻 Full Python Code
n = int(input())
# Print the top part
for i in range(n):
# i spaces, then '\', then (2*n - 2*i - 1) spaces, then '/'
left_spaces = ' ' * i
middle_spaces = ' ' * (2 * n - 2 * i - 1)
print(left_spaces + '\\' + middle_spaces + '/')
# Print the central x
print(' ' * n + 'x')
# Print the bottom part (mirror of above)
for i in range(n-1, -1, -1):
left_spaces = ' ' * i
middle_spaces = ' ' * (2 * n - 2 * i - 1)
print(left_spaces + '/' + middle_spaces + '\\')🔍 Step-by-Step Explanation
- Top Rows:
- For each row
ifrom0ton-1:- Print
ispaces. - Print a backslash (
\). - Print
(2*n - 2*i - 1)spaces (between slashes). - Print a forward slash (
/).
- Print
- For each row
- Central Row:
- Print
nspaces, then the character'x'.
- Print
- Bottom Rows:
- Repeat in reverse for
ifromn-1to0:- Print
ispaces. - Print a forward slash (
/). - Print
(2*n - 2*i - 1)spaces. - Print a backslash (
\).
- Print
- Repeat in reverse for
- No trailing spaces are added to the right of the pattern.
🧪 Practice Examples
Example 1
Input:
2Output:
\ /
\ /
x
/ \
/ \Example 2
Input:
3Output:
\ /
\ /
\ /
x
/ \
/ \
/ \Example 3
Input:
0Output:
x✨ Tips
- Use
'\\'for a literal backslash in Python strings! - No additional spaces to the right of any line.
- The size of the “X” will be
2*n + 1lines in total.
Happy Coding! 🚀
Try changing n to see different sizes of the “X” pattern!