Skip to content

Python Language Practice

PYTHON QUEST

Explore Python code

Practice Python fundamentals with single-line code exercises.

  sandbox / python

Enter one line of code and press Enter to see simulated output.

Complete code examples

The examples below are for reading and copying; they cannot be run in the simulated terminal above. Each is a standalone Python 3 program that can be saved as example.py and run with python3 example.py.

Fibonacci sequence: loops and functions

def fibonacci(n):
    result = []
    a, b = 0, 1
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result


if __name__ == "__main__":
    print(fibonacci(7))

Output: [0, 1, 1, 2, 3, 5, 8]

Word frequency: dictionaries and loops

def count_words(text):
    counts = {}
    for word in text.lower().split():
        counts[word] = counts.get(word, 0) + 1
    return counts


if __name__ == "__main__":
    counts = count_words("Go Python go")
    for word in sorted(counts):
        print(f"{word}: {counts[word]}")

Output: go: 2 and python: 1, each on its own line.

Parse JSON: exception handling

import json


def main():
    data = '{"name":"web","port":8080}'
    try:
        service = json.loads(data)
        print(f'{service["name"]}: {service["port"]}')
    except (json.JSONDecodeError, KeyError) as error:
        print(f"Parse failed: {error}")


if __name__ == "__main__":
    main()

Output: web: 8080

The Workbench pipeline agent provides a Python environment.

Comments