I would like to make a program that will print out number values. I want it to display the number, then replace it with another number. A little like this:
val = 0
for looper in range(1, 10):
val += 1
print (val)
#Code to replace old number to new number
Thanks for helping!
If you want in-place update of the number, you can use \r.
import sys
val = 0
for looper in range(1, 10):
val += 1
sys.stdout.write("\r%d" % (val))
sys.stdout.flush()
time.sleep(1) # sleep added so that you can see the effect
Seems like you're looking for something to replace output in sys.stdout.
This is limited without using external libraries but you can do something like this:
import sys
import time
for number in xrange(10):
# put number in 'stdout'
sys.stdout.write(str(number))
# empty stdout (by default it waits for a new line)
sys.stdout.flush()
# display the number for some time
time.sleep(1)
# go back to beginning of input to override existing output
sys.stdout.write('\r')
I think you are taking about carriage return
use "\r" this with time.sleep(ms)
On Python 3, #Teemu Kurppa's answer could be written as:
import time
for i in range(1, 11):
print(i, end='\r', flush=True)
time.sleep(1)
Related
a = 1
for i in range(5):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button").click()
sleep(1)
I want to increase the 1 in div[1] by 1+ every loop, but how can i do that?
i thought i need to add a value, do "+a+" and last of all a "a = a + 1" to increase the value every time, but it didnt worked.
a = 1
for i in range(5):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+a+"]/div[3]/button").click()
a = a + 1
sleep(1)
for i in range(1,6):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+str(i)+"]/div[3]/button").click()
sleep(1)
you don't need 2 variables, just one variable i in the loop, convert it to string with str() and add it to where you need it, pretty simple. the value of i increases for every iteration of the loop going from 1 to 5 doing exactly what you need.
alternatively to Elyes' answer, you can use the 'global' keyword at the top of your function then a should increment 'correctly'.
You don't really need two variables for this unless you are going to use the second variable for something. However, look at the following code and it will show you that both i and a will give you the same result:
from time import sleep
a = 1
for i in range(1, 6):
path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=i)
print(path, 'using i')
path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=a)
a += 1
print(path, 'using a')
sleep(1)
Result:
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using a
You can read up on range here
So what im trying to do is printing several data with """ """ my Question is if its possible that i can hold this without python printing it again and again im using the sys.stdout.write func with "\r" at the end but in the Console its still moving down. Does Somebody have an idea how to it with """ """ or another method?(Im using Python 2.7)
Thats not really what i want i want the stuff thats in the """ """ to be not moving in the console so that its not printed every time again want to stay in one place like this and not like this
In python 2 you can simply add comma to end of the statement to avoid adding "\n" to output.
print "Hello",
print "world",
The output will be Hello world.
Update:
Look here to read about escape codes.
Made a simple example for you:
import time
template = """
Line 1: [%d]
Line 2: [%d]
"""
prev_line_char = "\033[F"
k = 3
m = 4
while True:
print template % (k, m)
k += 1
m += 3
time.sleep(1)
for i in range(4):
print prev_line_char,
I'm trying to increase the count of an integer given that an if statement returns true. However, when this program is ran it always prints 0.I want n to increase to 1 the first time the program is ran. To 2 the second time and so on.
I know functions, classes and modules you can use the global command, to go outside it, but this doesn't work with an if statement.
n = 0
print(n)
if True:
n += 1
Based on the comments of the previous answer, do you want something like this:
n = 0
while True:
if True: #Replace True with any other condition you like.
print(n)
n+=1
EDIT:
Based on the comments by OP on this answer, what he wants is for the data to persist or in more precise words the variable n to persist (Or keep it's new modified value) between multiple runs times.
So the code for that goes as(Assuming Python3.x):
try:
file = open('count.txt','r')
n = int(file.read())
file.close()
except IOError:
file = open('count.txt','w')
file.write('1')
file.close()
n = 1
print(n)
n += 1
with open('count.txt','w') as file:
file.write(str(n))
print("Now the variable n persists and is incremented every time.")
#Do what you want to do further, the value of n will increase every time you run the program
NOTE:
There are many methods of object serialization and the above example is one of the simplest, you can use dedicated object serialization modules like pickle and many others.
If you want it to work with if statement only. I think you need to put in a function and make to call itself which we would call it recursion.
def increment():
n=0
if True:
n+=1
print(n)
increment()
increment()
Note: in this solution, it would run infinitely.
Also you can use while loop or for loop as well.
When you rerun a program, all data stored in memory is reset. You need to save the variable somewhere outside of the program, on disk.
for an example see How to increment variable every time script is run in Python?
ps. Nowadays you can simply do += with a bool:
a = 1
b = True
a += b # a will be 2
I have two functions prints() and clear(). The function prints() print lines of text and the function clear() delete the printed lines with this method:
def clear():
i = 0
while True:
if(i > globals['l']):
break
else:
sys.stdout.write("\033[F \033[K")
i += 1
where globals['l'] is the number of lines to clear.
Then after the function clear() runs and the lines are cleared, the function prints() run again etc...
I don't understand why the function clear() is clearing only 22 lines of 32 lines. But if I have, for example, 19 lines it is working perfectly. Where is the problem? How can I fix this?
Try this:
def clear(line_count):
sys.stdout.write("\033[F \033[K" * line_count)
sys.stdout.flush()
EDIT:
Works only on Unix systems
You can use:
print("\033c")
Or:
import subprocess
subprocess.call(["printf", "\033c"])
I have a code in python and I need to print 3 results, the first one at the bottom, the third on the top.
The terminal will print in this order:
first
(pause)
second
(pause)
third
I would like to print in this order instead (there will be a pause in between the output):
...third
...second (pause)
first to be printed (then pause)
in order to simulate this I'm using this sequence of print statement:
from time import sleep
print '1'
sleep(1)
print '2'
print '1'
sleep(1)
print '3'
print '2'
print '1'
This bottom up printing should be only used specifically for this 3 line output and not globally for all the output.
Is that possible? Thank you
UPDATE:
It seems that the only library I can effectively use for modifying the newline order of the terminal is curses.
I will give it a try. Thank you.
I think you want to "overwrite" the print outputs for every successive run. If newlines are not a hard constraint, you can do something like this:
import sys
import time
for i in range(3):
sys.stdout.write('\r' + ','.join([str(a) for a in range(i+1, 0, -1)]))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\n')
This will first print 1, wait for a second, overwrite the 1 with 2,1, wait for a second and then overwrite the 2,1 with 3,2,1, wait for a second and exit.
The interesting portion is the use of the \r in the output string - this is the Unix carriage return which causes the stdout file pointer in terminals to move to the leftmost position. Now that the pointer is located at the left-most position, we then print the next set of characters in effect overwriting the previous output.
I use sys.stdout.write to avoid the implicit newline or space that print adds. The range is written in this way to generate a reversed list of numbers to print. The flush is needed to force the characters to be flushed to the output.
This only works as long as the output is on a single line - multi-line outputs like in your example will not work with this method. If you must have multi-line outputs, the curses library is your best bet.
Examples :
results = ["1","2","3"]
print "\n".join(results)
1
2
3
print "\n".join(results[::-1])
3
2
1
Yes it is possible. Please post any code that you are stuck with so that people can help you faster. You can use reversed(), a python built-in to reverse any iterable you are trying to print.
For example:
list = ['1', '2', '3']
for item in list:
print item
# You get
# 1
# 2
# 3
Now if you just want to reverse this order of printing you can do something like this:
for item in reversed(list):
print item
# You get
# 3
# 2
# 1
Hope this helps.