Skip to content

ltsali8220/Python-predefined-helpers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation


Python’s Predefined Keywords: A Practical Guide

Python comes with a rich set of predefined keywords that form the backbone of its syntax. These aren't functions you define — they’re built into the language and serve specific roles in control flow, error handling, logic, and structure. Here’s a walk-through of the most essential ones, with explanations and syntax examples to help you master them.


Exception Handling

Python’s exception handling is clean and readable, thanks to keywords like try, except, finally, raise, and assert.

  • try: Begins a block of code that might raise an exception.
    try:
        risky_operation()
  • except: Catches and handles exceptions raised in the try block.
    except ValueError:
        print("Invalid value")
  • finally: Runs regardless of whether an exception occurred — perfect for cleanup.
    finally:
        close_resources()
  • raise: Manually triggers an exception.
    raise RuntimeError("Something went wrong")
  • assert: Validates a condition and raises AssertionError if it fails.
    assert x > 0, "x must be positive"

Looping and Control Flow

Python’s loop constructs are intuitive and flexible, allowing you to iterate, skip, or exit based on conditions.

  • for: Iterates over items in a sequence.
    for item in items:
        print(item)
  • while: Loops as long as a condition is true.
    while not done:
        process()
  • break: Exits the loop immediately.
    if error_detected:
        break
  • continue: Skips the current iteration and moves to the next.
    if not valid:
        continue
  • pass: A no-op placeholder — useful when the syntax requires a block but you don’t want to do anything yet.
    if condition_met:
        pass

Conditional Logic

Python’s conditional keywords let you branch your logic cleanly.

  • if: Executes a block if the condition is true.
    if score >= 90:
        print("Excellent")
  • elif: Adds additional conditions.
    elif score >= 75:
        print("Good")
  • else: Executes if no prior conditions matched.
    else:
        print("Needs improvement")

Functions and Classes

Defining reusable blocks of logic or object-oriented structures is straightforward with these keywords.

  • def: Declares a function.
    def greet(name):
        return f"Hello, {name}"
  • class: Declares a class.
    class User:
        def __init__(self, name):
            self.name = name
  • return: Sends a value back from a function.
    return result
  • yield: Used in generators to return a value and pause execution.
    yield item

Importing Modules

Python’s modularity is powered by its import system.

  • import: Brings in a module.
    import os
  • from: Imports specific parts of a module.
    from math import sqrt
  • as: Assigns an alias to a module or function.
    import numpy as np

Other Useful Keywords

These keywords support context management, scope control, and logical operations.

  • with: Manages resources like files or locks using context managers.
    with open("data.txt") as file:
        content = file.read()
  • lambda: Creates anonymous functions.
    square = lambda x: x * x
  • global: Declares a variable as global inside a function.
    global counter
  • nonlocal: Refers to variables in the nearest enclosing scope (not global).
    nonlocal total
  • del: Deletes a variable or item.
    del my_list[0]
  • is: Checks identity (not equality).
    if a is b:
        print("Same object")
  • in: Checks membership.
    if "admin" in roles:
        grant_access()
  • not, and, or: Logical operators.
    if not error and ready or override:
        proceed()

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published