Run Python code stored in a string

Run Python code stored in a string

MediumFunction Programs · 13 of 39

Write a Python function that executes Python code stored in a string.

Output
inside exec: 81
81

Approach

  1. exec() runs code; give it a separate namespace dictionary so it cannot touch your variables.

Solution

Python
def run_code(source):    namespace = {}    exec(source, namespace)    return {k: v for k, v in namespace.items() if not k.startswith("__")} code = """def square(x):    return x * xresult = square(9)print("inside exec:", result)"""print(run_code(code)["result"])
Output
inside exec: 81
81

Line by line

Lines 2-3

The code runs inside its own dictionary, which then holds the names it created.

Line 4

Python adds __builtins__ to the namespace, so names starting with __ are filtered out.

Watch out

Never pass text from users or files you do not trust to exec(); it can run any code on your machine.

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Squares of 1 to 10

Squares of 1 to 10

EasyFunction Programs · 12 of 39

Write a Python function that creates and prints a list of the squares of 1 to 10.

Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Approach

  1. Build the list, print it and return it.

Solution

Python
def squares(n=10):    result = [i * i for i in range(1, n + 1)]    print(result)    return result squares()
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Even numbers from a list

Even numbers from a list

EasyFunction Programs · 11 of 39

Write a Python function that returns the even numbers of a list.

Input
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
[2, 4, 6, 8]

Approach

  1. A list comprehension in the return statement.

Solution

Python
def evens(numbers):    return [n for n in numbers if n % 2 == 0] print(evens([1, 2, 3, 4, 5, 6, 7, 8, 9]))
Output
[2, 4, 6, 8]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Prime check function

Prime check function

EasyFunction Programs · 10 of 39

Write a Python function that returns True if a number is prime.

Input
7, 12, 1
Output
[(7, True), (12, False), (1, False)]

Approach

  1. Test divisors up to the square root.

Solution

Python
def is_prime(n):    if n < 2:        return False    for d in range(2, int(n ** 0.5) + 1):        if n % d == 0:            return False    return True print([(n, is_prime(n)) for n in [7, 12, 1]])
Output
[(7, True), (12, False), (1, False)]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Unique elements in order

Unique elements in order

EasyFunction Programs · 9 of 39

Write a Python function that returns a new list with the unique elements of a list, in order.

Input
[2, 2, 3, 1, 4, 4, 4, 4, 4, 6]
Output
[2, 3, 1, 4, 6]

Approach

  1. Append items not yet seen.

Solution

Python
def unique(items):    result = []    for x in items:        if x not in result:            result.append(x)    return result print(unique([2, 2, 3, 1, 4, 4, 4, 4, 4, 6]))
Output
[2, 3, 1, 4, 6]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Is a number in a range?

Is a number in a range?

EasyFunction Programs · 8 of 39

Write a Python function to check whether a number is within a range (inclusive).

Input
7 in 2 to 20; 25 in 2 to 20
Output
7 is in the range
25 is outside the range

Approach

  1. A chained comparison.

Solution

Python
def in_range(n, low, high):    return low <= n <= high for n in [7, 25]:    print(n, "is in the range" if in_range(n, 2, 20) else "is outside the range")
Output
7 is in the range
25 is outside the range

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Reverse a string

Reverse a string

EasyFunction Programs · 7 of 39

Write a Python function to reverse a string.

Input
"Python1234"
Output
4321nohtyP

Approach

  1. Return text[::-1].

Solution

Python
def reverse(text):    return text[::-1] print(reverse("Python1234"))
Output
4321nohtyP

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Product of a list

Product of a list

EasyFunction Programs · 6 of 39

Write a Python function to multiply all the numbers in a list.

Input
[-8, 6, 1, 9, 2]
Output
-864

Approach

  1. Start at 1 and multiply.

Solution

Python
def product(numbers):    result = 1    for n in numbers:        result *= n    return result print(product([-8, 6, 1, 9, 2]))
Output
-864

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Sum of a list

Sum of a list

EasyFunction Programs · 5 of 39

Write a Python function to add up the numbers in a list.

Input
[6, 9, 4, 5, 3]
Output
27

Approach

  1. Loop and add.

Solution

Python
def total(numbers):    result = 0    for n in numbers:        result += n    return result print(total([6, 9, 4, 5, 3]))
Output
27

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Maximum of three numbers

Maximum of three numbers

EasyFunction Programs · 4 of 39

Write a Python function to find the maximum of three numbers.

Input
17, 21, -9
Output
21

Approach

  1. Reuse a two-number max function twice.

Solution

Python
def max_of_two(a, b):    return a if a > b else b def max_of_three(a, b, c):    return max_of_two(a, max_of_two(b, c)) print(max_of_three(17, 21, -9))
Output
21

Line by line

Lines 4-5

Building on a smaller function keeps each one simple.

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs