python doesn't print in same line with end = '' after number - python

I've made a program that makes a random change to a number every 10th of a second, and I want the new number to be printed in the same line as before. However, it just prints nothing when I add "end = '' " to the print command.
Here's my code:
import random, time
stock = 1000000
while True:
change = random.randint(0, 10)
operation = random.randint(0, 1)
if operation == 0:
stock -= change
else:
stock += operation
print(stock, change, end = ' ')
time.sleep(0.1)

I'm guessing you would want to use
print(stock, change, end = '\r')

add flush=True and sep=' ' in your print function. That will make sure the print dynamically in one line.
e.g
print(stock, change, sep=' ', end='', flush=True)

Related

How to store while loop produced string into variable

I want to store all the "o"'s printed by stdout.write function into a a variable which could be accesable any time
I have tried using len function to break loop once it reaches certain amount of strings, but no luck
import time
import sys
while True:
sys.stdout.write("o")
sys.stdout.flush()
time.sleep(0.05)
Very simply, you can add them to a string, one at a time:
record = ""
while True:
sys.stdout.write("o")
sys.stdout.flush()
record += 'o'
time.sleep(0.05)
A slightly faster way is to count the quantity written, and then produce your desired string:
count = 0
while True:
sys.stdout.write("o")
sys.stdout.flush()
count += 1
time.sleep(0.05)
# Insert your exit condition
record = 'o' * count
Keep on appending values to a string. Check the length and break when desired.
import time
import sys
data = ""
while True:
temp = "o"
data += temp
sys.stdout.write(temp)
sys.stdout.flush()
time.sleep(0.05)
if(len(data)==10):
break;
You could keep track of the number of O's in a separate variable:
number_of_os = 0
while True:
sys.stdout.write("o")
sys.stdout.flush()
number_of_os += 1
if number_of_os >= 100:
break
time.sleep(0.05)

How do I print just the final output of the index in a for loop?

I want to print just the last line that I get from my for the for statement. For example a random string is generated and it prints as so.
e
ej
ejb
ejbG
ejbGl
I want it to just print out ejbGl. If I take the print(easy_input) out of the loop it will print ejbGl, but I need that to stay in the loop so that I can used it for the if statements and for the user to see the word they have to type. I am not allowed to share the cse231_random, so this might make this difficult to find a solution.
import string
import random
import time
from cse231_random import randint
ALPHABET_EASY = string.ascii_letters
ALPHABET = string.ascii_letters + string.punctuation
easy_str = ""
length=random.randint(3, 5)
for i in range(length):
index=randint(0, len(ALPHABET_EASY))
easy_str += ALPHABET_EASY[index]
print(easy_str)
start= time.time()
easy_input=input("\nEnter this string:")
stop= time.time()
easy_input=easy_input.replace(" ", "")
easy_input=easy_input
if stop-start>10:
print("Oops! Too much time.")
continue
elif easy_input.lower()==easy_str.lower():
print("Good job! You spent {} of 10 seconds entering string [{}][{}]".format(stop- start,easy_str,easy_input))
continue
elif easy_input.lower()!=easy_str.lower():
print("Incorrect.")
continue

Print multiple lines in place

for index in range(0, len(order_of_fruits)):
maze[prevY][prevX] = ' '
curr = order_of_fruits[index]
maze[curr[1]][curr[0]] = 'P'
prevX = curr[0]
prevY = curr[1]
result_maze = ""
for i in range(len(maze)):
for j in range(len(maze[0])):
result_maze = result_maze + maze[i][j]
result_maze = result_maze + '\n'
animation.append(result_maze)
#animate
for index in range(0, len(animation)):
time.sleep(0.2)
sys.stdout.write("\r" + str(animation[index]))
sys.stdout.flush()
Hi, my problem is that I have a two-dimentionay array whose condition will update. Then I convert each updated array to a string and append each string to a list which are used to print in the console. Now I want print the changing condition of this maze which have already been converted to string in place. I used the "\r" and flush but it does not work. I guess this might because I have "\n" in each of my string. So is there any way that I can print the series of maze in console in place? So the result looks like only one maze appears on the console whose condition will update every 0.2?
Thanks!
"\r" maybe put in the end of line.
import time
for index in range(0, len(animation)):
sys.stdout.write(str(animation[index]) + "\r")
sys.stdout.flush()
time.sleep(0.2)
You might consider using the curses module. This program updates the screen, waits 0.2 seconds, and updates the screen again:
from curses import wrapper
import time
def main(stdscr):
stdscr.clear()
for i in range(5):
for y in range(5):
for x in range(5):
stdscr.addstr(y, x, chr(ord('1')+i))
stdscr.refresh()
time.sleep(0.2)
stdscr.getkey()
wrapper(main)

