Syntax Error: Outside a function? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Syntax Error: Outside a function? (/thread-31270.html) |
Syntax Error: Outside a function? - aplusfordao2702 - Dec-01-2020 ordered_list = [2, 4, 6, 8, 10] guess = input('Guess a number: ') for element in ordered_list: if element == guess: return True else: return False Hi! Does anyone know why the code produces a syntax error which says "return true outside a function?" What does outside a function means and how do I solve the error? RE: Syntax Error: Outside a function? - SheeppOSU - Dec-01-2020 return is a builtin method which returns a value from a function. The function is executed and returns a value, here's an example:def add(x, y): return x + yIt takes x and y, then returns their value added together. So they cannot be used outside functions. print(add(3, 6))
RE: Syntax Error: Outside a function? - deanhystad - Dec-01-2020 You cannot use "return" unless outside a function. You have no functions so you cannot use return. You could write a function like this: ordered_list = [2, 4, 6, 8, 10] def guess_in_list(guess, ordered_list): for element in ordered_list: if element == guess: return True else: return False guess = input('Guess a number: ')That wouldn't work at all for many reasons. The first being that input returns a string and your ordered list contains numbers (integers). The second reason being that it only looks at the first element in the list. ordered_list = [2, 4, 6, 8, 10] def guess_in_list(guess, ordered_list): for element in ordered_list: if element == guess: return True return False guess = int(input('Guess a number: ')) print(guess_in_list(guess, ordered_list))That works, but it ignores a useful list operation. You should always work on increasing you familiarity with a programming language. The more you know the better your code. ordered_list = [2, 4, 6, 8, 10] def guess_in_list(guess, ordered_list): return guess in ordered_list guess = int(input('Guess a number: ')) print(guess_in_list(guess, ordered_list))And now that we are down to a one line function there is no reason to have a function. ordered_list = [2, 4, 6, 8, 10] guess = int(input('Guess a number: ')) print(guess in ordered_list)As long as we are at it, why use a variable name like "ordered_list". Variable names should describe the thing they reference, not the thing's type. even_numbers = [2, 4, 6, 8, 10] guess = int(input('Guess a number: ')) if guess in even_numbers: print(guess, 'is an even number in the range 2 to 10') |