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

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("#")

Related

How would I get my histogram to output the data vertically?

So I have the data to output like this for example
progress 1: *
progress-moduletrailer 4: ****
do_not_progress 6:******
exclude 2: **
But I would want it to show it like this
progress
2:
**
etc
I would appreciate any help with this, very stuck.
print("Progress",Progress, ":", end= " ")
for i in range (Progress):
print("*", end = " ")
print("\n")
print("Progress_module_trailer",Progress_module_trailer, ":", end= " ")
for i in range (Progress_module_trailer):
print("*", end = " ")
print("\n")
print("Do_not_progress_module_trailer",Do_not_progress_module_trailer, ":", end= " ")
for i in range (Do_not_progress_module_trailer):
print("*", end = " ")
print("\n")
print("Exclude",Exclude, ":", end= " ")
for i in range (Exclude):
print("*", end = " ")
print("\n")
print(Progress+Progress_module_trailer+Do_not_progress_module_trailer+Exclude,"Number of students in total")
Try defining the separator argument of the print function and using an f-string format as such:
print("Progress", f"{Progress}:", sep='\n'))
FYI: The default separator is a single space, changing it to a new line (or 2 new lines if you so wish) can be done through each function call.
If I understood it correctly a \n between progress, the number and the stars should do the trick!
The \n means that a new line is started.
Example:
print(Hello world)
Prints out:
Hello world
but
print(Hello\nworld)
Prints out:
Hello
World

How to remove last blank from printed line in python3?

I want to remove the last blank from printed line.
example)
list=[1,2,3,4]
for i in range(2):
print(list[i], end=" ")
>>> 1 2
There is a one blank after '2' in printed line. How can I modify the code to remove the last blank?
You can also use "list unpacking" similar to Unpacking Argument Lists in conjunction with slices.
For example:
print(*list[:2])
Returns:
1 2
+ new line symbol \n
To remove the \n symbol, you can use this code.
print(*list[:2], end="")
You can do this " ".join(map(str, [list[i] for i in range(2)])).
The blank is due to the argument end = " " in print function. This essentially tells the python program to add a " " (blank) instead of newline after every print. So you can either remove it or do something like this in your for loop.
list = [1, 2, 3, 4]
for i in range(2) :
if (i != range(2)[-1]) :
print (list[i], end = " ")
else :
print (list[i], end='')
This tells the python program to not use the extra space or newline at the end of for loop.
You don't need a for loop for this
a=[1,2,3,4]
b=' '.join(map(str,a[:2]))
will do
list=[1,2,3,4]
for i in range(2):
if i == max(range(2)):
print(list[i])
else:
print(list[i], end=" ")
1 2
If you mean you always want to cut the last space but keep the others, how about adding if?

Creating shapes using For Loop Coding in Python

Hey guys I am having a difficult time writing a code to create a triangle of asterisks and having a reflection of the triangle appear on the same line. The end product is two triangles that have a giant V shape of empty space in the middle. So far I have created the left side triangle but I do not know how to reflect it to appear reversed on the opposite side. Here is my code so far:
for A in range(1,10):
for A1 in range(1,A+1):
print("*", end='')
print()
for A2 in range():
print(" ", end='')
print()
for A3 in range(1,A+1):
print("*", end='')
print()
The end shape should look something like an M made up of triangles with a wider space in the middle. I think I am on the right track but A2 needs to be the code to create the gap of spaces in between but I cannot figure out the numbers to do it.
Any help would be appreciated, thanks!
One solution doesn't even use nested for loops
for A in range(1,10):
print(A*"*" + (18-(2*A))*" " + A*"*")
or
for A in range(1,N):
print(A * "*" + (((N-1)*2)*A)*" " + A * "*")

Python Printing and multiplying strings in Print statement

I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. Here is the code I tried:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space.
Printing two #'s works also.
I can't figure out how to combine it into one statement that works, or any other method of doing this.
Any help would be appreciated, thanks.
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i.
You want to print a string that depends an a variable. There are other methods to build a string but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#", a sequence of spaces and another "#". To add together the pieces you have to use the + operator, like in "#"+" "+"#".
Another problem in your code is the while loop, if you don't increment the variable i its value will be always 0 and the loop will be executed forever!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0 to n-1 is for i in range(n): ..., but for now the while loop is good enough.
This should do it:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return

Printing Out Every Third Letter Python

I'm using Grok Learning and the task it give you is 'to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.'
This is my code:
text = input("Message? ")
length = len(text)
for i in range (0, length, 3):
decoded = text[i]
print(decoded, end=" ")
Although I it says it isn't correct, it say this is the desired out-put:
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
And my output is the same expect, in my output, I have a space after the last 'e' in challenge. Can anyone think of a way to fix this?
To have spaces only between the characters, you could use a slice to create the string "challenge" then use str.join to add the spaces:
" ".join(text[::3])
Here's Grok's explanation to your question: "So, this question is asking you to loop over a string, and print out every third letter. The easiest way to do this is to use for and range, letting range do all the heavy lifting and hard work! We know that range creates a list of numbers, - we can use these numbers as indexes for the message!"
So if you are going to include functions like print, len, end, range, input, for and in functions, your code should look somewhat similar to this:
line = input('Message? ')
result = line[0]
for i in range(3, len(line), 3):
result += ' ' + line[i]
print(result)
Or this:
line = input('Message? ')
print(line[0], end='')
for i in range(3, len(line), 3):
print(' ' + line[i], end='')
print()
Or maybe this:
code = input ('Message? ') [0::3]
msg = ""
for i in code: msg += " " + i
print (msg [1:])
All of these should work, and I hope this answers your question.
I think Grok is just really picky about the details. (It's also case sensitive)
Maybe try this for an alternative because this one worked for me:
message = input('Message? ')
last_index = len(message) -1
decoded = ''
for i in range(0, last_index, 3):
decoded += message[i] + ' '
print(decoded.rstrip())
You should take another look at the notes on this page about building up a string, and then printing it out all at once, in this case perhaps using rstrip() or output[:-1] to leave off the space on the far right.
Here's an example printing out the numbers 0 to 9 in the same fashion, using both rstrip and slicing.
output = ""
for i in range(10):
output = output + str(i) + ' '
print(output[:-1])
print(output.rstrip())
If you look through the Grok course, there is one page called ‘Step by step, side by side’ (link here at https://groklearning.com/learn/intro-python-1/repeating-things/8/) where it introduces the rstrip function. If you write print(output.rstrip()) it will get rid of whitespace to the right of the string.

Categories