How to let user end program and shift list

Im trying to make an encryption program
def intro():
msg = input("Enter the message you wish to encrypt: ")
return msg
def shift(msg):
alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
rotate = int(input("The level of the encryption?: "))
text = ""
for ch in msg:
if ch == " " or ch == ".":
pass
elif msg == "$":
print("nah")
else:
index = alpha.index(ch)
newindex = index + rotate
new= alpha[newindex]
text += new
return text
def start():
msg = intro()
text = shift(msg)
print("Your encryptions is: " + text)
start()
I can't figure out a way to loop the list without getting an index out of range error. For example, if you put "z" it will shift to an "a". I also need for my program to loop till user inputs to end it. I just started coding in python a few months ago so any help will be appreciated!beginner
All you need to do is add this line
newindex %= len(alpha)
Detailed Change (with context)
index = alpha.index(ch)
newindex = index + rotate
new= alpha[newindex]
text += new
to
index = alpha.index(ch)
newindex = index + rotate
newindex %= len(alpha) # <--- this is the new line
new= alpha[newindex]
text += new
This will automatically make the new index loop so it never goes past the end!
Working example
>> Enter the message you wish to encrypt: 'xyz'
>> The level of the encryption?: 2
>> Your encryptions is: zab
Since your code is running fine, I can tell you about some techniques you can work on to get the functionality you want.
To get an array that loops around, you can use a mod system. For example 8 mod 3 = 2 and it would be coded remainder = 8 % 3. If you had a mod size 26, i.e. the alphabet, you could take the remainder of the total number and use it as an index in your alphabet list. This would cycle around when the total number is greater than 26 and begin again at a.
To get the program to end on user input, you can use a variety of methods such as keyboard interrupts, recognizing certain commands such as ctrl-c or whole words. Here is a start from a previous stackoverflow question. How to kill a while loop with a keystroke?
use the modulus operator to wrap the index around when it's outside the list length:
newindex = (index + rotate) % len(alpha)
To repeat, use a while True: loop, and use break to end it.
def start():
while True:
msg = intro()
if msg == '':
break
text = shift(msg)
print("Your encryptions is: " + text)
This will end when the user inputs an empty line.

Loop Issue with Local Variable

I'm using Python (3.x) to create a simple program for an assignment. It takes a multiline input, and if there is more than one consecutive whitespace it strips them out and replaces it with one whitespace. [That's the easy part.] It must also print the value of the most consecutive whitespaces in the entire input.
Example:
input = ("This is the input.")
Should print:
This is the input.
3
My code is below:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
I understand that this is probably horribly inefficient, but it seems to almost work. My issue is this: I would like to, once the loop is finished appending to all_lines_max, print the largest value of that list. However, there doesn't seem to be a way to print the max of that list without doing it on every line, if that makes sense. Any ideas on my convoluted code?
Just print the max of all_line_max, right where you currently print the whole list:
print(max(all_line_max))
but leave it at the top level (so dedent once):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
and remove the print(z) call, which prints the maximum whitespace count per line.
Your maxspaces() function adds count_max to your counts list each time a space is found; not the most efficient method. You don't even need to keep a list there; count_max needs to be moved out of the loop and will then correctly reflect the maximum space count. You also don't have to turn the sentence into a list, you can directly loop over a string:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count

Categories