This question already has answers here:
How to print one character at a time on one line?
(4 answers)
How to make it look like the computer is typing? [duplicate]
(1 answer)
Closed 5 years ago.
I have written this small code in Python. It should print every character in a string with a small sleeptime between them...
import time, sys
def writeText(string, t):
i = 0
while i < len(string):
sys.stdout.write(string[i])
time.sleep(float(t))
i += 1
writeText("Hello World", 0.5)
but it only prints the whole string after 0.5 seconds... I often have this issue but I haven't found a solution yet.
sys.stdout.flush() might solve your problem.
import time, sys
def writeText(string, t):
i = 0
while i < len(string):
sys.stdout.write(string[i])
time.sleep(float(t))
i += 1
sys.stdout.flush()
writeText("Hello World", 0.5)
You should add
sys.stdout.flush()
after writing, to force the output of the text.
Related
This question already has answers here:
python: what does the comma do in += s,?
(1 answer)
In threading.thread, why does args take a comma at the end [duplicate]
(1 answer)
Closed 1 year ago.
Why in this example we must put a comma after the pat and mat argument?
I searched several sites but did not find an answer
import _thread
import turtle
def f(painter):
for i in range(3):
painter.fd(50)
painter.lt(60)
def g(painter):
for i in range(3):
painter.rt(60)
painter.fd(50)
try:
pat=turtle.Turtle()
mat=turtle.Turtle()
mat.seth(180)
_thread.start_new_thread(f,(pat,))
_thread.start_new_thread(g,(mat,))
turtle.done()
except:
pass
Because its a tuple. Writing (pat) or (mat) is evaluated as part of an operation like x * (y + z). Adding the comma allows the runtime to understand you're providing a tuple or an immutable list.
This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Print in one line dynamically [duplicate]
(22 answers)
Closed 3 years ago.
I have a program that has to only print data onto one line.
What can I do to do this.
for i in range(10):
print(i)
Is it possible to print all of this on one line so it prints 0, erases the line, print 2, erases, etc..?
Use print(i,end="\r") to return to the start of the line and overwrite.
for i in range(10):
print(i,end=" ")
this is easiest way to print in one line.
in python 2.x:
from __future__ import print_function
for i in range(10):
print (i, end="")
in python 3.x
for i in range(10):
print (i, end="")
For this specific usecase you can do something like this:
print(*range(10))
And to update each character on the line you will need to use '\r' or the return character, that returns the position of the cursor to the beginning of the line. However, you need to be sure you count in the length of the strings you are printing, otherwise you will be overwriting only part of the string. A full proof solution will be:
import time
maxlen = 0
for i in range(12,-1,-1):
if len(str(i))>maxlen:
maxlen = len(str(i))
print(f'\r{str(i): <{maxlen}}',end = '')
time.sleep(2)
print('')
time part is added so that you can view the change. maxlen computes the maximum length string you are going to print and formats the string accordingly. Note: I have used f'strings, hence it would only work for Python 3.x
This question already has answers here:
How do I check the difference, in seconds, between two dates?
(7 answers)
Closed 4 years ago.
I have a function where I read the time from a file. I put this into a variable. I then subtract this value from the current time which most of the time will give me a value around .
My problem is im not sure how to check if this value which I attach to a variable is greater than say 20 seconds.
def numberchecker():
with open('timelog.txt', 'r') as myfile:
data=myfile.read().replace('\n','')
a = datetime.strptime(data,'%Y-%m-%d %H:%M:%S.%f')
b = datetime.now()
c = b-a (This outputs for example: 0:00:16.657538)
d = (would like this to a number I set for example 25 seconds)
if c > d:
print ("blah blah")
The difference which you're getting is a timedelta object.
You can just use c.seconds to get the seconds.
if c.total_seconds() > datetime.timedelta(seconds=d):
print ("blah blah")
This question already has answers here:
How do I do exponentiation in python? [duplicate]
(3 answers)
Closed 6 years ago.
I am running this little loop on a Jupyter notebook
import time
def time_loop(reps):
start = time.clock()
count = 0
for i in range(reps):
count += 1
return time.clock() - start
time_loop(10000^100)
No matter what I enter as an argument, I seem to always get an output around 0.003
0.0031050000000050204
What is going on?
One guess is that python understands that the result of the loop will simply be count = reps, and quits the loop?
But if I run this instead
import time
import numpy as np
def time_loop(reps):
start = time.clock()
count = 0
for i in range(reps):
count += np.sin(reps)
return time.clock() - start
time_loop(10000^100)
It does take longer as I increase the argument, even though the result of the loop is still quite simply count = reps*sin(reps).
^ is xor and not exponentation:
>>> 10000^100
10100
That's a big number but not like with exponentation: **, that returns:
>>> 10000**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
That also takes a "while" to iterate over.
A good reference for the operators and their precedence is avaiable in the python documentation:
^ - Bitwise XOR
** - Exponentiation
This question already has answers here:
How do I write output in same place on the console?
(9 answers)
Closed 6 years ago.
What I'm trying to code is pretty simple:
I want to print an iteration variable, but I don't want all the lines printed for each loop, I want that will update the previous one.
Example:
for i in range(0,2000):
print 'number is %d', %i
Wrong result:
number is 0
number is 1
number is 2
number is 3
number is 4
number is 5
number is 6
...
...
What I want is:
number is 0
At the second iteration:
number is 1 `(it will replace 0 and I don't want the previous 0 anymore).`
It will be something like updating percentage of something in only one line.
Does a function exist for it in Python?
This will do the trick, and update every 1 second:
import sys
import time
for i in range(0,2000):
sys.stdout.write('\rnumber is %d' %i)
sys.stdout.flush()
time.sleep(1)
You can try something from this thread on clearing the terminal, or something from the one that fuglede posted as duplicated.
The following code worked fine for me in a mac, but if you remove the time.sleep() it will just run so fast that you wont even see the prints.
import time, sys
for i in range(0, 20):
print 'Number is: %d' % i
time.sleep(.1)
sys.stderr.write("\x1b[2J\x1b[H")
What you want is called the Carriage Return, or \r
Use:
for i in range(0,2000):
print "number is %d \r" %i,
The spaces will keep the line clear from prior output.