I have to prompt a user to input a value n >= 3 such that my python 3.2 program can print a n by n pattern.
Example, n=4 ==> Pattern:
x..x
.xx.
.xx.
x..x
Another example, n=5 ==> Pattern:
x...x
.x.x.
..x..
.x.x.
x...x
Notice that the x get closer to each other after each row. After the middle row the get further from each other and finally reach their respective ends.
Please help me with this problem. I know I have to use branching and looping but I just can’t figure the logic behind the pattern.
I’ve managed to print out a n by n pattern but it looks like this:
Example n=4 ==> Pattern:
xx..
xx..
xx..
xx..
My code looks like this:
pattern_size = int(input("Please enter pattern size:"))
while pattern_size < 3:
print("Pattern size should be at least 3")
pattern_size = int(input("Please enter pattern size:"))
for level in range(1,pattern_size+1):
for num in range(2):
print("x", end="")
num_dot = pattern_size - 2
for num in range(num_dot):
print(".", end="")
print()
Can someone advice me on how to print the “.” and “x” alternately?
Here is the code that works for python2.7. The trick here is one of the “x” always shifting left, while the other one is always shifting right.
Here is another solution using lists: