How do you get Python to detect for no input

后端 未结 5 495
野趣味
野趣味 2020-12-11 07:04

I\'m new to coding in python and I was filling out some code that required a number of inputs. One thing it asked for was for the program to perform an action if the user pr

5条回答
  •  时光取名叫无心
    2020-12-11 07:22

    I know this question is old, but I'm still sharing the solution to your problem as it could be a helpful hand to others. To detect no input in Python, you actually need to detect for "End of File" error. Which is caused when there is no input:
    This can be checked by the following piece of code:

    final=[]
    while True:
        try:
             final.append(input())   #Each input given by the user gets appended to the list "final"
        except EOFError:
             break                   #When no input is given by the user, control moves to this section as "EOFError or End Of File Error is detected"
    

    Hope this helps.

提交回复
热议问题