0

I'm working on a website called NOWCODER, similar to the Leetcode but a Chinese version.

One of the question is asking for user to input some text(multiple lines) and determine whether the texts that enter are qualified as an appropriate password.

What bothers me is the input()

so I write my code on Jupyter notebook (python 3) as:

# 1st Code

s = [] # get all the input text
while True:
    try:
        lines = input()
        if lines:
            s.append(lines)
        else:
            break

the code works fine in jupyter nootbook but when i copied it to the nowcoder website it doesn't work, it said "no input and output data"

so i modified the code to the following:

# 2nd Code

s = []
while True:
    try:
        s.append(input())
    except:
        break

and it works

The problem is now I tried to execute the 2nd Code in the Jupyter notebook, the while loop never ends and keeps asking for input. I don't know how to fix it or where is the problem.

Also i try re.stdin.readline() and it doenst work on jupyter nootbook, so I want to know if there is some way to make it executable on both the NOWCODER website as well as on the Jupyter notebook

wjandrea
  • 28,235
  • 9
  • 60
  • 81
whateverlx
  • 57
  • 1
  • 1
  • 6
  • 1
    The first code is invalid because the `try` doesn't have an `except` or `finally`. It must be masking an exception if you don't see an error. Otherwise, there's no different between the code. The behavior should be identical. – Carcigenicate Jan 12 '20 at 17:41
  • @Carcigenicate Thank you! I modified the 1st Code and it works great on NOWCODER but the 2nd Code just doesnt work well on jupyter notebook, it wont break the loop, any idea? – whateverlx Jan 12 '20 at 18:13
  • 1
    You don't have any condition that break the loop, you just keep adding empty string to the `s` list. – Amiram Jan 12 '20 at 19:06
  • @Amiram so is there a way to break the loop? – whateverlx Jan 12 '20 at 19:11

1 Answers1

1

The second code is fine, you just need to send an end-of-file signal (EOF), which you can do on Unix/Linux with Ctrl+D and on Windows with Ctrl+Z. Python receives this as an EOFError, which your except clause will catch and break the loop. However, a bare except is bad practice. You should at least change it to except Exception.

That said, you could simplify massively by using fileinput.input to take input.

import fileinput
s = [s.rstrip('\n') for s in fileinput.input()]
wjandrea
  • 28,235
  • 9
  • 60
  • 81