How to store while loop produced string into variable - python

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)

Related

Take some inputs until 0 encountered, print each word in lowercase and break the loop

Write a program to input the lines of text, print them to the screen after converting them to lowercase. The last line prints the number of input lines.
The program stops when it encounters a line with only zero.
Requirements: use infinite loop and break . statement
here's my code but it's saying Input 9 is empty
a = 1
l = 0
while a != 0:
a = input()
a.lower()
print(a)
l+=1
example inputs
TbH
Rn
ngL
bRb
0
I'd suggest this, it's a combination of these 2 comments, sorry
count = 0
while True:
a = input()
if a == '0':
break
else:
print(a.lower())
count += 1
print(count)
This may accomplish what you are trying to achieve:
def infinite_loop():
while True:
user_input = input('enter a value:\n> ')
if user_input == '0':
break
else:
print(user_input.lower())
if __name__ == '__main__':
infinite_loop()
There a few errors in your original code, here is some suggestions and fixes. This post is try to follow your code as much as it can, and point the changes needed.
Please see the comments and ask if you have any questions.
count = 0 # to count the lines
while w != '0': # input's string
w = input().strip() # get rid of \n space
word = w.lower() # convert to lower case
print(word)
count += 1
# while-loop stops once see '0'
Outputs: (while running)
ABBA
abba
Misssissippi
misssissippi
To-Do
to-do
0
0

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

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)

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

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