简体   繁体   中英

python sys.stdin for loop not working

I am trying to write a simple program that will read from keyboard as sys.stdin.readline()

I am trying to do it in a 'for' loop as

import sys
for line in sys.stdin.readline().strip("\n"):
if(line == 'stop'):
    break
print(line)

Problem is 1) The for loop is not executing. It exits after first input 2) the if-statement is not getting hit when input is stop 3)if I input "hi" and hit ctrl+DI see output as "H" "I"

I can achieve my goal by a while loop as shown below BUT how to do it in For loop ?

 import sys
 def readfromconsole():
new_list = []
while True:
    line = sys.stdin.readline().rstrip("\n")
    if(line == 'enough'):
        break
    else:

        new_list.append(line)
print(new_list)
return
print("Welcome")
print("please enter your input, enough to stop")
readfromconsole()

It stops after the first interation because you are assigning the value being iterated over in the definition of the for loop. You can see this by doing sys.stdin.readline() in the interpreter. This means your loop is equivalent to

for line in <first entered line>:
    do things

In your while loop, it will keep asking for more inputs, and so your code works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM