Mr.Fry
Mr.Fry

Reputation: 125

Return outside function error

This is my code and I simply want it to read the input and if it is not empty just return what was inputted.

print "Welcome to translator!"
print "Enter in an english word"
original=raw_input("Enter a word")

if len(original) != 0:
     return original

Upvotes: 2

Views: 163

Answers (2)

Andy_A̷n̷d̷y̷
Andy_A̷n̷d̷y̷

Reputation: 795

From the Python Official Website:

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement is not allowed to include an expression_list. In that context, a bare return indicates that the generator is done and will cause StopIteration to be raised.

Upvotes: 1

Deelaka
Deelaka

Reputation: 13713

You can only return from within a function So that would produce a SyntaxError.

A proper way to achieve what you want is by:

print "Welcome to translator!"
print "Enter in an english word"
original = raw_input("Enter a word")

if original: # Checks if original is not empty
     print original

If you want to return from a function:

print "Welcome to translator!"
print "Enter in an english word"
original=raw_input("Enter a word")

def not_empty(string):
     if string:
        return string

print not_empty(original)

Upvotes: 3

Related Questions