How to convert this while loop to for loop - python

Hello, I am fairly new to python and wondering how to convert this while loop to a for loop. I am not sure how to keep looping the inputs so it keeps asking Enter a line until GO and then say Next until STOP then display the count of lines.
def keyboard():
"""Repeatedly reads lines from standard input until a line is read that
begins with the 2 characters "GO". Then a prompt Next: , until a line is
read that begins with the 4 characters "STOP". The program then prints a
count of the number of lines between the GO line and the STOP line (but
not including them in the count) and exits."""
line = input("Enter a line: ")
flag = False
count = 0
while(line[:4] != "STOP"):
if (line[:2] == "GO"):
flag = True
if flag:
line = input("Next: ")
count += 1
else:
line = input("Enter a line: ")
print(f"Counted {count-1} lines")
keyboard()
With these inputs:
ignore me
and me
GO GO GO!
I'm an important line
So am I
Me too!
STOP now please
I shouldn't even be read let alone printed
Nor me
Should display/result in:
Enter a line: ignore me
Enter a line: and me
Enter a line: GO GO GO!
Next: I'm an important line
Next: So am I
Next: Me too!
Next: STOP now please
Counted 3 lines

You just need an infinity for loop which is what while True essentially is.
This answer has it: Infinite for loops possible in Python?
#int will never get to 1
for _ in iter(int, 1):
pass
So just replace your while loop with the above and add a break condition.
def keyboard():
"""Repeatedly reads lines from standard input until a line is read that
begins with the 2 characters "GO". Then a prompt Next: , until a line is
read that begins with the 4 characters "STOP". The program then prints a
count of the number of lines between the GO line and the STOP line (but
not including them in the count) and exits."""
line = input("Enter a line: ")
flag = False
count = 0
for _ in iter(int, 1):
if line[:4] == "STOP":
break
if (line[:2] == "GO"):
flag = True
if flag:
line = input("Next: ")
count += 1
else:
line = input("Enter a line: ")
print(f"Counted {count-1} lines")
keyboard()

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

Working with printing a certain amount of line in a file

I am trying to achieve:
User input word, and it outputs how many lines contain that word also sees it up to the first ten such lines. If no lines has the words, then your program must output Not found.
My code so far:
sentences = []
with open("txt.txt") as file:
for line in file:
words = line.split()
words_count += len(words)
if len(words) > len(maxlines.split()):
maxlines = line
sentences.append(line)
word = input("Enter word: ")
count = 0
for line in sentences:
if word in line:
print(line)
count += 1
print(count, "lines contain", word)
if count == 0:
print("Not found.")
How would I only print first 10 line regardless the amount of lines
Thank you!
If you want to iterate 10 times (old style, not pythonic at all)
index = 0
for line in file:
if index >= 10:
break
# do stuff 10 times
index += 1
Without using break, just put the stuff inside the condition. Notice that the loop will continue iterating, so this is not really a smart solution.
index = 0
for line in file:
if index < 10:
# do stuff 10 times
index += 1
However this is not pythonic at all. the way you should do it in python is using range.
for _ in range(10):
# do stuff 10 times
_ means you don't care about the index and just want to repeat 10 times.
If you want to iterate over file and keeping the index (line number) you can use enumerate
for lineNumber, line in enumerate(file):
if lineNumber >= 10:
break
# do stuff 10 times
Finally as#jrd1 suggested, you can actually read all the file and then only slice the part that you want, in your case
sentences[:10] # will give you the 10 first sentences (lines)
just change your code like this, it should help:
for line in sentences:
if word in line:
if count < 10: print(line) # <--------
count += 1

why is my code returning 0 even though word exists in file

So this is a code of me trying to find a word a user inputs and look up how many lines contain the word and if no lines contain the word output not found however when i input a word that I know exist in the file it returns 0 and not only is the word in the file it doesn't even output not found like I want it to. (here is my code)
response = input('Please enter words: ')
letters = response.split()
count = 0
with open("alice.txt", "r", encoding="utf-8") as program:
for line in program:
if letters in line:
count += 1
if(count < 1):
print("not found")
print(count)
What you're doing isn't gonna work the split function returns a list of strings and you're checking that list against a single string.
Is this what you wanted to do?
response = input("Please enter a word: ")
count = 0
with open("alice.txt", 'r') as program:
for line in program:
if response in line:
count += 1
if count == 0:
print("not found")
print(count)
You dont need the split function and the place of if condition is wrong in your code. Please refer below code.
response = input('Please enter word: ')
count = 0
with open("alice.txt", "r", encoding="utf-8") as program:
for line in program:
if response in line:
count += 1
if count == 0:
print('Not found')
else:
print(count)
You had an issue with opening the txt file as a single line, and not as a list of the individual lines.
Adding ".readlines()" can fix this issue!
I also went ahead and set the individual lines as 'line', where I then search for the input word in the new 'line' variable.
response = input('Please enter words: ')
letters = response.split()
count = 0
foo = open(
"alice.txt", "r",
encoding="utf-8").readlines()
for line in foo:
for word in letters:
if word in line:
count += 1
if(count < 1):
print("not found")
else:
print(count)

