Using end= parameter in loop (Python) - python

My desired output is two half pyramids separated by two spaces.
length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
spaces = length - (i+1)
hashes = 2+i
print("", end=" "*spaces)
print("#", end=" "*hashes)
print(" ", end="")
print("#" * hashes)
However, this ends up printing only the first hashes of each row on the left pyramid. If I get rid of the end= in line 7, the pyramids are both printed correctly, but with newlines after each row. Here are the outputs:
With end=:
# ##
# ###
# ####
# #####
Without end=:
##
##
###
###
####
####
#####
#####
All I want now is to have the second output, but without the newlines.

The most straightforward way to print any output you want without newlines is to uses sys.stdout.write. This writes a string to the stdout without appending a new line.
>>> import sys
>>> sys.stdout.write("foo")
foo>>> sys.stdout.flush()
>>>
As you can see above, "foo" is written with no newline.

You're multiplying the end parameter by the number of hashes, instead of multiplying the main text portion.
Try this modification:
length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
spaces = length - (i+1)
hashes = 2+i
print(" " * spaces, end="")
print("#" * hashes, end="")
print(" ", end="")
print("#" * hashes)

Try this algorithm:
length = int(input("Enter size of pyramid."))
# Build left side, then rotate and print all in one line
for i in range(0, length):
spaces = [" "] * (length - i - 1)
hashes = ["#"] * (1 + i)
builder = spaces + hashes + [" "]
line = ''.join(builder) + ''.join(builder[::-1])
print(line)

Related

how to print star hypen pattern in python

How to print the pattern like this:
(need to print n-1 lines)
input=3
----#
--#-#-#
input=6
----------#
--------#-#-#
------#---#---#
----#-----#-----#
--#-------#-------#
My code:
row = int(input())
for i in range(1, row):
for j in range(1,row-i+1):
print("-", end="")
for j in range(1, 2*i):
if j==1 or j==2*i-1:
print("#", end="")
else:
print("-", end="")
print()
MY OUTPUT:
input=5
----#
---#-#
--#---#
-#-----#
Please explain how to do??
There are a few things missing and to be improved in your code:
There's no need to make a loop to print the same character again and again: on python you can use the product to repeat the character an x number of times. For example: "-" * 3 == "---"
They way you calculate the hyphens in the middle is fine, but you need to do it twice and add an "#" in between.
You can build the strings part by part first and then print the whole line, avoiding having to print an empty line in the end of the loop.
Personally, since the first line is going to have one "#" and not three, I prefer to calculate it and print it separately.
With these improvements, a solution to your problem could be:
row = int(input())
print("-" * (row - 1) * 2 + "#")
for i in range(row - 2, 0, -1):
left_hyphens = "-" * i * 2
mid_hyphens = "-" * (1 + 2 * (row - 2 - i))
print(left_hyphens + "#" + mid_hyphens + "#" + mid_hyphens + "#")
row = int(input())
for i in range(1, row):
for j in range(1,2*(row-i)+1):
print("-", end="")
for j in range(1, 4*i):
if j==1 or j==2*i-1 or j==4*i-3:
print("#", end="")
elif j<=4*i-3:
print("-", end="")
print()

4.16 LAB: Warm up: Drawing a right triangle

This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.
(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character.
(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character.
I'm having trouble figuring out how to create a space between my characters. Example input is % and 5. My code is:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_height):
print((triangle_char) * (i + 1))
my output is:
%
%%
%%%
%%%%
%%%%%
while expected output is:
%
% %
% % %
% % % %
% % % % %
You need to use join(). This would work:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)))
It is adding spaces between every character because strings are iterable.
This may be optimized a bit by having a list of the characters and appending 1 character in each iteration, rather than constructing triangle_char * (i+1) every time.
This should fix the white space errors:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)) + ' ')
for i in range(triangle_height+1):
print(f'{triangle_char} '*i)
I see the popular way so far is using join, but another way while trying to stay true to the original idea is you simply can add a white space after each character. See below:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range(triangle_height):
print((triangle_char + ' ') * (i + 1))
There are some really good suggestions on here. Another approach is to use an incremented variable in a while loop as shown below:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
i = 0
while (i <= triangle_height):
print((triangle_char + ' ') * i)
i += 1
With the example above, i iterates until it is equal to triangle_height and uses polymorphism to generate a quantity of (triangle_height + ' ') based on the value of i. This will generate the right triangle this lab requires. The space is used to format the triangle per lab requirements.
Another method is using the .join() feature, and it certainly would work well here, but is not taught until CH7 of this book where you learn about input and CSV files. I am unsure if your professor would approve of using this, and I am only saying this because my professor was strict about using material not covered.
An additional method mentioned already is to use a for loop with the use of the range() feature containing an expression:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
for i in range((triangle_height + 1)):
print((triangle_char + ' ') * i)
The end point of range() being just triangle_height would not suffice because the value specified as the end point is not included in the sequence. This would make a right triangle with a height of 4 even if triangle_height was 5 Therefore, you must use the expression (triangle_height + 1). From there, the output is set up similarly to my first solution.
Try adding a whitespace in the print statement.
height = int(input())
symbol = (input())
print()
for i in range(height): #Loop for every index in the range 0-height
print((symbol + ' ') * (i + 1)) #Add whitespace to symbol

