By Using Loop, Print
*
*
*
*
Print hollow square by using loops in python.
You may use below function to generate hollow square of side length "side"
def hollow_square(side):
for i in range(side):
for j in range(side):
if i == 0 or i == side-1 or j == 0 or j == side-1:
print("*", end="")
else:
print(" ", end="")
print()
hollow_square(5)
you could do it in this way
n = int(input("enter the number:"))
def spaces(n): # creating spaces
sp = ""
for i in range(n-2):
sp += " "
return sp
for i in range(n):
if(i == 0) : # for top row
print('*'*n)
elif (i==n-1) : #for bottom row
print('*'*n)
else : # for the middle section
print(f"*{spaces(n)}*")
Related
I have to print a hollow inverted pyramid:
******
* *
* *
* *
**
*
Following is my code:
n = int(input())
for i in range(n,0,-1):
if i == n:
print(n*'*', end = '')
if i > 1 and i <n:
print('*'+(i-2)*' '+'*')
else:
print('*')
print()
For input as 6 I am not sure why my code is printing 7 stars.
If anyone could help explain what I am doing wrong or missing would be really great!
There are two problems here:
There is no need for the , end=''. You still want a newline to print after this line of stars.
You used if not elif for the second condition, so the third block of code in the else will still run even if the first condition is true.
Here is the corrected code:
n = int(input())
for i in range(n, 0, -1):
if i == n:
print(n * "*")
elif 1 < i < n:
print("*" + (i - 2) * ' ' + '*')
else:
print('*')
If the first iteration of the loop, there are two print calls executing: the first one and the last, so that makes a total of 7 stars in that first line of output.
As the first and last case are different from the other cases, it is easier to just deal with those outside of the loop:
n = int(input())
print(n*'*')
for i in range(n - 3, -1, -1):
print('*' + i*' ' + '*')
if n > 1:
print('*')
There is still one if here to ensure it still works correctly for n equal to 1 or even 0.
To do it without that if, you could do this:
n = int(input())
print(n*'*')
s = '*' + n*' '
for i in range(n - 2, -1, -1):
print(s[:i] + '*')
another type of inverted hollow matrix:
54321
4 1
3 1
2 1
1
Answers:
Hollow Right-angled triangle!!!
n=int(input())
for i in range(n,0,-1):
for k in range(n,0,-1):
if i==n or i==k or k==n-(n-1):
print(k,end=" ")
else:
print(end=" ")
print()
Trying to make a program that asks the user for a height and a character, and then outputs a hollow triangle to that height using that character. Was trying to firstly make a solid triangle, then solve it from there, but so far have only managed to make a half triangle.
Also, using only for loops and no '*' operator
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < rows:
print(C, end="")
count += 1
print()
rows += 1
this results in this:
*
**
***
****
*****
my goal is this:
*
* *
* *
* *
*********
any help would be appreciated!
Slightly changed your script:
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < 2*rows-1:
count += 1
if count == 1 or count == 2*rows-1 or rows == H:
print(C, end="")
else:
print(" ", end="")
print()
rows += 1
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
for i in range(H):
for j in range(H - i):
print(' ', end='')
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or i == H - 1:
print(C, end='')
else:
print(' ', end='')
print()
There's already an answer, but considering that I had fun doing this little program, and that our solution are not the same :
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 0
while rows <= H:
cols = 0
if rows == H:
while cols <= H*2:
print(C, end="")
cols += 1
else:
while cols <= H*2:
if rows + cols == H or cols - rows == H:
print(C, end="")
else:
print(" ", end="")
cols += 1
print()
rows += 1
Note that I did this with for loops, and just swapped to while loops to paste it here.
The way to get a hollow triangle is to print spaces in a loop.
If you observe the output you need, you'll see that except for the top and bottom lines, every line has only 2 asterisks (*). That means you need a logic that handles spaces.
There are several ways to write the logic, such as treating each vertical halves as blocks of fixed length and just varying the position of the star or actually counting the spaces for each line. You can explore the different ways to achieve what you need at your convenience. I'll present one soln.
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if len(C) != 1:
C = "*"
rows = 1
count = 0
while rows < H:
str = ""
for i in range(H - rows):
str += " "
str += C
if rows > 1:
for i in range(2 * rows - 3):
str += " "
str += C
print(str)
rows += 1
str = ""
for i in range(2 * H - 1):
str += C
print(str)
I have made a change about checking the character. You should not allow characters of more than length 1. Otherwise, the spacing will get messed up
These exercises are meant for you to understand the logic and get comfortable with manipulating code, so do try different variations
This is probably not the most optimized solution but, remember that printing is in general slow as it has to interact with a peripheral (monitor), so try to print in bulk whenever possible. This improves the speed
def Y(n):
for i in range(n):
for j in range(n+1):
if j == i or j == n-i:
print('*',end = '')
print(' ',end = '')
if j > (n/2)+1 and i>(n/2)+1:
print(' ', end='')
print()
Right now the code prints out this:
Y(5)
* *
* *
* *
* *
* *
I cant figure out how to remove the two bottom right "*" to make it a y and not an x
You're solution is very close, it just needs one more condition:
def Y(n):
for i in range(n):
for j in range(n+1):
if j == i or j == n-i:
print('*',end = '')
# stop printing '*' or ' ' if i > n/2
if i > n/2:
break
print(' ',end = '')
if j > (n/2)+1 and i>(n/2)+1:
print(' ', end='')
print()
it's helpful to draw out each iteration and see how the variables are moving and what is actually being printed.
I am trying to create an arrow out of asterisk's, where the amount of columns is entered by the user. Yes, I do know how to use for loops to accomplish this:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
for x in range(1, columns):
for x in range(x):
print(" ", end="")
print("*")
for x in range(columns,0,-1):
for x in range(x):
print(" ", end="")
print("*")
#output looks like
"""
How many columns? 3
*
*
*
*
*
"""
However my question is, how would I accomplish the same outcome using only while loops?
Thanks
Edit: I was going to post what I had thus far in trying to work it out myself, but it is now of no use!
Thank you all for your efficient varying answers! Much appreciated!
Just for fun, here's a version that doesn't loop using indexing.
def print_arrow(n):
a = '*'.ljust(n + 1)
while a[-1] != '*':
print(a)
a = a[-1] + a[:-1]
a = a[1:]
while a[0] != '*':
a = a[1:] + a[0]
print(a)
# Test
print_arrow(4)
output
*
*
*
*
*
*
*
This should do:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
while x < columns:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x += 1
x = columns
while x > 0:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x -= 1
First, it's better to use functions. And easier if you know that character*number returns that character concatenated number times.
Example:
'*'*10
returns
'**********'
So your program using whiles would follow the same logic.
def print_arrow(k):
i = 0
while(i < k-1):
print(i*' ' + '*')
i +=1
while(i >= 0):
print(i*' ' + '*')
i -= 1
The first while prints the upper part, the last one uses the fact that i = k-1, so just do same in the reversed order.
Example:
print_arrow(3)
returns
*
*
*
*
*
n = int(input( ))
n1 = n//2 + 1
i = 1
while i <= n1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i += 1
i = n - n1
while i >= 1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i -= 1
Arrow pattern of asterisk
-Remember the n value here is always odd
for n = 5
output will be
I am trying to write a program that looks something like this if, say, the input number was 6, or something like that the output should look like this:
*
**
***
****
*****
******
*****
****
***
**
*
but when I do it like I was told, this way specifically because this is what a classmate told me to do. :
n = int(input("Enter a value for n: "))
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
for i in range(1, n):
for j in range(n):
if n - j < i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
I get:
*
**
***
****
*****
******
*****
****
***
**
*
What am I doing wrong? Please tell me how to get it to correctly line up, I'd really appreciate it if someone could help me with this so I can learn to do this on my own, please assist me...
If your assignment requires you to write the code exactly as you posted, Austin Kootz answer is the way to go.
However, a more simplifed way of doing this is using ljust
n = 6
for x in range(n - 1, 0, -1):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
for x in range(n):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
Your loops are a bit overcomplicated, so I've simplified somewhat:
n = int(input("Enter a value for n: "))
for x in range(n):
out = ''
for y in range(n-x):
out = out +' '
for y in range(x):
out = out +'*'
print(out)
for x in range(n):
out = ''
for y in range(x):
out = out +' '
for y in range(n-x):
out = out +'*'
print(out)
Enjoy!
What you want in the second set of loops is to take the row number (counting from 1) and print that many spaces (" "), and then print asterisks ("*") for the rest of the row. So if i is the row number and j the column number (and indexing starts from 0), you should print " " while j < i + 1 and "*" otherwise. This gives:
# The top part of the pyramid
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
# The bottom half of the pyramid
for i in range(n):
for j in range(n):
# Print spaces in the beginning of the row
# (while the column number is less than the row number)
if j < i + 1:
print(" ", end = " ")
# Print asterisks for the rest of the row
else:
print("*", end = " ")
print("")