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.
Related
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
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?
So here is what I have. This is a program in which I have to take a random string, ex) "]][][sfgfbd[pdsbs]\bdgb"; and strip it of all special characters. the function "Strip" works for its purpose.
message=(str.lower(input("Enter a Coded message: ")))
offset=int(input("Enter Offset: "))
alphabet="abcdefghijklmnopqrstuvwxyz"
def strip(text):
print("Your Lower case string is: ",message)
print("With the specials stripped: ")
for index in text:
if index in alphabet:
print(index, end="")
print()
return strip
I need the output from strip in the "decode" function, but I can't seem to figure out anyway of storing the iterations of "index"
def decode(character):
encrypted= ""
for character in message:
global offset
if character == " ":
encrypted+= " "
elif ord(character) + offset > ord("z"):
encrypted+=chr(ord(character) +offset - 26)
else:
encrypted+= chr(ord(character)+(offset))
print("the decoded string is: ",encrypted,end=" ")
print()
So "decode" only takes the output from the original "message" input. "Palin" however succeeds in taking decode's value.
def palin(code):
print(code[::-1])
print(code[:])
if code[::-1]==code[:]:
print("This is a Palindrome!")
else:
print("This is not a Palindrome.")
return palin
print()
palin(decode(strip(message)))
Don't get confused between print and return.
You need to look carefully at the outputs of your methods (what they return, not what they print to the console):
the strip() and palin() methods are returning references to themselves, rather than anything useful relating to their inputs.
the decode() method isn't returning anything.
To fix this, you can use a variable inside your method, that you build based on the input variables, using the logic you want. For example:
def strip(text):
print("Your Lower case string is: ",text)
print("With the specials stripped: ")
stripped_text = "" # <-- create and initialise a return variable
for index in text:
if index in alphabet:
stripped_text += index # <-- update your return variable
print(index, end="")
print()
return stripped_text # <-- return the updated variable
You then need to do something similar for decode(), although here you already have an output variable (encrypted) so you just need to return it at the end of the method.
The palin() method doesn't need to return anything: it just prints out the result.
Once you get this working, you should think about how you can use other features of the Python language to achieve your goals more easily.
For example, you can use replace() to simplify your strip() method:
def strip(text):
return text.replace('[^a-z ]','') # <-- that's all you need :)
I'm trying to print multiple things scattered in a loop. Here is an example:
print str(n)+" ",
for I in range(k):
print str(l)+"+",
if l>4:
break
This gives me an out put like
10= 1+ 2+ 3+ 4
While I want it to give
10=1+2+3+4
Use sys.stdout.write directly instead of print:
from sys import stdout
stdout.write(str(n)+" ")
for I in range(k):
stdout.write(str(l)+"+")
if l>4:
break
The reason this happens is because a comma with the print statement forces a space between the two elements. You're best to construct the target output string inside the loop, then print it once. Try to avoid any sort of output being done in a loop if possible.
outstr = str(n)+" " # do you mean `str(n)+"="?`
for I in range(k):
outstr = outstr + str(l)+"+",
if l>4:
break
print outstr
I am following the book Introduction to Computing Using Python, by Ljubomir Perkovic, and I am having trouble with one of the examples in recursion section of the book. The code is as follows:
def pattern(n):
'prints the nth pattern'
if n == 0: # base case
print(0, end=' ')
else: #recursive step: n > 0
pattern(n-1) # print n-1st pattern
print(n, end=' ') # print n
pattern(n-1) # print n-1st pattern
For, say, pattern(1), the output should be 0 1 0, and it should be displayed horizontally. When calling the function pattern(1), nothing prints out, however. But if this is followed by a print statement without arguments, then the results are displayed.
>>>pattern(1)
>>>print()
0 1 0
If I remove the end argument of the print() functions inside the recursive function, I get correct output (albeit it displays it vertically):
>>> pattern(1)
0
1
0
This makes me think that the recursive code itself is correct (plus I confirmed it was with the source provided by the book's website, and with the errata sheet). I am not sure, however, why the print statement isn't printing the output as the functions run, if the end parameter is included. Any help would be greatly appreciated.
The print function doesn't always flush the output. You should flush it explicitly:
import sys
def pattern(n):
'prints the nth pattern'
if n == 0: # base case
print(0, end=' ')
else: #recursive step: n > 0
pattern(n-1) # print n-1st pattern
print(n, end=' ') # print n
pattern(n-1) # print n-1st pattern
sys.stdout.flush()
Note that on python3.3 print has a new keyword argument flush that you can use to forcibly flush the output(and thus avoid using sys.stdout.flush).
On a general note I'd decouple the output from the pattern, doing, for example:
def gen_pattern(n):
if n == 0:
yield 0
else:
for elem in gen_pattern(n-1):
yield elem
yield n
for elem in gen_pattern(n-1):
yield elem
def print_pattern(n):
for elem in gen_pattern(n):
print(elem, end=' ')
sys.stdout.flush()
This makes the code more flexible and reusable, and has the advantage of calling flush only once, or you could also call it once every x elements(actually I believe print already does this. It flushes if trying to write many characters on the screen).
In python3.3 the code could be simplified a little:
def gen_pattern(n):
if n == 0:
yield 0
else:
yield from gen_pattern(n-1)
yield n
yield from gen_pattern(n-1)
The reason is that when end is used with some value other than a "\n" then the print function accumulates the whole value and prints the output only when a newline is to be printed or the loop is over.
See the difference in these two programs:
In [17]: for x in range(5):
print(x,end=" ")
if x==3:
print(end="\n")
sleep(2)
....:
0 1 2 3 #first this is printed
4 #and then after a while this line is printed
In [18]: for x in range(5):
print(x,end=" ")
if x==3:
print(end="\t")
sleep(2)
....:
0 1 2 3 4 #whole line is printed at once