Reputation: 3
i want to program that take user input line:
, and check that each line is correct or not from a speech.txt
. if the line is correct with line in file it should proceed and ask input again line:
check the line again, if the line is wrong print the correct line, and if the user types LINE!
then print the correct line from file, and print GOOD
when lines finished.
so FAR i have made this program but the last some loops are useless even if the lines in file are finished
f=open('speech.txt')
while True:
userline=input("line: ")
for line in f:
line=line.strip()
if line.lower() == userline.lower():
userline=input("line: ")
elif userline=="LINE!":
print(line)
print("Good!")
break
Upvotes: 0
Views: 2422
Reputation: 17168
It seems to me like you're using more loops than you need. This is how I'd write it, if I understand your constraints correctly.
with open('speech.txt') as f:
for line in f:
line = line
userline = input("line: ")
if userline == 'LINE!':
print(line)
elif userline.strip().lower() == line.strip().lower():
continue # Correct, so go on to the next line of the file
else:
print("Nope! Correct was:")
print(line)
print('FINISHED') # I wouldn't use "GOOD" unless the user gets everything right!
The trick here is the continue
statement. This skips ahead to the next iteration of the loop if the user was correct. To break out of a loop entirely (say, if you wanted to simply stop when the user gets a line wrong), you would use the break
statement.
I don't know what your original while
loop was intended to do, but it wasn't doing anything at all in your code, and you don't need two loops just to go through a file once.
Upvotes: 0
Reputation: 2775
If I understood your question right, this would be what you are looking for:
try:
_input = raw_input
except:
_input = input
with open('a') as a:
for i in a:
line = i.rstrip('\n')
while True:
user = _input("enter line: ")
if user == "LINE!":
print('%s\n' % line)
break
if line == user:
break
print("No! Try again...")
print("Good!")
Upvotes: 2
Reputation: 3752
The short answer is: to stop a loop, use the break statement eg
while True:
q = input("What is your quest? ")
if q == "To seek the holy grail":
break
print("That's not right, try again")
#Program continues.
In your case I would consider thinking about the logic of the loops. You seem to have nested loops unnecessarily. A single for loop through the file should be enough.
Upvotes: 0