%{ #include <stdio.h> #include <stdlib.h> #include <string.h> int line_num = 1; int error_count = 0; int indent_level = 0; int paren_count = 0; int brace_count = 0; int bracket_count = 0; void print_token(const char *type, const char *lexeme) { printf("Line %d: \t%-30s \t%s\n", line_num, type, lexeme); } void print_error(const char *message, const char *lexeme) { printf("Line %d: \tERROR: %-30s \t%s\n", line_num, message, lexeme); error_count++; } %} %option noyywrap DIGIT [0-9] LETTER [a-zA-Z_] ALPHANUM {LETTER}|{DIGIT} ID {LETTER}{ALPHANUM}* INT_NUM {DIGIT}+ FLOAT_NUM {DIGIT}*\.{DIGIT}+([eE][-+]?{DIGIT}+)? HEX_NUM 0[xX][0-9a-fA-F]+ OCT_NUM 0[oO][0-7]+ BIN_NUM 0[bB][01]+ COMPLEX_NUM ({FLOAT_NUM}|{INT_NUM})[jJ] STRING_SQ \'([^'\\\n]|\\.)*\'? STRING_DQ \"([^"\\\n]|\\.)*\"? F_STRING_SQ f\'([^'\\\n]|\\.)*\'? F_STRING_DQ f\"([^"\\\n]|\\.)*\"? TRIPLE_SQ \'\'\'([^\\]|\\.)*?\'\'\' TRIPLE_DQ \"\"\"([^\\]|\\.)*?\"\"\" F_TRIPLE_SQ f\'\'\'([^\\]|\\.)*?\'\'\' F_TRIPLE_DQ f\"\"\"([^\\]|\\.)*?\"\"\" COMMENT #.* %% {COMMENT} { print_token("COMMENT", yytext); } "def" { print_token("KEYWORD_DEF", yytext); } "class" { print_token("KEYWORD_CLASS", yytext); } "return" { print_token("KEYWORD_RETURN", yytext); } "if" { print_token("KEYWORD_IF", yytext); } "elif" { print_token("KEYWORD_ELIF", yytext); } "else" { print_token("KEYWORD_ELSE", yytext); } "while" { print_token("KEYWORD_WHILE", yytext); } "for" { print_token("KEYWORD_FOR", yytext); } "in" { print_token("KEYWORD_IN", yytext); } "import" { print_token("KEYWORD_IMPORT", yytext); } "from" { print_token("KEYWORD_FROM", yytext); } "as" { print_token("KEYWORD_AS", yytext); } "try" { print_token("KEYWORD_TRY", yytext); } "except" { print_token("KEYWORD_EXCEPT", yytext); } "finally" { print_token("KEYWORD_FINALLY", yytext); } "raise" { print_token("KEYWORD_RAISE", yytext); } "assert" { print_token("KEYWORD_ASSERT", yytext); } "with" { print_token("KEYWORD_WITH", yytext); } "lambda" { print_token("KEYWORD_LAMBDA", yytext); } "pass" { print_token("KEYWORD_PASS", yytext); } "break" { print_token("KEYWORD_BREAK", yytext); } "continue" { print_token("KEYWORD_CONTINUE", yytext); } "del" { print_token("KEYWORD_DEL", yytext); } "global" { print_token("KEYWORD_GLOBAL", yytext); } "nonlocal" { print_token("KEYWORD_NONLOCAL", yytext); } "yield" { print_token("KEYWORD_YIELD", yytext); } "async" { print_token("KEYWORD_ASYNC", yytext); } "await" { print_token("KEYWORD_AWAIT", yytext); } "and" { print_token("KEYWORD_AND", yytext); } "or" { print_token("KEYWORD_OR", yytext); } "not" { print_token("KEYWORD_NOT", yytext); } "is" { print_token("KEYWORD_IS", yytext); } "True" { print_token("BOOLEAN_TRUE", yytext); } "False" { print_token("BOOLEAN_FALSE", yytext); } "None" { print_token("NONE_TYPE", yytext); } "Ellipsis" { print_token("ELLIPSIS_KEYWORD", yytext); } "+" { print_token("OP_PLUS", yytext); } "-" { print_token("OP_MINUS", yytext); } "*" { print_token("OP_MULT", yytext); } "/" { print_token("OP_DIV", yytext); } "%" { print_token("OP_MOD", yytext); } "**" { print_token("OP_POWER", yytext); } "//" { print_token("OP_FLOOR_DIV", yytext); } "=" { print_token("OP_ASSIGN", yytext); } ":=" { print_token("WALRUS_OPERATOR", yytext); } "==" { print_token("OP_EQUALS", yytext); } "!=" { print_token("OP_NOT_EQ", yytext); } ">" { print_token("OP_GT", yytext); } "<" { print_token("OP_LT", yytext); } ">=" { print_token("OP_GTE", yytext); } "<=" { print_token("OP_LTE", yytext); } "+=" { print_token("OP_PLUS_ASSIGN", yytext); } "-=" { print_token("OP_MINUS_ASSIGN", yytext); } "*=" { print_token("OP_MULT_ASSIGN", yytext); } "/=" { print_token("OP_DIV_ASSIGN", yytext); } "%=" { print_token("OP_MOD_ASSIGN", yytext); } "**=" { print_token("OP_POWER_ASSIGN", yytext); } "//=" { print_token("OP_FLOOR_DIV_ASSIGN", yytext); } "&" { print_token("OP_BIT_AND", yytext); } "|" { print_token("OP_BIT_OR", yytext); } "^" { print_token("OP_BIT_XOR", yytext); } "~" { print_token("OP_BIT_NOT", yytext); } "<<" { print_token("OP_LSHIFT", yytext); } ">>" { print_token("OP_RSHIFT", yytext); } "&=" { print_token("OP_BIT_AND_ASSIGN", yytext); } "|=" { print_token("OP_BIT_OR_ASSIGN", yytext); } "^=" { print_token("OP_BIT_XOR_ASSIGN", yytext); } "<<=" { print_token("OP_LSHIFT_ASSIGN", yytext); } ">>=" { print_token("OP_RSHIFT_ASSIGN", yytext); } "(" { paren_count++; print_token("LPAREN", yytext); } ")" { paren_count--; print_token("RPAREN", yytext); } "[" { bracket_count++; print_token("LBRACKET", yytext); } "]" { bracket_count--; print_token("RBRACKET", yytext); } "{" { brace_count++; print_token("LBRACE", yytext); } "}" { brace_count--; print_token("RBRACE", yytext); } ":" { print_token("COLON", yytext); } "," { print_token("COMMA", yytext); } "." { print_token("DOT", yytext); } "..." { print_token("ELLIPSIS", yytext); } ";" { print_token("SEMICOLON", yytext); } "@" { print_token("DECORATOR", yytext); } "->" { print_token("ARROW", yytext); } {F_TRIPLE_SQ} { print_token("F_TRIPLE_STRING_LITERAL", yytext); } {F_TRIPLE_DQ} { print_token("F_TRIPLE_STRING_LITERAL", yytext); } {F_STRING_SQ} { if (yytext[yyleng-1] == '\'') { print_token("F_STRING_LITERAL", yytext); } else { print_error("Unclosed f-string literal", yytext); } } {F_STRING_DQ} { if (yytext[yyleng-1] == '\"') { print_token("F_STRING_LITERAL", yytext); } else { print_error("Unclosed f-string literal", yytext); } } {TRIPLE_SQ} { print_token("TRIPLE_STRING_LITERAL", yytext); } {TRIPLE_DQ} { print_token("TRIPLE_STRING_LITERAL", yytext); } {STRING_SQ} { if (yytext[yyleng-1] == '\'') { print_token("STRING_LITERAL", yytext); } else { print_error("Unclosed string literal", yytext); } } {STRING_DQ} { if (yytext[yyleng-1] == '\"') { print_token("STRING_LITERAL", yytext); } else { print_error("Unclosed string literal", yytext); } } {BIN_NUM} { print_token("BINARY_LITERAL", yytext); } {OCT_NUM} { print_token("OCTAL_LITERAL", yytext); } {HEX_NUM} { print_token("HEX_LITERAL", yytext); } {COMPLEX_NUM} { print_token("COMPLEX_LITERAL", yytext); } {FLOAT_NUM} { print_token("FLOAT_LITERAL", yytext); } {INT_NUM} { print_token("INT_LITERAL", yytext); } {ID} { print_token("IDENTIFIER", yytext); } \n { line_num++; } [ \t\r]+ { /* Ignore whitespace */ } . { print_error("Unknown character", yytext); } %% int main(int argc, char **argv) { if (argc > 1) { yyin = fopen(argv[1], "r"); if (!yyin) { return 1; } } else { fprintf(stderr, "Usage: %s <input_file.py>\n", argv[0]); fprintf(stderr, "Example: %s test.py\n", argv[0]); return 1; } printf("================================================================================\n"); printf("PYTHON LEXICAL ANALYZER - SUPPORTS ALL FUNCTION TYPES\n"); printf("================================================================================\n"); printf("%-10s %-30s %s\n", "LINE", "TOKEN TYPE", "LEXEME"); printf("--------------------------------------------------------------------------------\n"); yylex(); printf("================================================================================\n"); printf("Analysis complete. Total lines: %d, Errors: %d\n", line_num, error_count); // Check for unbalanced brackets if (paren_count != 0) printf("WARNING: Unbalanced parentheses\n"); if (brace_count != 0) printf("WARNING: Unbalanced braces\n"); if (bracket_count != 0) printf("WARNING: Unbalanced brackets\n"); printf("================================================================================\n"); if (yyin != stdin) { fclose(yyin); } return error_count > 0 ? 1 : 0; } int yywrap(void) { return 1; }
# =============================================================================
# COMPREHENSIVE PYTHON TEST FILE - ALL LANGUAGE FEATURES
# =============================================================================
# -------------------------------
# 1. ALL DATA TYPES & LITERALS
# -------------------------------
# Numeric literals
integer_var = 42
float_var = 3.14159
hex_var = 0x1A3F
octal_var = 0o755
binary_var = 0b1101
complex_var = 3 + 4j
scientific_var = 1.23e-4
# String literals
single_quote_str = 'hello world'
double_quote_str = "python programming"
triple_single_str = '''multiline
string with triple
single quotes'''
triple_double_str = """multiline
string with triple
double quotes"""
f_string = f"formatted: {integer_var}"
raw_string = r"raw string \n no escape"
# Boolean and None
true_var = True
false_var = False
none_var = None
# Collections
list_var = [1, 2, 3, "mixed", True]
tuple_var = (1, "hello", 3.14)
dict_var = {"key1": "value1", "key2": 42}
set_var = {1, 2, 3, 2, 1}
# -------------------------------
# 2. ALL KEYWORDS
# -------------------------------
# Function definition keywords
def regular_function(param1, param2):
"""This is a regular function"""
return param1 + param2
# Class definition
class MyClass:
"""A sample class"""
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
@classmethod
def class_method(cls):
return "class method"
@staticmethod
def static_method():
return "static method"
# Control flow keywords
if True:
print("if statement")
elif False:
print("elif statement")
else:
print("else statement")
# Loops
for i in range(5):
print(f"for loop: {i}")
if i == 2:
continue
if i == 4:
break
while True:
print("while loop")
break
# Exception handling
try:
risky_operation = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception:
print("General exception")
finally:
print("Finally block")
# Import keywords
import math
import os as operating_system
from sys import platform
from collections import deque, Counter
# Scope keywords
global global_variable
global_variable = "I'm global"
def scope_test():
local_var = "I'm local"
global global_variable
global_variable = "modified"
# Async keywords
async def async_function():
await some_async_operation()
return "async result"
# Other keywords
lambda_func = lambda x: x * 2
del list_var[0]
# -------------------------------
# 3. ALL OPERATORS
# -------------------------------
# Arithmetic operators
a, b = 10, 3
add = a + b
subtract = a - b
multiply = a * b
divide = a / b
floor_divide = a // b
modulus = a % b
power = a ** b
# Assignment operators
x = 5
x += 3
x -= 2
x *= 4
x /= 2
x //= 3
x %= 5
x **= 2
# Comparison operators
eq = (a == b)
ne = (a != b)
gt = (a > b)
lt = (a < b)
ge = (a >= b)
le = (a <= b)
# Logical operators
and_result = (True and False)
or_result = (True or False)
not_result = (not True)
# Identity operators
is_result = (a is b)
is_not_result = (a is not b)
# Membership operators
in_result = (2 in [1, 2, 3])
not_in_result = (4 not in [1, 2, 3])
# Bitwise operators
bit_and = a & b
bit_or = a | b
bit_xor = a ^ b
bit_not = ~a
left_shift = a << 2
right_shift = a >> 1
# Bitwise assignment
y = 15
y &= 7
y |= 8
y ^= 4
y <<= 1
y >>= 2
# Walrus operator
if (n := len("hello")) > 3:
print(f"Length is {n}")
# -------------------------------
# 4. ALL FUNCTION TYPES
# -------------------------------
# Regular function
def simple_func():
return "simple"
# Function with type hints
def typed_func(name: str, age: int) -> str:
return f"{name} is {age}"
# Function with default parameters
def default_params(a, b=10, c=None):
if c is None:
c = []
return a + b
# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
return args, kwargs
# Generator function
def number_generator(limit):
for i in range(limit):
yield i * 2
# Async function
async def fetch_data(url):
# Simulate async operation
return f"data from {url}"
# Lambda function
square = lambda x: x ** 2
add_lambda = lambda x, y: x + y
# Nested function
def outer_function():
outer_var = "outer"
def inner_function():
return outer_var + " inner"
return inner_function()
# Function with decorators
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@simple_decorator
def decorated_function():
return "decorated"
# Multiple decorators
def decorator1(func):
return func
def decorator2(func):
return func
@decorator1
@decorator2
def multi_decorated():
return "multi-decorated"
# Class-based decorator
class ClassDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
@ClassDecorator
def class_decorated():
return "class decorated"
# -------------------------------
# 5. ALL CONTROL STRUCTURES
# -------------------------------
# If-elif-else chains
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
# Nested if statements
if True:
if False:
pass
else:
print("nested else")
# For loops with different iterables
for char in "hello":
print(char)
for key, value in {"a": 1, "b": 2}.items():
print(f"{key}: {value}")
for i, item in enumerate(["apple", "banana"]):
print(f"{i}: {item}")
# While-else loop
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed")
# Try-except-else-finally
def safe_divide(x, y):
try:
result = x / y
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError as e:
return f"Type error: {e}"
else:
print("Division successful")
return result
finally:
print("Division attempt completed")
# Context manager (with statement)
with open('test.txt', 'w') as f:
f.write("Hello World")
# -------------------------------
# 6. ADVANCED FEATURES
# -------------------------------
# List comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Dictionary comprehensions
square_dict = {x: x**2 for x in range(5)}
# Set comprehensions
unique_chars = {char for char in "hello world"}
# Generator expressions
gen_expr = (x*2 for x in range(5))
# Conditional expressions (ternary)
max_value = a if a > b else b
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
# Extended unpacking
first, *middle, last = [1, 2, 3, 4, 5]
# Format strings with expressions
name = "Alice"
age = 30
formatted = f"{name.upper()} is {age + 5} years old in 5 years"
# Ellipsis
def incomplete():
...
class AbstractClass:
def method(self):
...
# -------------------------------
# 7. COMPLEX EXAMPLES
# -------------------------------
# Complex class with inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Multiple inheritance
class Aquatic:
def swim(self):
return "Swimming"
class Flying:
def fly(self):
return "Flying"
class Duck(Aquatic, Flying):
def __init__(self, name):
self.name = name
# Complex function with everything
@simple_decorator
def complex_example(
required: str,
optional: int = 10,
*args: tuple,
**kwargs: dict
) -> dict:
"""A complex function demonstrating many features"""
# Walrus in comprehension
results = {
key: (value := val * 2)
for key, val in kwargs.items()
if (value := val * 2) > 10
}
# Multiple conditions
if (required and
optional > 5 and
len(args) > 0 and
'important' in kwargs):
# Nested try-except
try:
processed = [
item.upper() if isinstance(item, str) else item * 2
for item in args
if item is not None
]
except Exception as e:
print(f"Error: {e}")
processed = []
finally:
print("Processing complete")
else:
processed = []
return {
'results': results,
'processed': processed,
'metadata': {
'args_count': len(args),
'kwargs_count': len(kwargs)
}
}
# -------------------------------
# 8. MAIN EXECUTION BLOCK
# -------------------------------
if __name__ == "__main__":
# Test all features
# Data types
print("Data types test:")
print(f"Integer: {integer_var}")
print(f"Float: {float_var}")
print(f"String: {single_quote_str}")
print(f"F-string: {f_string}")
# Functions
print("\nFunctions test:")
result = regular_function(5, 3)
print(f"Regular function: {result}")
# Classes
print("\nClasses test:")
dog = Dog("Buddy")
print(dog.speak())
# Control structures
print("\nControl structures test:")
for i in range(3):
if i % 2 == 0:
print(f"Even: {i}")
else:
print(f"Odd: {i}")
# Operators
print("\nOperators test:")
print(f"Arithmetic: {add}, {subtract}, {multiply}")
print(f"Comparison: {eq}, {ne}, {gt}")
print(f"Logical: {and_result}, {or_result}, {not_result}")
# Advanced features
print("\nAdvanced features test:")
print(f"List comprehension: {squares}")
print(f"Dict comprehension: {square_dict}")
print(f"Ternary: {max_value}")
# Complex example
print("\nComplex example test:")
complex_result = complex_example(
"required_value",
15,
"hello", "world",
important=10,
test=5
)
print(f"Complex result: {complex_result}")
print("\n✅ ALL FEATURES TESTED SUCCESSFULLY!")
# -------------------------------
# END OF COMPREHENSIVE TEST FILE
# -------------------------------ERROR: /home/mGMfkS/prog:2:1: Syntax error: Operator expected
ERROR: /home/mGMfkS/prog:229:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: '$runtoplevel'/0: Undefined procedure: program/0
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: '$runtoplevel'/0: Undefined procedure: program/0
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? ERROR: Can't ignore goal at this port
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
Exception: (3) program ? ERROR: '$runtoplevel'/0: Undefined procedure: program/0
Exception: (3) program ? Options:
+: spy -: no spy
/c|e|r|f|u|a goal: find .: repeat find
a: abort A: alternatives
b: break c (ret, space): creep
[depth] d: depth e: exit
f: fail [ndepth] g: goals (backtrace)
h (?): help i: ignore
l: leap L: listing
n: no debug p: print
r: retry s: skip
u: up w: write
m: exception details
C: toggle show context
Exception: (3) program ? ERROR: Unknown option (h for help)
Exception: (3) program ? % Break level 1
ERROR: Syntax error: Operator expected
ERROR: complex_var = 3 +
ERROR: ** here **
ERROR: 4j
scientific_var = 1.23e-4
# String literals
single_quote_str = 'hello world'
double_quote_str = "python programming"
triple_single_str = '''multiline
string with triple
single quotes'''
triple_double_str = """multiline
string with triple
double quotes"""
f_string = f"formatted: {integer_var}"
raw_string = r"raw string \n no escape"
# Boolean and None
true_var = True
false_var = False
none_var = None
# Collections
list_var = [1, 2, 3, "mixed", True]
tuple_var = (1, "hello", 3.14)
dict_var = {"key1": "value1", "key2": 42}
set_var = {1, 2, 3, 2, 1}
# -------------------------------
# 2 .
ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR: KEYWORDS
# -------------------------------
# Function definition keywords
def regular_function(param1, param2):
"""This is a regular function"""
return param1 + param2
# Class definition
class MyClass:
"""A sample class"""
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
@classmethod
def class_method(cls):
return "class method"
@staticmethod
def static_method():
return "static method"
# Control flow keywords
if True:
print("if statement")
elif False:
print("elif statement")
else:
print("else statement")
# Loops
for i in range(5):
print(f"for loop: {i}")
if i == 2:
continue
if i == 4:
break
while True:
print("while loop")
break
# Exception handling
try:
risky_operation = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception:
print("General exception")
finally:
print("Finally block")
# Import keywords
import math
import os as operating_system
from sys import platform
from collections import deque, Counter
# Scope keywords
global global_variable
global_variable = "I'm global"
def scope_test():
local_var = "I'm local"
global global_variable
global_variable = "modified"
# Async keywords
async def async_function():
await some_async_operation()
return "async result"
# Other keywords
lambda_func = lambda x: x * 2
del list_var[0]
# -------------------------------
# 3 .
ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR: OPERATORS
# -------------------------------
# Arithmetic operators
a, b = 10, 3
add = a + b
subtract = a - b
multiply = a * b
divide = a / b
floor_divide = a // b
modulus = a
power = a ** b
# Assignment operators
x = 5
x += 3
x -= 2
x *= 4
x /= 2
x //= 3
x
x **= 2
# Comparison operators
eq = (a == b)
ne = (a != b)
gt = (a > b)
lt = (a < b)
ge = (a >= b)
le = (a <= b)
# Logical operators
and_result = (True and False)
or_result = (True or False)
not_result = (not True)
# Identity operators
is_result = (a is b)
is_not_result = (a is not b)
# Membership operators
in_result = (2 in [1, 2, 3])
not_in_result = (4 not in [1, 2, 3])
# Bitwise operators
bit_and = a & b
bit_or = a | b
bit_xor = a ^ b
bit_not = ~a
left_shift = a << 2
right_shift = a >> 1
# Bitwise assignment
y = 15
y &= 7
y |= 8
y ^= 4
y <<= 1
y >>= 2
# Walrus operator
if (n := len("hello")) > 3:
print(f"Length is {n}")
# -------------------------------
# 4 .
ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR: FUNCTION TYPES
# -------------------------------
# Regular function
def simple_func():
return "simple"
# Function with type hints
def typed_func(name: str, age: int) -> str:
return f"{name} is {age}"
# Function with default parameters
def default_params(a, b=10, c=None):
if c is None:
c = []
return a + b
# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
return args, kwargs
# Generator function
def number_generator(limit):
for i in range(limit):
yield i * 2
# Async function
async def fetch_data(url):
# Simulate async operation
return f"data from {url}"
# Lambda function
square = lambda x: x ** 2
add_lambda = lambda x, y: x + y
# Nested function
def outer_function():
outer_var = "outer"
def inner_function():
return outer_var + " inner"
return inner_function()
# Function with decorators
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@simple_decorator
def decorated_function():
return "decorated"
# Multiple decorators
def decorator1(func):
return func
def decorator2(func):
return func
@decorator1
@decorator2
def multi_decorated():
return "multi-decorated"
# Class-based decorator
class ClassDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
@ClassDecorator
def class_decorated():
return "class decorated"
# -------------------------------
# 5 .
ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR: CONTROL STRUCTURES
# -------------------------------
# If-elif-else chains
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
# Nested if statements
if True:
if False:
pass
else:
print("nested else")
# For loops with different iterables
for char in "hello":
print(char)
for key, value in {"a": 1, "b": 2}.items():
print(f"{key}: {value}")
for i, item in enumerate(["apple", "banana"]):
print(f"{i}: {item}")
# While-else loop
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed")
# Try-except-else-finally
def safe_divide(x, y):
try:
result = x / y
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError as e:
return f"Type error: {e}"
else:
print("Division successful")
return result
finally:
print("Division attempt completed")
# Context manager (with statement)
with open('test.txt', 'w') as f:
f.write("Hello World")
# -------------------------------
# 6 .
ERROR: Syntax error: Operator expected
ERROR: ADVANCED
ERROR: ** here **
ERROR: FEATURES
# -------------------------------
# List comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x
# Dictionary comprehensions
square_dict = {x: x**2 for x in range(5)}
# Set comprehensions
unique_chars = {char for char in "hello world"}
# Generator expressions
gen_expr = (x*2 for x in range(5))
# Conditional expressions (ternary)
max_value = a if a > b else b
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
# Extended unpacking
first, *middle, last = [1, 2, 3, 4, 5]
# Format strings with expressions
name = "Alice"
age = 30
formatted = f"{name.upper()} is {age + 5} years old in 5 years"
# Ellipsis
def incomplete():
...
class AbstractClass:
def method(self):
...
# -------------------------------
# 7 .
ERROR: Syntax error: Operator expected
ERROR: COMPLEX
ERROR: ** here **
ERROR: EXAMPLES
# -------------------------------
# Complex class with inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Multiple inheritance
class Aquatic:
def swim(self):
return "Swimming"
class Flying:
def fly(self):
return "Flying"
class Duck(Aquatic, Flying):
def __init__(self, name):
self.name = name
# Complex function with everything
@simple_decorator
def complex_example(
required: str,
optional: int = 10,
*args: tuple,
**kwargs: dict
) -> dict:
"""A complex function demonstrating many features"""
# Walrus in comprehension
results = {
key: (value := val * 2)
for key, val in kwargs.items()
if (value := val * 2) > 10
}
# Multiple conditions
if (required and
optional > 5 and
len(args) > 0 and
'important' in kwargs):
# Nested try-except
try:
processed = [
item.upper() if isinstance(item, str) else item * 2
for item in args
if item is not None
]
except Exception as e:
print(f"Error: {e}")
processed = []
finally:
print("Processing complete")
else:
processed = []
return {
'results': results,
'processed': processed,
'metadata': {
'args_count': len(args),
'kwargs_count': len(kwargs)
}
}
# -------------------------------
# 8 .
ERROR: Stream user_input:1006:32 Syntax error: Unexpected end of file
% Exit break level 1
Exception: (3) program ? EOF: exit