0

I've only started learning Python. If I wrote:

def questions(): 
    sentence= input(" please enter a sentence").split()

How would I end the function If the user didn't input anything and just hit enter

4
  • can you please share your code? Commented Sep 22, 2016 at 16:03
  • The function will end on its own since it is complete after any user input. if sentence == []: print('No user input detected') is something you may be looking for, though. Commented Sep 22, 2016 at 16:05
  • 1
    You could add a return statement if len(sentence) == 0 Commented Sep 22, 2016 at 16:05
  • Which version of Python? 2 or 3? Commented Sep 22, 2016 at 16:10

3 Answers 3

1
def questions():
    sentence= input(" please enter a sentence").split()
    if sentence == []:
        #This is what happens when nothing was entered
    else:
        #This happens when something was entered 
Sign up to request clarification or add additional context in comments.

2 Comments

You could shorten it to if sentence:
Yeah, but I wanted to make it clear that .split() returns a list and not a string.
1

Did you test this? The function will work properly if the user simply hits Enter. The sentence variable would be an empty list. If there was nothing else in the function, it would return None, the default return value. If you wanted to do further processing that requires an actual sentence with content, you can put if not sentence: return after that line.

3 Comments

This fails with SyntaxError: unexpected EOF while parsing in Python 2 btw unless they use raw_input
@roganjosh - That's fine; nobody uses input in Python 2 anyway, and they shouldn't be using Python 2 in the first place. :P I answer based on the current standard, which is Python 3, unless specified otherwise.
Um, I've ended up being stuck in Python 2 so my instinct is to answer along that vein :P But also, many tutorials will work with Python 2 so for beginner questions I would definitely anticipate such things!
0

You can add exception in your code. If you want to raise an exception only on the empty string, you'll need to do that manually:

Example

 try:
    input = raw_input('input: ')
    if int(input):
        ......
except ValueError:
    if not input:
        raise ValueError('empty string')
    else:
        raise ValueError('not int')

try this, both empty string and non-int can be detected.

2 Comments

OP is using python3 :)
@JacobVlijm How do you know that? I didn't get a response to my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.