Codee
Codee

Reputation: 1

Python function calling

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

Upvotes: 0

Views: 45

Answers (3)

TigerhawkT3
TigerhawkT3

Reputation: 49318

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.

Upvotes: 1

Sayali Sonawane
Sayali Sonawane

Reputation: 12599

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.

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60944

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 

Upvotes: 1

Related Questions