Why is my python word counting program not working?

i'm doing a python course and one of the questions asks me to write a program that counts words like this:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 2
witch 1
The code i have so far is:
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
line = input('Enter line: ')
for word in sorted(occurences):
print(word, occurences[word])
But when I run this code, it either tells me every word occured only once or some other strange output. Thanks for the help!
Here is an example of it not working:
Enter line: test test test
Enter line: one two test
Enter line: one
Enter line:
test 3
This is the output i get while the expected output is:
test 4
two 1
one 2
Your input inside for loop is causing the problem, please try this:
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
print( m)
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
print(occurences)
line = input('Enter line: ')
for word in sorted(occurences):
print(word, occurences[word])
By resetting the input inside the for loop, you are asking for new input after the first word is counted, and ignoring the subsequent words in the string.
When i ran the code i got no output at all, this is because you have a infinite loop by asking the user for another line at the end of the "While" loop, which cause it to do indefinitely.
To match what you were doing before I've changed your code a tiny bit
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
break ## Once the word has been put into occurences it breaks
## so that the next loop can run
for word in sorted(occurences):
print(word, occurences[word])
if you want it to go forever until the user quits the program then you would do this:
while True:
occurences = {}
line = input('Enter line: ')
while line:
m = line.split()
for i in m:
if i in occurences:
occurences[i] += 1
else:
occurences[i] = 1
break
for word in sorted(occurences):
print(word, occurences[word])

Python textwrap and Reset count after everyline

Hello everyone i have an issue with this problem, the problem is i need to reset the count after every line in the file, i put a comment so you can see where i want to reset the count.
The program is suppose to cut each line after every specified lineLength.
def insert_newlines(string, afterEvery_char):
lines = []
for i in range(0, len(string), afterEvery_char):
lines.append(string[i:i+afterEvery_char])
string[:afterEvery_char] #i want to reset here to the beginning of every line to start count over
print('\n'.join(lines))
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r')
file = openFile.read()
lineLength = int(input("enter a number between 10 & 20: "))
while (lineLength < 10) or (lineLength > 20) :
print("Invalid input, please try again...")
lineLength = int(input("enter a number between 10 & 20: "))
print("\nYour file contains the following text: \n" + file + "\n\n") # Prints original File to screen
print("Here is your output formated to a max of", lineLength, "characters per line: ")
insert_newlines(file, lineLength)
main()
Ex. If a file has 3 lines like this with each line having 20 chars
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg
after the lines are cut it should look like this
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
i want to RESET the count after every line in the file.
I'm not sure I understand your problem, but from your comments it appears you simply want to cut the input string (file) to lines lineLength long. That is already done in your insert_newlines(), no need for the line with comment there.
However, if you want to output lines meaning strings ending with newline char that should be no more than lineLength long, then you could simply read the file like this:
lines = []
while True:
line = openFile.readline(lineLength)
if not line:
break
if line[-1] != '\n':
line += '\n'
lines.append(line)
print(''.join(lines))
or alternatively:
lines = []
while True:
line = openFile.readline(lineLength)
if not line:
break
lines.append(line.rstrip('\n'))
print('\n'.join(lines))
I don't understand the issue here, the code seems to work just fine:
def insert_newlines(string, afterEvery_char):
lines = []
# if len(string) is 100 and afterEvery_char is 10
# then i will be equal to 0, 10, 20, ... 90
# in lines we'll have [string[0:10], ..., string[90:100]] (ie the entire string)
for i in range(0, len(string), afterEvery_char):
lines.append(string[i:i+afterEvery_char])
# resetting i here won't have any effect whatsoever
print('\n'.join(lines))
>>> insert_newlines('Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\n..', 10)
Beautiful
is better
than ugly.
Explicit
is better
than impli
cit.
Simpl
e is bette
r than com
plex.
..
isn't that what you want?

Categories