Spaces:
Running
Running
Initial upload — Legesher native code submission portal
Browse filesFiles changed (15)
- .gitattributes+1
- README.md+52-4
- app.pyAdded+470
- exercises.jsonAdded+170
- references/es.mdAdded+291
- references/ur.mdAdded+294
- references/zh.mdAdded+291
- requirements.txtAdded+14
- wheels/legesher-0.7.3-py3-none-any.whlAdded
- wheels/legesher_core-0.7.3-py3-none-any.whlAdded
- wheels/legesher_i18n-0.7.3-py3-none-any.whlAdded+3
- wheels/legesher_i18n_python_en-0.0.2-py3-none-any.whlAdded
- wheels/legesher_i18n_python_es-0.0.3-py3-none-any.whlAdded
- wheels/legesher_i18n_python_ur-0.0.2-py3-none-any.whlAdded
- wheels/legesher_i18n_python_zh-0.0.4-py3-none-any.whlAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textwheels/legesher_i18n-0.7.3-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
123456789101112---title: Legesher Native Codeemoji: 🌍colorFrom: pinkcolorTo: bluesdk: gradiosdk_version: 6.11.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960---title: Legesher Native Code Submissionemoji: 🌍colorFrom: bluecolorTo: greensdk: gradiosdk_version: 6.11.0app_file: app.pypinned: false---# Native Code Submission PortalA Gradio web app for collecting natively-written Legesher Python code from native speakers of Chinese, Spanish, and Urdu.Part of **Language, Decoded — Expedition Tiny Aya** (Condition 4: Strictly Native Code).---## What this doesContributors open the app, pick an exercise, write their solution in their native language using Legesher, run it to confirm it works, then submit. Submissions are saved to a HuggingFace dataset.The app uses the Legesher Python API (`TokenTranslator`) to transpile native-language code to standard Python for execution — so contributors can see their code actually run in the browser.---## Run locally**Prerequisites:** Python 3.10+```bashcd native-code-submissionpip install -r requirements.txtpython app.py```---## Folder structure```native-code-submission/├── app.py # Main Gradio app├── exercises.json # Exercise prompts (zh/es/ur, tiers 1–3)├── requirements.txt # Python dependencies├── references/ # Legesher keyword reference per language│ ├── zh.md│ ├── es.md│ └── ur.md└── wheels/ # Bundled Legesher wheels (not on PyPI)```---## Related issues- AYA-128 — Exercise design (Done)- AYA-129 — Native code criteria (Done) — [criteria doc](https://linear.app/legesher-research/document/native-code-criteria-qualification-disqualification-and-quality-rubric-5705fc83d6e8)- AYA-127 — Submission flow design (this)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470"""Native Code Submission Portal — Language, Decoded / Expedition Tiny Aya=======================================================================A Gradio app for collecting natively-written Legesher code fromnative speakers of Chinese, Spanish, and Urdu.
Contributors write Python in their native language using Legesher,run it to verify it works, then submit it for research use.
HF Space secrets required: HF_TOKEN — write token for pushing submissions to the dataset repo HF_DATASET_ID — target dataset repo (e.g. "legesher-research/native-code-submissions")"""
import jsonimport loggingimport osimport subprocessimport sysimport tempfileimport uuidfrom datetime import datetime, timezonefrom pathlib import Path
import gradio as gr
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------# Legesher setup# ---------------------------------------------------------------------------
try: from legesher_core import TokenTranslator LEGESHER_OK = True logger.info("Legesher loaded successfully.")except ImportError as e: LEGESHER_OK = False logger.warning(f"Legesher not available: {e}. Run/translate disabled.")
# Cache translators so we don't reload on every button click_translators: dict[str, TokenTranslator] = {}
def _get_native_to_en(lang: str) -> TokenTranslator: if lang not in _translators: en_to_native = TokenTranslator.from_language_pack(lang) _translators[lang] = en_to_native.reverse() return _translators[lang]
# ---------------------------------------------------------------------------# Exercises# ---------------------------------------------------------------------------
EXERCISES_PATH = Path(__file__).parent / "exercises.json"with open(EXERCISES_PATH, encoding="utf-8") as _f: _ALL_EXERCISES: dict = json.load(_f)
TIER_KEYS = ["tier1", "tier2", "tier3"]TIER_LABELS = ["Tier 1 — Basic (10–20 lines)", "Tier 2 — Applied (20–50 lines)", "Tier 3 — Domain (50–100 lines)"]
LANGUAGES = { "zh": "中文 (Chinese)", "es": "Español (Spanish)", "ur": "اردو (Urdu)",}
# Reverse map: display label -> code (handles Gradio 6 returning label instead of value)_LABEL_TO_CODE = {v: k for k, v in LANGUAGES.items()}
# ---------------------------------------------------------------------------# Keyword reference — loaded from REFERENCE.md files per language# ---------------------------------------------------------------------------
_REFERENCES_DIR = Path(__file__).parent / "references"
def load_reference(lang: str) -> str: """Load the Legesher REFERENCE.md for the given language.""" path = _REFERENCES_DIR / f"{lang}.md" if path.exists(): return path.read_text(encoding="utf-8") return f"_Reference file not found for `{lang}`._"
def normalize_lang(lang_input: str) -> str: """Accept either a language code ('ur') or display label ('اردو (Urdu)') and return the code.""" if lang_input in LANGUAGES: return lang_input if lang_input in _LABEL_TO_CODE: return _LABEL_TO_CODE[lang_input] logger.warning(f"Unknown lang input: {lang_input!r}, falling back to zh") return "zh"
def get_exercise_choices(lang: str, tier_idx: int) -> list[str]: tier_key = TIER_KEYS[tier_idx] exercises = _ALL_EXERCISES.get(lang, {}).get(tier_key, []) return [ex["title"] for ex in exercises]
def get_exercise(lang: str, tier_idx: int, title: str) -> dict | None: tier_key = TIER_KEYS[tier_idx] for ex in _ALL_EXERCISES.get(lang, {}).get(tier_key, []): if ex["title"] == title: return ex return None
# ---------------------------------------------------------------------------# HuggingFace dataset submission# ---------------------------------------------------------------------------
HF_TOKEN = os.environ.get("HF_TOKEN", "")HF_DATASET_ID = os.environ.get("HF_DATASET_ID", "legesher-research/native-code-submissions")
def push_submission(row: dict) -> bool: """Push a single submission row to the HF dataset as a JSONL entry.""" if not HF_TOKEN: logger.warning("HF_TOKEN not set — submission not saved to HF.") return False try: from huggingface_hub import HfApi api = HfApi(token=HF_TOKEN) filename = f"submissions/{row['language']}/{row['id']}.json" content = json.dumps(row, ensure_ascii=False, indent=2).encode("utf-8") api.upload_file( path_or_fileobj=content, path_in_repo=filename, repo_id=HF_DATASET_ID, repo_type="dataset", commit_message=f"[submission] {row['language']} {row['exercise_id']} {row['id'][:8]}", ) return True except Exception as e: logger.error(f"HF upload failed: {e}") return False
# ---------------------------------------------------------------------------# Core actions# ---------------------------------------------------------------------------
def run_code(code: str, lang: str, stdin: str = "") -> str: """Translate native code to English Python and execute it safely.""" lang = normalize_lang(lang) if not code.strip(): return "Write some code first." if not LEGESHER_OK: return "Legesher is not available in this environment. Code execution disabled."
try: translator = _get_native_to_en(lang) english_code = translator.translate_code(code) except Exception as e: return f"Translation error: {e}"
try: with tempfile.NamedTemporaryFile( mode="w", suffix=".py", delete=False, encoding="utf-8" ) as tmp: tmp.write(english_code) tmp_path = tmp.name
result = subprocess.run( [sys.executable, "-X", "utf8", tmp_path], input=stdin if stdin.strip() else None, capture_output=True, text=True, timeout=10, encoding="utf-8", env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}, ) os.unlink(tmp_path)
out = result.stdout.strip() err = result.stderr.strip() if err: out = (out + "\n\n⚠️ Errors:\n" + err).strip() return out or "(no output — did you call your function at the bottom?)"
except subprocess.TimeoutExpired: return "Timed out after 10 seconds. Check for infinite loops or missing input." except Exception as e: return f"Execution error: {e}"
def submit_code( code: str, lang: str, # normalized below tier_idx: int, exercise_title: str, time_spent: int, consent: bool,) -> str: lang = normalize_lang(lang) if not consent: return "Please tick the consent checkbox before submitting." if not code.strip(): return "Code is empty — nothing to submit." if not exercise_title: return "Select an exercise before submitting."
ex = get_exercise(lang, tier_idx, exercise_title) exercise_id = ex["id"] if ex else f"{lang}-unknown"
row = { "id": str(uuid.uuid4()), "code": code, "language": lang, "exercise_id": exercise_id, "exercise_title": exercise_title, "tier": tier_idx + 1, "time_spent_minutes": time_spent, "submitted_at": datetime.now(timezone.utc).isoformat(), "consent_given": True, "legesher_version": "0.7.3", }
saved = push_submission(row) if saved: return f"Submitted! Your contribution ID: `{row['id'][:8]}`. Thank you for contributing to Language, Decoded." else: # Fallback: save locally so nothing is lost fallback_dir = Path(__file__).parent / "local_submissions" fallback_dir.mkdir(exist_ok=True) (fallback_dir / f"{row['id']}.json").write_text( json.dumps(row, ensure_ascii=False, indent=2), encoding="utf-8" ) return f"Saved locally (HF upload unavailable). ID: `{row['id'][:8]}`."
# ---------------------------------------------------------------------------# UI helpers# ---------------------------------------------------------------------------
def update_exercise_dropdown(lang: str, tier_idx: int): choices = get_exercise_choices(lang, tier_idx) value = choices[0] if choices else None return gr.update(choices=choices, value=value)
def update_prompt(lang: str, tier_idx: int, exercise_title: str) -> str: if not exercise_title: return "" ex = get_exercise(lang, tier_idx, exercise_title) if not ex: return "" time_note = f"*Estimated time: ~{ex['time_estimate_min']} minutes*\n\n" return time_note + ex["prompt"]
def update_on_lang_change(lang: str, tier_idx: int): choices = get_exercise_choices(lang, tier_idx) value = choices[0] if choices else None prompt = update_prompt(lang, tier_idx, value) if value else "" return gr.Dropdown(choices=choices, value=value), prompt
# ---------------------------------------------------------------------------# Gradio UI# ---------------------------------------------------------------------------
HEADER_MD = """# Native Code Contribution Portal### Language, Decoded — Expedition Tiny Aya
Write Python code in your native language using [Legesher](https://legesher.io) and contribute to our research on native-language programming.
**How it works:**1. Select your language and an exercise2. Write your solution using Legesher (native keywords + native variable names)3. Click **Run** to verify your code works4. Fill in the metadata and click **Submit**
---"""
CONSENT_TEXT = ( "I give permission for my submitted code to be used in the Language, Decoded research project " "and to be published as part of an open dataset (Apache 2.0 / CC-BY-4.0). " "No personal information is collected — submissions are anonymous.")
SIDEBAR_MD = """### What counts as native code?
- Variables, functions, and classes named in your language- Written from scratch — not translated from an English solution- Reflects how *you* would naturally think about the problem- Uses Legesher keywords throughout
### What doesn't qualify?
- Word-for-word translations of English code- AI-generated code- English variable names with only keywords swapped
Need help? Read the full [criteria document](https://linear.app/legesher-research/document/native-code-criteria-qualification-disqualification-and-quality-rubric-5705fc83d6e8)."""
def build_app() -> gr.Blocks: with gr.Blocks(title="Native Code Submission — Language, Decoded") as app:
gr.Markdown(HEADER_MD)
with gr.Row(): # ---- Left column: config + exercise ---- with gr.Column(scale=1): lang_dropdown = gr.Dropdown( label="Your language", choices=[(v, k) for k, v in LANGUAGES.items()], value="zh", )
tier_radio = gr.Radio( label="Exercise tier", choices=TIER_LABELS, value=TIER_LABELS[0], )
exercise_dropdown = gr.Dropdown( label="Exercise", choices=get_exercise_choices("zh", 0), value=get_exercise_choices("zh", 0)[0], )
exercise_prompt = gr.Markdown( value=update_prompt("zh", 0, get_exercise_choices("zh", 0)[0]), label="Exercise prompt", )
gr.Markdown(SIDEBAR_MD)
with gr.Accordion("Legesher keyword reference", open=False): cheatsheet = gr.Markdown( value=load_reference("zh"), )
# ---- Right column: editor + run + submit ---- with gr.Column(scale=2): code_editor = gr.Code( label="Your Legesher code", language="python", lines=20, value="# Write your solution here using Legesher\n# Use native-language variable and function names\n", )
with gr.Row(): run_btn = gr.Button("Run code", variant="secondary") clear_btn = gr.Button("Clear", variant="stop")
stdin_input = gr.Textbox( label="Program input (stdin) — one value per line", placeholder="e.g. 15\n(leave blank if your code needs no input)", lines=2, )
run_output = gr.Textbox( label="Output", lines=6, placeholder="Run your code to see output here...", interactive=False, )
gr.Markdown("---") gr.Markdown("### Submit your solution")
time_slider = gr.Slider( label="Time spent (minutes)", minimum=1, maximum=120, step=1, value=15, )
consent_checkbox = gr.Checkbox( label=CONSENT_TEXT, value=False, )
submit_btn = gr.Button("Submit contribution", variant="primary")
submit_status = gr.Textbox( label="Submission status", interactive=False, )
# ---- State ---- tier_idx_state = gr.State(value=0) lang_state = gr.State(value="zh")
# ---- Event wiring ----
def tier_to_idx(tier_label: str) -> int: return TIER_LABELS.index(tier_label)
def on_tier_change(tier_label: str, lang: str): try: idx = TIER_LABELS.index(tier_label) if tier_label in TIER_LABELS else 0 choices = get_exercise_choices(lang, idx) value = choices[0] if choices else None prompt = update_prompt(lang, idx, value) if value else "" return idx, gr.update(choices=choices, value=value), prompt except Exception as e: logger.error(f"on_tier_change error: {e!r} | tier_label={tier_label!r} lang={lang!r}") return 0, gr.update(), ""
def on_lang_change(lang_raw: str, tier_label: str): try: lang_code = normalize_lang(lang_raw) logger.info(f"on_lang_change: raw={lang_raw!r} -> code={lang_code!r} tier={tier_label!r}") idx = TIER_LABELS.index(tier_label) if tier_label in TIER_LABELS else 0 choices = get_exercise_choices(lang_code, idx) value = choices[0] if choices else None prompt = update_prompt(lang_code, idx, value) if value else "" sheet = load_reference(lang_code) logger.info(f"on_lang_change OK: choices={choices}") return lang_code, gr.update(choices=choices, value=value), prompt, sheet except Exception as e: logger.error(f"on_lang_change error: {e!r} | lang_raw={lang_raw!r}") return "zh", gr.update(), "", load_reference("zh")
def on_exercise_change(exercise_title: str, lang_raw: str, tier_idx: int): # Use lang_dropdown value directly (always current), not lang_state (can be stale) try: lang_code = normalize_lang(lang_raw) return update_prompt(lang_code, tier_idx, exercise_title) except Exception as e: logger.error(f"on_exercise_change error: {e!r}") return ""
lang_dropdown.change( on_lang_change, inputs=[lang_dropdown, tier_radio], outputs=[lang_state, exercise_dropdown, exercise_prompt, cheatsheet], )
tier_radio.change( on_tier_change, inputs=[tier_radio, lang_state], outputs=[tier_idx_state, exercise_dropdown, exercise_prompt], )
exercise_dropdown.change( on_exercise_change, inputs=[exercise_dropdown, lang_dropdown, tier_idx_state], outputs=[exercise_prompt], )
run_btn.click( fn=run_code, inputs=[code_editor, lang_state, stdin_input], outputs=[run_output], )
clear_btn.click( fn=lambda: ("", "", ""), outputs=[code_editor, stdin_input, run_output], )
submit_btn.click( fn=submit_code, inputs=[ code_editor, lang_state, tier_idx_state, exercise_dropdown, time_slider, consent_checkbox, ], outputs=[submit_status], )
return app
if __name__ == "__main__": app = build_app() app.launch(theme=gr.themes.Soft(primary_hue="blue"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170{ "zh": { "tier1": [ { "id": "zh-t1-fizzbuzz", "title": "FizzBuzz", "tier": 1, "prompt": "写一个程序,打印从 1 到 30 的数字。\n\n规则:\n- 如果数字能被 3 整除,打印 \"嘶嘶\" 而不是数字\n- 如果数字能被 5 整除,打印 \"嗡嗡\" 而不是数字\n- 如果数字既能被 3 又能被 5 整除,打印 \"嘶嘶嗡嗡\"\n\n预期输出示例:1, 2, 嘶嘶, 4, 嗡嗡, 嘶嘶, 7, ...", "expected_output": "1\n2\n嘶嘶\n4\n嗡嗡\n嘶嘶\n7\n8\n嘶嘶\n嗡嗡\n11\n嘶嘶\n13\n14\n嘶嘶嗡嗡", "time_estimate_min": 10 }, { "id": "zh-t1-factorial", "title": "阶乘", "tier": 1, "prompt": "写一个函数,计算一个正整数的阶乘。\n\n例如:\n- 阶乘(5) → 120\n- 阶乘(0) → 1\n- 阶乘(7) → 5040\n\n提示:阶乘(n) = n × (n-1) × ... × 1", "expected_output": "120\n1\n5040", "time_estimate_min": 10 }, { "id": "zh-t1-palindrome", "title": "回文检测", "tier": 1, "prompt": "写一个函数,检测一个字符串是否是回文(正读反读都一样)。\n\n例如:\n- \"racecar\" → 是回文\n- \"hello\" → 不是回文\n- \"上海自来水来自海上\" → 是回文\n\n忽略大小写和空格。", "expected_output": "是\n否\n是", "time_estimate_min": 15 } ], "tier2": [ { "id": "zh-t2-calculator", "title": "计算器", "tier": 2, "prompt": "写一个简单的命令行计算器,支持以下功能:\n\n- 加法、减法、乘法、除法\n- 处理除以零的错误\n- 循环接受用户输入,直到用户输入 '退出'\n\n输入格式:\"数字 运算符 数字\"(例如:\"10 + 5\")", "expected_output": "计算器已启动(输入'退出'结束)\n>>> 10 + 5 = 15", "time_estimate_min": 25 }, { "id": "zh-t2-word-count", "title": "词频统计", "tier": 2, "prompt": "写一个程序,统计一段文字中每个词出现的频率,并按频率从高到低排序输出前 10 个词。\n\n输入:一段中文或英文文字(可以硬编码在程序中)\n输出:词语及其出现次数,按频率排序", "expected_output": "词频统计结果:\n\"的\": 15次\n\"是\": 12次\n...", "time_estimate_min": 30 } ], "tier3": [ { "id": "zh-t3-data-analysis", "title": "数据分析脚本", "tier": 3, "prompt": "写一个数据分析脚本,分析一组学生成绩数据。\n\n功能要求:\n1. 定义一组学生数据(姓名 + 成绩列表,至少 10 名学生)\n2. 计算班级平均分、最高分、最低分\n3. 按成绩分组(优秀 90+、良好 75-89、及格 60-74、不及格 <60)\n4. 找出成绩高于平均分的学生\n5. 输出完整报告", "expected_output": "班级成绩分析报告\n=================\n平均分:78.5\n最高分:98(李明)\n最低分:45(王芳)\n...", "time_estimate_min": 45 } ] }, "es": { "tier1": [ { "id": "es-t1-fizzbuzz", "title": "FizzBuzz", "tier": 1, "prompt": "Escribe un programa que imprima los números del 1 al 30.\n\nReglas:\n- Si el número es divisible entre 3, imprime \"Fizz\" en lugar del número\n- Si el número es divisible entre 5, imprime \"Buzz\" en lugar del número\n- Si es divisible entre ambos, imprime \"FizzBuzz\"\n\nEjemplo de salida: 1, 2, Fizz, 4, Buzz, Fizz, 7, ...", "expected_output": "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz", "time_estimate_min": 10 }, { "id": "es-t1-factorial", "title": "Factorial", "tier": 1, "prompt": "Escribe una función que calcule el factorial de un número entero positivo.\n\nEjemplos:\n- factorial(5) → 120\n- factorial(0) → 1\n- factorial(7) → 5040\n\nPista: factorial(n) = n × (n-1) × ... × 1", "expected_output": "120\n1\n5040", "time_estimate_min": 10 }, { "id": "es-t1-palindrome", "title": "Palíndromo", "tier": 1, "prompt": "Escribe una función que verifique si una cadena de texto es un palíndromo (se lee igual de izquierda a derecha que de derecha a izquierda).\n\nEjemplos:\n- \"reconocer\" → es palíndromo\n- \"hola\" → no es palíndromo\n- \"A man a plan a canal Panama\" → es palíndromo\n\nIgnora mayúsculas/minúsculas y espacios.", "expected_output": "Sí\nNo\nSí", "time_estimate_min": 15 } ], "tier2": [ { "id": "es-t2-calculator", "title": "Calculadora", "tier": 2, "prompt": "Escribe una calculadora de línea de comandos que soporte:\n\n- Suma, resta, multiplicación y división\n- Manejo del error de división por cero\n- Ciclo que acepta entradas hasta que el usuario escriba 'salir'\n\nFormato de entrada: \"número operador número\" (por ejemplo: \"10 + 5\")", "expected_output": "Calculadora iniciada (escribe 'salir' para terminar)\n>>> 10 + 5 = 15", "time_estimate_min": 25 }, { "id": "es-t2-word-count", "title": "Contador de palabras", "tier": 2, "prompt": "Escribe un programa que cuente la frecuencia de cada palabra en un texto y muestre las 10 más frecuentes ordenadas de mayor a menor.\n\nEntrada: Un texto (puede estar codificado directamente en el programa)\nSalida: Palabras y su conteo, ordenadas por frecuencia", "expected_output": "Resultado del conteo:\n\"el\": 15 veces\n\"la\": 12 veces\n...", "time_estimate_min": 30 } ], "tier3": [ { "id": "es-t3-data-analysis", "title": "Análisis de datos", "tier": 3, "prompt": "Escribe un script de análisis de datos para calificaciones de estudiantes.\n\nRequisitos:\n1. Define un conjunto de datos de al menos 10 estudiantes (nombre + calificación)\n2. Calcula el promedio, la calificación más alta y la más baja\n3. Agrupa por desempeño (Excelente 90+, Bueno 75-89, Suficiente 60-74, Insuficiente <60)\n4. Identifica estudiantes con calificación superior al promedio\n5. Genera un informe completo", "expected_output": "Informe de calificaciones\n========================\nPromedio: 78.5\nMás alta: 98 (María García)\nMás baja: 45 (Juan López)\n...", "time_estimate_min": 45 } ] }, "ur": { "tier1": [ { "id": "ur-t1-fizzbuzz", "title": "فز بز", "tier": 1, "prompt": "ایک پروگرام لکھیں جو 1 سے 30 تک کے اعداد پرنٹ کرے۔\n\nقواعد:\n- اگر عدد 3 پر پوری طرح تقسیم ہو تو \"فز\" پرنٹ کریں\n- اگر عدد 5 پر پوری طرح تقسیم ہو تو \"بز\" پرنٹ کریں\n- اگر دونوں پر تقسیم ہو تو \"فز بز\" پرنٹ کریں\n\nمثال: 1، 2، فز، 4، بز، فز، 7، ...", "expected_output": "1\n2\nفز\n4\nبز\nفز\n7\n8\nفز\nبز\n11\nفز\n13\n14\nفز بز", "time_estimate_min": 10 }, { "id": "ur-t1-factorial", "title": "فیکٹوریل", "tier": 1, "prompt": "ایک فنکشن لکھیں جو کسی مثبت پورے عدد کا فیکٹوریل حساب کرے۔\n\nمثالیں:\n- فیکٹوریل(5) ← 120\n- فیکٹوریل(0) ← 1\n- فیکٹوریل(7) ← 5040\n\nیاد رہے: فیکٹوریل(ن) = ن × (ن-1) × ... × 1", "expected_output": "120\n1\n5040", "time_estimate_min": 10 }, { "id": "ur-t1-palindrome", "title": "پیلنڈروم جانچ", "tier": 1, "prompt": "ایک فنکشن لکھیں جو یہ بتائے کہ کوئی لفظ یا جملہ پیلنڈروم ہے یا نہیں (یعنی آگے پیچھے سے ایک جیسا پڑھا جائے)۔\n\nمثالیں:\n- \"ملم\" ← پیلنڈروم ہے\n- \"سلام\" ← پیلنڈروم نہیں\n- \"racecar\" ← پیلنڈروم ہے\n\nبڑے اور چھوٹے حروف اور خالی جگہوں کو نظرانداز کریں۔", "expected_output": "ہاں\nنہیں\nہاں", "time_estimate_min": 15 } ], "tier2": [ { "id": "ur-t2-calculator", "title": "حساب کتاب", "tier": 2, "prompt": "ایک کمانڈ لائن کیلکولیٹر لکھیں جو یہ کام کرے:\n\n- جمع، تفریق، ضرب اور تقسیم\n- صفر سے تقسیم کی غلطی کو سنبھالنا\n- لوپ جو 'خروج' لکھنے تک جاری رہے\n\nاندراج کی شکل: \"عدد آپریٹر عدد\" (مثلاً: \"10 + 5\")", "expected_output": "کیلکولیٹر شروع ہو گیا ('خروج' لکھیں بند کرنے کے لیے)\n>>> 10 + 5 = 15", "time_estimate_min": 25 }, { "id": "ur-t2-word-count", "title": "الفاظ شمار", "tier": 2, "prompt": "ایک پروگرام لکھیں جو کسی متن میں ہر لفظ کتنی بار آیا یہ گنے اور سب سے زیادہ استعمال ہونے والے 10 الفاظ دکھائے۔\n\nاندراج: کوئی بھی متن (پروگرام میں لکھا جا سکتا ہے)\nنتیجہ: الفاظ اور ان کی تعداد، زیادہ سے کم ترتیب میں", "expected_output": "الفاظ شماری کا نتیجہ:\n\"کا\": 15 بار\n\"اور\": 12 بار\n...", "time_estimate_min": 30 } ], "tier3": [ { "id": "ur-t3-data-analysis", "title": "ڈیٹا تجزیہ", "tier": 3, "prompt": "طلبہ کے نمبروں کے ڈیٹا کا تجزیہ کرنے والا اسکرپٹ لکھیں۔\n\nضروریات:\n1. کم از کم 10 طلبہ کا ڈیٹا تیار کریں (نام + نمبر)\n2. اوسط، سب سے زیادہ اور سب سے کم نمبر حساب کریں\n3. کارکردگی کے مطابق گروپ بنائیں (اعلیٰ 90+، اچھا 75-89، ٹھیک 60-74، کمزور <60)\n4. اوسط سے زیادہ نمبر والے طلبہ کی فہرست بنائیں\n5. مکمل رپورٹ تیار کریں", "expected_output": "طلبہ کی کارکردگی رپورٹ\n====================\nاوسط: 78.5\nسب سے زیادہ: 98 (احمد علی)\nسب سے کم: 45 (سارہ خان)\n...", "time_estimate_min": 45 } ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# Spanish (Español) - Python Quick Reference



> Write Python code in Spanish. This guide shows the Spanish keywords
> to use for Legesher to understand your code.
## Language Details
| Attribute | Value |
| --------- | ----- |
| **Language** | Spanish |
| **Native Name** | Español |
| **Script** | Latin |
| **ISO 639-1** | `es` |
| **ISO 639-2** | `spa` |
| **BCP 47 Tag** | `es` |
| **Text Direction** | Left-to-Right (LTR) |
| **Status** | Experimental |
## Keywords (39 terms)
These are Python's reserved words translated to Spanish.
| English | Spanish |
| ------- | ------ |
| `and` | `y` |
| `as` | `como` |
| `assert` | `afirmar` |
| `async` | `asincrónico` |
| `await` | `esperar` |
| `break` | `romper` |
| `case` | `caso` |
| `class` | `clase` |
| `continue` | `continuar` |
| `def` | `definir` |
| `del` | `eliminar` |
| `elif` | `si_no` |
| `else` | `sino` |
| `except` | `excepto` |
| `except*` | `excepto*` |
| `False` | `falso` |
| `finally` | `finalmente` |
| `for` | `por` |
| `from` | `desde` |
| `global` | `declara_variable_global` |
| `if` | `si` |
| `import` | `importar` |
| `in` | `en` |
| `is` | `ser` |
| `lambda` | `funcion_anonima` |
| `match` | `coincidir` |
| `None` | `nulo` |
| `nonlocal` | `nolocal` |
| `not` | `no` |
| `or` | `o` |
| `pass` | `pasar` |
| `raise` | `levantar` |
| `return` | `devolver` |
| `True` | `verdadero` |
| `try` | `probar` |
| `type` | `tipo` |
| `while` | `mientras` |
| `with` | `con` |
| `yield` | `dar` |
## Built-in Functions (72 terms)
Python's built-in functions and types in Spanish.
| English | Spanish |
| ------- | ------ |
| `abs` | `valorabsoluto` |
| `aiter` | `iterador_asincrónico` |
| `all` | `todo` |
| `anext` | `próximo` |
| `any` | `cualquier` |
| `ascii` | `asciiificar` |
| `bin` | `binario` |
| `bool` | `booleano` |
| `breakpoint` | `puntodeinterrupción` |
| `bytearray` | `conjuntoDeBytes` |
| `bytes` | `bytes_inmutables` |
| `callable` | `llamable` |
| `chr` | `carácter` |
| `classmethod` | `métododeclase` |
| `compile` | `compilar` |
| `complex` | `complejo` |
| `delattr` | `eliminar_atributo` |
| `dict` | `diccionario` |
| `dir` | `directorio` |
| `divmod` | `division_con_resta` |
| `ellipsis` | `elipsis` |
| `enumerate` | `elenumerar` |
| `eval` | `evalúo` |
| `exec` | `ejecutar` |
| `filter` | `filtrar` |
| `float` | `flotante` |
| `format` | `formatear` |
| `frozenset` | `conjuntocongelado` |
| `getattr` | `obtenerelatributo` |
| `globals` | `globales` |
| `hasattr` | `teneratributo` |
| `hash` | `resumen_hash` |
| `help` | `ayuda` |
| `hex` | `hexadecimal` |
| `id` | `identificador` |
| `input` | `entrada` |
| `int` | `entero` |
| `isinstance` | `ser_de_la_clase` |
| `issubclass` | `subclasede` |
| `iter` | `iterar` |
| `len` | `longitud` |
| `list` | `lista` |
| `locals` | `loslocales` |
| `map` | `mapear` |
| `max` | `máximo` |
| `memoryview` | `vistadememoria` |
| `min` | `minimo` |
| `next` | `siguiente` |
| `notimplemented` | `noimplementado` |
| `object` | `objeto` |
| `oct` | `octal` |
| `open` | `abrir` |
| `ord` | `ordinal` |
| `pow` | `potencia` |
| `print` | `imprimir` |
| `property` | `propiedad` |
| `range` | `rango` |
| `repr` | `representación` |
| `reversed` | `revesado` |
| `round` | `redondear` |
| `set` | `conjunto` |
| `setattr` | `asignar` |
| `slice` | `rebanada` |
| `sorted` | `ordenado` |
| `staticmethod` | `estático` |
| `str` | `cadena` |
| `sum` | `sumar` |
| `super` | `superClase` |
| `tuple` | `tupla` |
| `type` | `tipo` |
| `vars` | `variables` |
| `zip` | `acopiar` |
## Exceptions (69 terms)
Exception classes for error handling.
| English | Spanish |
| ------- | ------ |
| `arithmeticerror` | `erroraritmético` |
| `assertionerror` | `errordeaserción` |
| `attributeerror` | `Errordeatributo` |
| `baseexception` | `excepciónbase` |
| `baseexceptiongroup` | `grupodeexcepcionesbase` |
| `basegeneratorexit` | `generarsalida` |
| `blockingioerror` | `errordeESbloqueante` |
| `brokenpipeerror` | `errordetuberíarota` |
| `buffererror` | `errordebúfer` |
| `byteswarning` | `advertenciadebytes` |
| `childprocesserror` | `errordeprocesosecundario` |
| `connectionabortederror` | `errordeabortarconexión` |
| `connectionerror` | `errordeconexión` |
| `connectionrefusederror` | `errorderechazodeconexión` |
| `connectionreseterror` | `resetearconexión` |
| `deprecationwarning` | `advertenciadedepreciación` |
| `encodingwarning` | `advertenciadecodificación` |
| `environmenterror` | `errordeentorno` |
| `eoferror` | `errordeentradasalida` |
| `exception` | `excepción` |
| `exceptiongroup` | `grupodeexcepciones` |
| `fileexistserror` | `errordeexistenciadearchivo` |
| `filenotfounderror` | `Errordenoencontrarelarchivo` |
| `floatingpointerror` | `errordepunteroflotante` |
| `futurewarning` | `advertenciafutura` |
| `generatorexit` | `salidadegenerador` |
| `importerror` | `errordeimportación` |
| `importwarning` | `advertenciadeimportación` |
| `indentationerror` | `errordesangría` |
| `indexerror` | `Errordeíndice` |
| `interruptederror` | `errordeinterrupción` |
| `ioerror` | `errordeES` |
| `isadirectoryerror` | `errordedirectorio` |
| `keyboardinterrupt` | `interrupcióndelteclado` |
| `keyerror` | `errordeclave` |
| `lookuperror` | `errordebúsqueda` |
| `memoryerror` | `errordememoria` |
| `modulenotfounderror` | `Errordemódulonoencontrado` |
| `nameerror` | `Errordenombre` |
| `notadirectoryerror` | `errordenoserundirectorio` |
| `notimplementederror` | `errordenoimplementación` |
| `oserror` | `ErrorDeOS` |
| `overflowerror` | `errordedesbordamiento` |
| `pendingdeprecationwarning` | `advertenciadeadvertenciadedepreciaciónpendiente` |
| `permissionerror` | `errordepermiso` |
| `processlookuperror` | `errordebúsquedadeproceso` |
| `recursionerror` | `errorderecursión` |
| `referenceerror` | `errordereferencia` |
| `resourcewarning` | `advertenciaderecursos` |
| `runtimeerror` | `errorentiempodeejecución` |
| `runtimewarning` | `advertenciadetiempodeejecución` |
| `stopasynciteration` | `detenerlaiteraciónasincrónica` |
| `stopiteration` | `detener_iteración` |
| `syntaxerror` | `errordesintaxis` |
| `syntaxwarning` | `advertenciadesintaxis` |
| `systemexit` | `salirdelsistema` |
| `taberror` | `errordetabulación` |
| `timeouterror` | `errordetiempodeespera` |
| `typeerror` | `errordetipo` |
| `unboundlocalerror` | `errordereferencialocalnoenlazada` |
| `unicodedecodeerror` | `errordedecodificacióndeUnicode` |
| `unicodeencodeerror` | `errordecodificaciónunicode` |
| `unicodeerror` | `errordeunicode` |
| `unicodetranslateerror` | `errordetraduccióndeUnicode` |
| `unicodewarning` | `advertenciadeunicode` |
| `userwarning` | `advertenciadelusuario` |
| `valueerror` | `errordevalor` |
| `warning` | `advertencia` |
| `zerodivisionerror` | `errordedivisiónporcero` |
## Example Code
Here's an example showing Spanish Python code with Legesher:
```python
# Ejemplo: Función factorial con manejo de errores
desde typing importar Optional
definir factorial(n):
"""Calcular el factorial de n."""
si n < 0:
levantar Errordevalor("Los números negativos no están permitidos")
si_no n == 0 o n == 1:
devolver 1
sino:
devolver n * factorial(n - 1)
definir principal():
numeros = [entero(x) por x en rango(6)]
por numero en numeros:
resultado = factorial(numero)
imprimir(f"{numero}! = {resultado}")
# Demostrar bucle while
contador = 0
mientras contador < 3:
imprimir(f"Contador: {contador}")
contador += 1
# Demostrar try/except
probar:
factorial(-1)
excepto Errordevalor como error:
imprimir(f"Error: {error}")
finalmente:
imprimir("¡Listo!")
si __name__ == "__main__":
principal()
```
## Usage
```python
from legesher_i18n import LanguagePackLoader
# Load Spanish pack for Python 3.12
loader = LanguagePackLoader()
pack = loader.load("es", "python", "3.12")
# Translate code
from legesher import translate
english_code = translate(your_es_code, from_lang="es", to_lang="en")
```
## Contributing
Found a better translation? We welcome contributions from native speakers!
1. Edit `legesher_i18n_python_es/packs/<version>.yml` for the Python version where the term was introduced:
- `3.10.yml` - Base translations (most terms)
- `3.11.yml` - Terms added in Python 3.11 (e.g., `except*`)
- `3.12.yml` - Terms added in Python 3.12 (e.g., `type`)
- `3.13.yml` / `3.14.yml` - Future additions
2. Submit a pull request with your reasoning
3. Translations should be natural, commonly used in CS education, and easy to type123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294# Urdu (اردو) - Python Quick Reference




> Write Python code in Urdu. This guide shows the Urdu keywords
> to use for Legesher to understand your code.
>
> **Note:** This is a right-to-left (RTL) language. RTL support is currently a work in progress — we welcome your feedback!
## Language Details
| Attribute | Value |
| --------- | ----- |
| **Language** | Urdu |
| **Native Name** | اردو |
| **Script** | Arabic |
| **ISO 639-1** | `ur` |
| **ISO 639-2** | `urd` |
| **BCP 47 Tag** | `ur` |
| **Text Direction** | Right-to-Left (RTL) |
| **Status** | Experimental |
## Keywords (39 terms)
These are Python's reserved words translated to Urdu.
| English | Urdu |
| ------- | ------ |
| `and` | `اور` |
| `as` | `بطور` |
| `assert` | `تصدیق` |
| `async` | `غیرہمزمان` |
| `await` | `انتظار` |
| `break` | `توڑ` |
| `case` | `صورت` |
| `class` | `جماعت` |
| `continue` | `جاری` |
| `def` | `تعریف` |
| `del` | `مٹاؤ` |
| `elif` | `ورنہاگر` |
| `else` | `ورنہ` |
| `except` | `سوائے` |
| `except*` | `سوائے*` |
| `False` | `غلط` |
| `finally` | `بالآخر` |
| `for` | `لیے` |
| `from` | `سے` |
| `global` | `عالمی` |
| `if` | `اگر` |
| `import` | `درآمد` |
| `in` | `میں` |
| `is` | `ہے` |
| `lambda` | `لیمڈا` |
| `match` | `مماثلت` |
| `None` | `کچھنہیں` |
| `nonlocal` | `غیرمقامی` |
| `not` | `نہیں` |
| `or` | `یا` |
| `pass` | `گزر` |
| `raise` | `اٹھاؤ` |
| `return` | `واپسی` |
| `True` | `صحیح` |
| `try` | `کوشش` |
| `type` | `نوعیت` |
| `while` | `جبتک` |
| `with` | `ساتھ` |
| `yield` | `حاصل` |
## Built-in Functions (72 terms)
Python's built-in functions and types in Urdu.
| English | Urdu |
| ------- | ------ |
| `abs` | `مطلق` |
| `aiter` | `غیرہمزمانتکرارکنندہ` |
| `all` | `تمام` |
| `anext` | `غیرہمزماناگلا` |
| `any` | `کوئی` |
| `ascii` | `آسکی` |
| `bin` | `ثنائی` |
| `bool` | `منطقی` |
| `breakpoint` | `وقفہ` |
| `bytearray` | `بائٹصف` |
| `bytes` | `بائٹس` |
| `callable` | `قابلِاستعمال` |
| `chr` | `حرف` |
| `classmethod` | `جماعتطریقہ` |
| `compile` | `تالیف` |
| `complex` | `مرکب` |
| `delattr` | `خاصیت_مٹاؤ` |
| `dict` | `لغت` |
| `dir` | `فہرست` |
| `divmod` | `تقسیمباقی` |
| `ellipsis` | `حذف` |
| `enumerate` | `شمار` |
| `eval` | `جانچ` |
| `exec` | `عمل` |
| `filter` | `چھاننا` |
| `float` | `اعشاری` |
| `format` | `شکل` |
| `frozenset` | `منجمدمجموعہ` |
| `getattr` | `خاصیت_لاؤ` |
| `globals` | `عالمیمتغیرات` |
| `hasattr` | `خاصیت_ہے` |
| `hash` | `ہیش` |
| `help` | `مدد` |
| `hex` | `سداسی` |
| `id` | `شناخت` |
| `input` | `داخلہ` |
| `int` | `عددصحیح` |
| `isinstance` | `مثال_ہے` |
| `issubclass` | `ذیلی_جماعت_ہے` |
| `iter` | `تکرارکنندہ` |
| `len` | `لمبائی` |
| `list` | `فہرستی` |
| `locals` | `مقامیمتغیرات` |
| `map` | `نقشہ` |
| `max` | `زیادہ` |
| `memoryview` | `یادداشتنظارہ` |
| `min` | `کمترین` |
| `next` | `اگلا` |
| `notimplemented` | `غیرنافذ` |
| `object` | `شے` |
| `oct` | `ہشتی` |
| `open` | `کھولو` |
| `ord` | `ترتیب` |
| `pow` | `قوت` |
| `print` | `چھاپو` |
| `property` | `خاصیت` |
| `range` | `حدود` |
| `repr` | `نمائندگی` |
| `reversed` | `الٹا` |
| `round` | `گول` |
| `set` | `مجموعہ` |
| `setattr` | `خاصیت_مقرر` |
| `slice` | `ٹکڑا` |
| `sorted` | `ترتیبشدہ` |
| `staticmethod` | `جامدطریقہ` |
| `str` | `متن` |
| `sum` | `کل` |
| `super` | `بالائی` |
| `tuple` | `ٹپل` |
| `type` | `نوعیت` |
| `vars` | `متغیرات_لاؤ` |
| `zip` | `جوڑا` |
## Exceptions (69 terms)
Exception classes for error handling.
| English | Urdu |
| ------- | ------ |
| `arithmeticerror` | `حسابیغلطی` |
| `assertionerror` | `تصدیقغلطی` |
| `attributeerror` | `خاصیتغلطی` |
| `baseexception` | `بنیادیاستثنا` |
| `baseexceptiongroup` | `بنیادیاستثناگروہ` |
| `basegeneratorexit` | `بنیادیجنریٹرخروج` |
| `blockingioerror` | `مسدودداخلہخارجہغلطی` |
| `brokenpipeerror` | `ٹوٹاپائپغلطی` |
| `buffererror` | `بفرغلطی` |
| `byteswarning` | `بائٹسانتباہ` |
| `childprocesserror` | `ذیلیعملغلطی` |
| `connectionabortederror` | `رابطہمنسوخغلطی` |
| `connectionerror` | `رابطہغلطی` |
| `connectionrefusederror` | `رابطہمستردغلطی` |
| `connectionreseterror` | `رابطہدوبارہغلطی` |
| `deprecationwarning` | `متروکانتباہ` |
| `encodingwarning` | `ضابطہبندیانتباہ` |
| `environmenterror` | `ماحولغلطی` |
| `eoferror` | `فائلختمغلطی` |
| `exception` | `استثنا` |
| `exceptiongroup` | `استثناگروہ` |
| `fileexistserror` | `فائلموجودغلطی` |
| `filenotfounderror` | `فائلنہملیغلطی` |
| `floatingpointerror` | `اعشاریاشارہغلطی` |
| `futurewarning` | `مستقبلانتباہ` |
| `generatorexit` | `جنریٹرخروج` |
| `importerror` | `درآمدغلطی` |
| `importwarning` | `درآمدانتباہ` |
| `indentationerror` | `حاشیہغلطی` |
| `indexerror` | `اشاریہغلطی` |
| `interruptederror` | `رکاوٹغلطی` |
| `ioerror` | `داخلہخارجہغلطی` |
| `isadirectoryerror` | `ڈائریکٹریہےغلطی` |
| `keyboardinterrupt` | `کلیدتختہرکاوٹ` |
| `keyerror` | `کلیدغلطی` |
| `lookuperror` | `تلاشغلطی` |
| `memoryerror` | `یادداشتغلطی` |
| `modulenotfounderror` | `ماڈیولنہملاغلطی` |
| `nameerror` | `نامغلطی` |
| `notadirectoryerror` | `ڈائریکٹرینہیںغلطی` |
| `notimplementederror` | `غیرنافذغلطی` |
| `oserror` | `آپریٹنگنظامغلطی` |
| `overflowerror` | `اوورفلوغلطی` |
| `pendingdeprecationwarning` | `زیرالتواءمتروکانتباہ` |
| `permissionerror` | `اجازتغلطی` |
| `processlookuperror` | `عملتلاشغلطی` |
| `recursionerror` | `تکرارغلطی` |
| `referenceerror` | `حوالہغلطی` |
| `resourcewarning` | `وسائلانتباہ` |
| `runtimeerror` | `وقتعملغلطی` |
| `runtimewarning` | `وقتعملانتباہ` |
| `stopasynciteration` | `غیرہمزمانتکراررُک` |
| `stopiteration` | `تکراررُک` |
| `syntaxerror` | `نحوغلطی` |
| `syntaxwarning` | `نحوانتباہ` |
| `systemexit` | `نظامخروج` |
| `taberror` | `ٹیبغلطی` |
| `timeouterror` | `وقتختمغلطی` |
| `typeerror` | `قسم_غلطی` |
| `unboundlocalerror` | `غیرمربوطمقامیغلطی` |
| `unicodedecodeerror` | `یونیکوڈضابطہکشائیغلطی` |
| `unicodeencodeerror` | `یونیکوڈضابطہبندیغلطی` |
| `unicodeerror` | `یونیکوڈغلطی` |
| `unicodetranslateerror` | `یونیکوڈترجمہغلطی` |
| `unicodewarning` | `یونیکوڈانتباہ` |
| `userwarning` | `صارفاطلاع` |
| `valueerror` | `قدرغلطی` |
| `warning` | `انتباہ` |
| `zerodivisionerror` | `صفرتقسیمغلطی` |
## Example Code
Here's an example showing Urdu Python code with Legesher:
```python
# مثال: غلطی کی ہینڈلنگ کے ساتھ فیکٹوریل فنکشن
سے typing درآمد Optional
تعریف فیکٹوریل(n):
"""عدد ن کا فیکٹوریل حساب کریں۔"""
اگر n < 0:
اٹھاؤ قدرغلطی("منفی اعداد کی اجازت نہیں")
ورنہاگر n == 0 یا n == 1:
واپسی 1
ورنہ:
واپسی n * فیکٹوریل(n - 1)
تعریف مرکزی():
اعداد = [عددصحیح(x) لیے x میں حدود(6)]
لیے عدد میں اعداد:
نتیجہ = فیکٹوریل(عدد)
چھاپو(f"{عدد}! = {نتیجہ}")
# جبتک لوپ کا مظاہرہ
گنتی = 0
جبتک گنتی < 3:
چھاپو(f"گنتی: {گنتی}")
گنتی += 1
# کوشش/سوائے کا مظاہرہ
کوشش:
فیکٹوریل(-1)
سوائے قدرغلطی بطور غلطی:
چھاپو(f"غلطی: {غلطی}")
بالآخر:
چھاپو("مکمل!")
اگر __name__ == "__main__":
مرکزی()
```
## Usage
```python
from legesher_i18n import LanguagePackLoader
# Load Urdu pack for Python 3.12
loader = LanguagePackLoader()
pack = loader.load("ur", "python", "3.12")
# Translate code
from legesher import translate
english_code = translate(your_ur_code, from_lang="ur", to_lang="en")
```
## Contributing
Found a better translation? We welcome contributions from native speakers!
1. Edit `legesher_i18n_python_ur/packs/<version>.yml` for the Python version where the term was introduced:
- `3.10.yml` - Base translations (most terms)
- `3.11.yml` - Terms added in Python 3.11 (e.g., `except*`)
- `3.12.yml` - Terms added in Python 3.12 (e.g., `type`)
- `3.13.yml` / `3.14.yml` - Future additions
2. Submit a pull request with your reasoning
3. Translations should be natural, commonly used in CS education, and easy to type123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# Chinese (中文) - Python Quick Reference



> Write Python code in Chinese. This guide shows the Chinese keywords
> to use for Legesher to understand your code.
## Language Details
| Attribute | Value |
| --------- | ----- |
| **Language** | Chinese |
| **Native Name** | 中文 |
| **Script** | Simplified Chinese (Han) |
| **ISO 639-1** | `zh` |
| **ISO 639-2** | `zho` |
| **BCP 47 Tag** | `zh-Hans` |
| **Text Direction** | Left-to-Right (LTR) |
| **Status** | Experimental |
## Keywords (39 terms)
These are Python's reserved words translated to Chinese.
| English | Chinese |
| ------- | ------ |
| `and` | `和` |
| `as` | `作为` |
| `assert` | `断言` |
| `async` | `异步` |
| `await` | `等待` |
| `break` | `终止` |
| `case` | `情况` |
| `class` | `类` |
| `continue` | `继续` |
| `def` | `定义` |
| `del` | `删除` |
| `elif` | `否则如果` |
| `else` | `否则` |
| `except` | `除外` |
| `except*` | `多重捕获*` |
| `False` | `错误` |
| `finally` | `最后` |
| `for` | `对于` |
| `from` | `从` |
| `global` | `全球` |
| `if` | `如果` |
| `import` | `导入` |
| `in` | `在` |
| `is` | `是` |
| `lambda` | `拉姆达` |
| `match` | `匹配` |
| `None` | `无` |
| `nonlocal` | `非本地` |
| `not` | `不` |
| `or` | `或` |
| `pass` | `过` |
| `raise` | `提出` |
| `return` | `返回` |
| `True` | `真实` |
| `try` | `尝试` |
| `type` | `类型` |
| `while` | `当` |
| `with` | `跟` |
| `yield` | `产生` |
## Built-in Functions (72 terms)
Python's built-in functions and types in Chinese.
| English | Chinese |
| ------- | ------ |
| `abs` | `绝对值` |
| `aiter` | `异步迭代器` |
| `all` | `全` |
| `anext` | `下一项` |
| `any` | `任意` |
| `ascii` | `ASCII` |
| `bin` | `二进制` |
| `bool` | `布尔` |
| `breakpoint` | `断点` |
| `bytearray` | `字节数组` |
| `bytes` | `字节` |
| `callable` | `可调用` |
| `chr` | `字符` |
| `classmethod` | `类方法` |
| `compile` | `编译` |
| `complex` | `复数` |
| `delattr` | `删除属性` |
| `dict` | `字典` |
| `dir` | `列出属性和方法` |
| `divmod` | `除模` |
| `ellipsis` | `省略号` |
| `enumerate` | `枚举` |
| `eval` | `评估` |
| `exec` | `执行` |
| `filter` | `过滤` |
| `float` | `浮点数` |
| `format` | `格式化` |
| `frozenset` | `冻结集` |
| `getattr` | `获取属性` |
| `globals` | `全局变量` |
| `hasattr` | `具有` |
| `hash` | `哈希` |
| `help` | `帮助` |
| `hex` | `十六进制` |
| `id` | `标识` |
| `input` | `输入` |
| `int` | `整数` |
| `isinstance` | `是实例` |
| `issubclass` | `是子类` |
| `iter` | `迭代` |
| `len` | `长度` |
| `list` | `列表` |
| `locals` | `局部变量` |
| `map` | `映射` |
| `max` | `最大值` |
| `memoryview` | `内存视图` |
| `min` | `最小值` |
| `next` | `下一个` |
| `notimplemented` | `未实现` |
| `object` | `对象` |
| `oct` | `八进制` |
| `open` | `打开` |
| `ord` | `顺序` |
| `pow` | `幂` |
| `print` | `打印` |
| `property` | `属性` |
| `range` | `范围` |
| `repr` | `表示` |
| `reversed` | `反转` |
| `round` | `四舍五入` |
| `set` | `集合` |
| `setattr` | `设置属性` |
| `slice` | `切片` |
| `sorted` | `排序` |
| `staticmethod` | `静态方法` |
| `str` | `字符串` |
| `sum` | `求和` |
| `super` | `超类` |
| `tuple` | `元组` |
| `type` | `类型` |
| `vars` | `变量字典` |
| `zip` | `压缩` |
## Exceptions (69 terms)
Exception classes for error handling.
| English | Chinese |
| ------- | ------ |
| `arithmeticerror` | `算术错误` |
| `assertionerror` | `断言错误` |
| `attributeerror` | `属性错误` |
| `baseexception` | `基本异常` |
| `baseexceptiongroup` | `基异常组` |
| `basegeneratorexit` | `基底生成器退出` |
| `blockingioerror` | `阻塞的IO错误` |
| `brokenpipeerror` | `破管错误` |
| `buffererror` | `缓冲区错误` |
| `byteswarning` | `字节警告` |
| `childprocesserror` | `子进程错误` |
| `connectionabortederror` | `连接中断错误` |
| `connectionerror` | `连接错误` |
| `connectionrefusederror` | `连接拒绝错误` |
| `connectionreseterror` | `连接重置错误` |
| `deprecationwarning` | `弃用警告` |
| `encodingwarning` | `编码警告` |
| `environmenterror` | `环境错误` |
| `eoferror` | `文件结束错误` |
| `exception` | `异常` |
| `exceptiongroup` | `异常组` |
| `fileexistserror` | `文件已存在错误` |
| `filenotfounderror` | `文件未找到错误` |
| `floatingpointerror` | `浮点数错误` |
| `futurewarning` | `未来警告` |
| `generatorexit` | `生成器退出` |
| `importerror` | `导入错误` |
| `importwarning` | `导入警告` |
| `indentationerror` | `缩进错误` |
| `indexerror` | `越界访问错误` |
| `interruptederror` | `中断错误` |
| `ioerror` | `IO错误` |
| `isadirectoryerror` | `是目录错误` |
| `keyboardinterrupt` | `键盘中断` |
| `keyerror` | `键错误` |
| `lookuperror` | `查找错误` |
| `memoryerror` | `内存错误` |
| `modulenotfounderror` | `模块未找到错误` |
| `nameerror` | `名称错误` |
| `notadirectoryerror` | `非目录错误` |
| `notimplementederror` | `未实现错误` |
| `oserror` | `操作系统错误` |
| `overflowerror` | `溢出错误` |
| `pendingdeprecationwarning` | `待删除警告` |
| `permissionerror` | `权限错误` |
| `processlookuperror` | `进程查找错误` |
| `recursionerror` | `递归错误` |
| `referenceerror` | `引用错误` |
| `resourcewarning` | `资源警告` |
| `runtimeerror` | `运行时错误` |
| `runtimewarning` | `运行时警告` |
| `stopasynciteration` | `停止异步迭代` |
| `stopiteration` | `停止迭代` |
| `syntaxerror` | `语法错误` |
| `syntaxwarning` | `语法警告` |
| `systemexit` | `系统退出` |
| `taberror` | `制表符错误` |
| `timeouterror` | `超时错误` |
| `typeerror` | `类型错误` |
| `unboundlocalerror` | `未绑定局部错误` |
| `unicodedecodeerror` | `统一码解码错误` |
| `unicodeencodeerror` | `统一码编码错误` |
| `unicodeerror` | `统一码错误` |
| `unicodetranslateerror` | `统一码转换错误` |
| `unicodewarning` | `统一码警告` |
| `userwarning` | `用户警告` |
| `valueerror` | `值错误` |
| `warning` | `警告` |
| `zerodivisionerror` | `零除数错误` |
## Example Code
Here's an example showing Chinese Python code with Legesher:
```python
# 示例:带错误处理的阶乘函数
从 typing 导入 Optional
定义 阶乘(n):
"""计算n的阶乘。"""
如果 n < 0:
提出 值错误("不允许负数")
否则如果 n == 0 或 n == 1:
返回 1
否则:
返回 n * 阶乘(n - 1)
定义 主函数():
数字列表 = [整数(x) 对于 x 在 范围(6)]
对于 数字 在 数字列表:
结果 = 阶乘(数字)
打印(f"{数字}! = {结果}")
# 演示while循环
计数 = 0
当 计数 < 3:
打印(f"计数: {计数}")
计数 += 1
# 演示try/except
尝试:
阶乘(-1)
除外 值错误 作为 错误:
打印(f"错误: {错误}")
最后:
打印("完成!")
如果 __name__ == "__main__":
主函数()
```
## Usage
```python
from legesher_i18n import LanguagePackLoader
# Load Chinese pack for Python 3.12
loader = LanguagePackLoader()
pack = loader.load("zh", "python", "3.12")
# Translate code
from legesher import translate
english_code = translate(your_zh_code, from_lang="zh", to_lang="en")
```
## Contributing
Found a better translation? We welcome contributions from native speakers!
1. Edit `legesher_i18n_python_zh/packs/<version>.yml` for the Python version where the term was introduced:
- `3.10.yml` - Base translations (most terms)
- `3.11.yml` - Terms added in Python 3.11 (e.g., `except*`)
- `3.12.yml` - Terms added in Python 3.12 (e.g., `type`)
- `3.13.yml` / `3.14.yml` - Future additions
2. Submit a pull request with your reasoning
3. Translations should be natural, commonly used in CS education, and easy to type1234567891011121314gradio>=4.44.0huggingface_hub>=0.24.0datasets>=2.20.0tree-sitter>=0.20.4tree-sitter-python>=0.21.0
# Legesher packages (bundled in wheels/)./wheels/legesher_core-0.7.3-py3-none-any.whl./wheels/legesher_i18n-0.7.3-py3-none-any.whl./wheels/legesher-0.7.3-py3-none-any.whl./wheels/legesher_i18n_python_en-0.0.2-py3-none-any.whl./wheels/legesher_i18n_python_zh-0.0.4-py3-none-any.whl./wheels/legesher_i18n_python_es-0.0.3-py3-none-any.whl./wheels/legesher_i18n_python_ur-0.0.2-py3-none-any.whl123version https://git-lfs.github.com/spec/v1oid sha256:227588a0e1ce7a3ba9a049a8999debb18b214b70c1027ebb4f060ae6ac11f0c5size 1854709.gitattributes+1
README.md+52-4
app.pyAdded+470
exercises.jsonAdded+170
references/es.mdAdded+291
references/ur.mdAdded+294
references/zh.mdAdded+291
requirements.txtAdded+14
wheels/legesher-0.7.3-py3-none-any.whlAdded
wheels/legesher_core-0.7.3-py3-none-any.whlAdded
wheels/legesher_i18n-0.7.3-py3-none-any.whlAdded+3
wheels/legesher_i18n_python_en-0.0.2-py3-none-any.whlAdded
wheels/legesher_i18n_python_es-0.0.3-py3-none-any.whlAdded
wheels/legesher_i18n_python_ur-0.0.2-py3-none-any.whlAdded
wheels/legesher_i18n_python_zh-0.0.4-py3-none-any.whlAdded