Print 2d list as a game board

I have a 2d list [1,2,3,4],[4,3,3,1],[3,2,1,1],[2,2,2,1] and I want to print it out to match the following format.
0123
XXXXXXXX
0*1234*0
1*4331*1
2*3211*2
3*2221*3
XXXXXXXX
0123
It should not be hard coded and the length of the list = n so this list n=4 but if list n=5 there would be 5 digits per row and the number on the sides would go 0,1,2,3,4.
So far all I have is:
for row in board:
for column in row:
print(column, end="")
print("")
Which only outputs the list as:
1234
4331
3211
2221
please help me add all the special stuff.
so I find a solution for what you want to do however I think it can be improved a lot (not program quite a lot in python), but I'll leave it here anyways :)
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
for x in range(len(board)+4):
print("X", end="")
print()
for num,row in enumerate(board):
print(f"{num}*", end="")
for column in row:
print(column, end="")
print(f"*{num}", end="")
print("")
for x in range(len(board)+4):
print("X", end="")
print()
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
Well for the first line you pretty much print 2 spaces, followed by all the digits between 0 and the number of columns in your board. You can use the "range" function for this. Then you must print the correct amount of 'X'. The correct amount is number of columns + 4, I think you can see why.
You should keep a counter starting from 0. For each row you print, you must print the string value of the counter, followed by an asterisk(*), followed by your row, followed by an asterisk(*) and finally followed by the same counter value. You must increment the counter by one for each row.
The last 2 rows are the same as top 2.
I do not want to share my code because this is such a simple problem, I think solving it on your own will help you in the long run.
Probably an unpopular opinion, but I think these kinds of problems are really fun.
This solution formats the contents correctly, even if you change the number of rows, and even the number of items in each row.
def draw_board(board):
# determining the number of elements in a row,
# this is used for printing the X's
# and printing the spaced ranges (i.e. " 0123 ")
n = len(board[0])
# calculating the total width of the board,
# + 4 is because of the "0*...*0" situation
width = n + 4
# calculating margin of the spaced ranges
# (i.e. calculating how much space on each side)
margin = int(n / 2)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
# printing the XXXX
print("X" * width)
# printing the row index number,
# with the *,
# along with the numbers in the row,
# followed by the * and the row number
for row in range(len(board)):
print(str(row) + "*" + "".join(str(elem) for elem in board[row]) + "*" + str(row))
# printing the XXXX
print("X" * width)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
b = [
[1,2,3,4],
[4,3,3,1],
[3,2,1,1],
[2,2,2,1]
]
draw_board(b)
# OUTPUT:
# 0123
# XXXXXXXX
# 0*1234*0
# 1*4331*1
# 2*3211*2
# 3*2221*3
# XXXXXXXX
# 0123
Edited to remove my own tests and to reflect given problem.

How do I minimize the space between characters in my nested loop?

so I'm trying to get my nested loop to display an image like in this picture:
So far, this is the code that I have.
for a in range (1):
print("#""#")
for b in range (0,5,1):
print("#", end=" ")
for c in range(b):
print(" ", end=" ")
print("#")
I'm new to the site, so please excuse my terrible formatting. The output I'm getting seems to have an extra space per line compared to the image given, and I'm not sure how to get rid of the space. I'd appreciate any help!
I'm thinking it's the 'end=' '' statement, but if I try replacing that with just a space, my entire line goes wonky.
Thanks!
end=" " prints an space instead of a newline in the end..
I think its better to concatenate the string in this case instead of manipulating the print's end..
for i in range(5):
print('#' + ' '*i + '#')
output:
##
# #
# #
# #
# #
You need to remove the whitespace in the 2nd end variable
for a in range (1):
print("#""#")
for b in range (0,5,1):
print("#", end=" ")
for c in range(b):
print(" ", end="") #this end variable is what is causing your additional space
print("#")
Like this? Changed the third print
for a in range (1):
print("#""#")
for b in range (0,5,1):
print("#", end=" ")
for c in range(b):
print(end=" ")
print("#")

Pyramid from letters in string

I have begun programming with Python and I made this simple program drawing stars in the shape of the pyramid:
print("Put in the number of stars")
row = int(input())
letters = "python"
for i in range(row):
stars = i*2-1
spaces = row - i
print(" "* spaces + "*"* stars)
How can I make this pyramid out of the word python instead of stars? I mean this:
p
pyt
python
pythonpyt
pythonpytho
and so on?
Thanks for help guys.
You can use itertools.cycle and itertools.islice to build the rows:
from itertools import islice, cycle
n = 5
for i in range(n):
print((n-i)*' ' + ''.join(islice(cycle('python'), 2*i+1)))
prints:
p
pyt
pytho
pythonp
pythonpyt
Modification to the original post:
print("Put in the number of stars")
row = int(input())
letters = "python"
l = letters * row
for i in range(1, row + 1):
stars = i*2-1
p = l[0:stars]
spaces = row - i
print(" "* spaces + p)
output:
Put in the number of stars
10
p
pyt
pytho
pythonp
pythonpyt
pythonpytho
pythonpythonp
pythonpythonpyt
pythonpythonpytho
pythonpythonpythonp

Categories