本文介绍了你如何让 Python 检测到没有输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 编码的新手,我正在填写一些需要大量输入的代码.它要求的一件事是,如果用户按下回车键并且没有输入任何输入,程序就执行一个操作.我的问题是你如何让 python 来检查它.会不会是:

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 pressed the enter key and did not type in any input. My question is how you would get python to check for that. Would it be:

if input == "":
    #action

或者是别的什么?谢谢你的帮助.

Or is it something else? Thank you for the help.

这是我的代码目前的样子以供参考.

Here is what my code currently looks like for reference.

 try:
     coinN= int(input("Enter next coin: "))

     if coinN == "" and totalcoin == rand:
         print("Congratulations. Your calculations were a success.")
     if coinN == "" and totalcoin < rand:
         print("I'm sorry. You only entered",totalcoin,"cents.")

 except ValueError:
     print("Invalid Input")
 else:
     totalcoin = totalcoin + coinN

推荐答案

我知道这个问题很老了,但我仍在分享您的问题的解决方案,因为它可能对他人有所帮助.要检测 Python 中没有输入,您实际上需要检测文件结尾"错误.这是在没有输入时引起的:
这可以通过以下代码进行检查:

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"

希望这会有所帮助.

这篇关于你如何让 Python 检测到没有输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:01