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

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

Related

Run for loop simultaneously on different lines

I am writing a small python3 script that prints a line in a for loop. after the line is printed, it clears that line and prints another with the percentage going up by one. However, I am struggling to get the for loop to print on two seperate lines at the same time.
If you are unclear about anything or have any questions. Run the script, hopefully you'll see what I mean.
import time
import sys
import os
# you dont need this, it merely clears the terminal screen
os.system('clear')
for c in range(1, 101):
print("xaishfsaafsjbABSF - " + str(c) + "% |======= |")
sys.stdout.write("\033[F") # goes back one line on terminal
sys.stdout.write("\033[K") # clears that line
time.sleep(0.03)
if c == 100:
print("xaishfsaafsjbABSF - " + str(c) + "% | COMPLETE |")
I have tried adding for z in range(1, 3): above for c in range(1, 101): but that just prints the second one after the first one. I want them to print at the same time on different lines.
Using ANSI escape codes to move the curser up 2 lines:
import time
for i in range(1,21):
print("Number:",i)
print("Percent:",i*100/20)
time.sleep(0.5)
print("\033[2A", end="") # move up 2 lines
print("\033[2B", end="") # move down 2 lines after the loop
Just use \r:
import time
for c in range(1, 101):
print("xaishfsaafsjbABSF - " + str(c) + "% |======= |\r", end="")
time.sleep(0.03)
if c == 100:
print("xaishfsaafsjbABSF - " + str(c) + "% | COMPLETE |")

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

How to make last element of list finish with a dot and the others with a comma?

I made this list with a for loop that points errors when yoy choose a name. I'd like to know how can I make it so that the last line finishes with '.' and the others finish with ';'.
while True:
if len(errors_list) != 0:
print("Your name has thesse errors::")
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
print("Try again.")
errors_list.clear()
name = input("My name is ").title()
choose_name(name)
else:
print("Nice to meet you, " + fname + " " + sname + ".")
break
Result when I type a name like '--- ':
Your name has these errors:
1- It has no letters.
2- It has symbols.
3- The last letter is a space.
Try again.
My name is
I'd like to make it so that 1 and 2 finish with ';' and 3 with '.'. Thanks!
All the existing solutions so far seem pretty poor, this is as print is expensive to call.
errors_list.index(i) runs in O(n) time making your solution run in O(n^2) time. You can improve this, to O(n) time, by using enumerate.
You can also think of what you're doing simply as concatenating values of a list and adding a period.
I would use:
errors = [f' {i}- {error}' for i, error in enumerate(errors_list, 1)]
print(';\n'.join(errors) + '.')
Extending Roman Perekhrest's answer, enumerate has an optional parameter start:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print("\t{}- {}{}".format(i, err, ';' if i < len(errors_list) else '.'))
additionaly with Python 3.6+ you can use f-strings instead of format:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print(f"\t{i}- {err}{';' if i < len(errors_list) else '.'}")
Instead of:
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
do
s = len(errors_list)
for e, i in enumerate(errors_list):
ending = ";" if e + 1 < s else "."
print(" " + str(errors_list.index(i) + 1) + "- " + i + ending)
EDIT:
to those jumping to the gun - OP did write in a title comma, but he used semicolon (;) twice (!) in a question itself.
Simply with enumerate function:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
...
for i, err in enumerate(errors_list):
print(" {}- {}{}".format(i+1, err, ';' if i+1 != len(errors_list) else '.'))
The crucial loop will output:
1- It has no letters;
2- It has symbols;
3- The last letter is a space.

How to replace "-" with a space?

I'm making a hangman program, and I want it to be able to include phrases; however, when I input a phrase to be guessed, the output only dashes. For instance, when I put in "how are you"(input to be guessed), the output is "-----------". What i want the out put to be is "--- --- ---", as it makes it easier for the player to know that it is a phrase. I've tried a 'for' loop and 'if' statement to now avail, and would appreciate some help. Thanks!
*At the moment I'm trying replace. Also, if this is badly worded, let me know and I'll try rewriting it.
right = ""
guess=""
attempts = 6
tries = 0
space = " "
print("Hangman: guess letters until you can guess the word or phrase.")
print("In this game you get six tries.")
right_str = str(input("\nEnter your word: "))
right_str = right_str.lower()
#displays the proper amount of unknown spaces
right = right * len(right_str)
if space in right_str:
right_str.find(space, i)
print(i)
you could try this:
guess=""
attempts = 6
tries = 0
space = " "
print("Hangman: guess letters until you can guess the word or phrase.")
print("In this game you get six tries.")
right_str = str(input("\nEnter your word: "))
right_str = right_str.lower()
output = ""
for c in right_str:
if c != " ":
output += "-"
else:
output += " "
print output

Python print messages into loop?

How can i show "dynamic" messages into loop?
For example:
for item in array:
print (item + " > Cheking file", end=" ")
#Conditions which takes some time. Create a zip file or smth else..
if (some condition):
print ("> Creating archive", end=" ")
#Another conditions which takes some time.
if (some condition):
print ("> Done!")
I thought that the result must be:
FILENAME > Checking file ... *tick tock* ... > Creating archive ... *tick tock* ... > Done!
But the line appeares entirely after each loop cycle.
How can show messages like CMD style?
The issue you have with the messages not showing up until after the last print is probably due to buffering. Python's standard output stream is line-buffered by default, so you won't see the text you've printed until a newline is included in one of them (e.g. when no end parameter is set).
You can work around that buffering by passing flush=True in the calls where you're setting end. That will tell Python to flush the buffer even though there has not been a newline written.
So try:
for item in array:
print(item + " > Cheking file", end=" ", flush=True)
#Conditions which takes some time. Create a zip file or smth else..
if some_condition:
print("> Creating archive", end=" ", flush=True)
#Another conditions which takes some time.
if some_other_condition:
print("> Done!")
This is due to buffering of the output stream. You can flush the stream after each write with the flush option to print():
for item in 'a', 'b', 'c':
print (item + " > Cheking file", end=" ", flush=True)
if (some condition):
print ("> Creating archive", end=" ", flush=True)
if (some condition):
print ("> Done!")
It's not necessary for the last print (although it won't hurt) since that will print a new line which will flush the output.
Note also that you will want to print a new line at the end of each iteration. Considering that you are printing conditionally, the final print might not actually occur, so it's a good idea to use end=' ' in all of the prints, and then print a new line at the end of each iteration:
for item in 'a', 'b', 'c':
print (item + " > Cheking file", end=" ", flush=True)
if (some condition):
print ("> Creating archive", end=" ", flush=True)
if (some condition):
print ("> Done!", end=' ')
print()
Now, if for some reason the final condition is not True, a new line will still be printed.

Categories