Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
    • Generative AI
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Python Keywords

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Exception Handling
  • Python File Handling
  • Python Package and PIP
  • Python Modules
  • Python Keywords
  • Python Built In Method
  • Python Regular Expressions (RegEx)
  • Python JSON
  • Python Datetime

Python Keywords¶

  • In Python, keywords are special reserved words that have predefined meanings and purposes within the language syntax. These words cannot be used as variable names, function names, class names, or identifiers of any kind because they are part of the Python core language.

Key Characteristics:¶

  • Keywords are reserved: You are not allowed to use them to name constants, variables, functions, or classes.
  • All keywords are in lowercase: Python defines all its keywords using lowercase letters only (e.g., if, while, return). Some exceptions like True, False, and None use capitalization for specific built-in constants.
  • Using a keyword as a variable name will result in a syntax error.
Useful Tip: To view all Python keywords available in your current interpreter version, use the `keyword`
In [ ]:
# Importing keyword module to list all Python reserved keywords
import keyword

print(keyword.kwlist)  # Outputs a list of all Python keywords
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
No Keyword Description
1 and Logical operator used to combine two conditional expressions.
2 as Used to assign an alias while importing modules or using context managers.
3 assert Used for debugging; raises an error if a given condition is false.
4 async Declares an asynchronous function or coroutine.
5 await Pauses coroutine execution until the awaited result is available.
6 break Exits the current loop prematurely.
7 class Defines a new user-defined class.
8 continue Skips the rest of the current loop iteration and moves to the next one.
9 def Defines a function or method.
10 del Deletes objects like variables, list items, or dictionary entries.
11 elif Else-if condition used in branching logic.
12 else Defines a block of code to run if preceding conditions are false.
13 except Catches exceptions in try blocks.
14 False Boolean value indicating "not true".
15 finally A block of code that always executes after try-except, regardless of errors.
16 for Used to iterate over a sequence (like list, tuple, or string).
17 from Used to import specific components from a module.
18 global Declares a global variable inside a function.
19 if Introduces a conditional statement.
20 import Imports entire modules or packages.
21 in Checks for membership in a collection (like list or set).
22 is Tests identity — whether two references point to the same object.
23 lambda Creates small anonymous (unnamed) functions.
24 None Represents a null or "no value" state.
25 nonlocal Declares variables from the nearest enclosing scope (not global).
26 not Logical operator that negates a boolean value.
27 or Logical operator where only one condition needs to be true.
28 pass A placeholder statement that does nothing — often used in empty blocks.
29 raise Triggers an exception manually.
30 return Exits a function and optionally sends back a value.
31 True Boolean value indicating "truth".
32 try Specifies a block to test for errors.
33 while Starts a loop that continues while a condition is true.
34 with Simplifies resource management (like file handling or context managers).
35 yield Ends a function and returns a generator instead of a single return value.

1. and (Logical Operator)¶

Point Description
Use Case The and keyword is a logical operator used to combine two Boolean conditions. It returns True only when both conditions evaluate to True.
Syntax condition1 and condition2
Parameter Values Both condition1 and condition2 must be Boolean expressions.

Logical Operation Behavior¶

Condition 1 Condition 2 Result (condition1 and condition2)
True True True
True False False
False True False
False False False

Useful Information¶

No. Point Description
1 Returns True Only if Both Conditions Are True If even one condition is False, the final result becomes False.
2 Short-Circuits on First False Python will not evaluate the second condition if the first is already False.
3 Used in Multi-Condition Validations Ideal for scenarios such as range checks, permission checks, or compound rules.
4 Supports Complex Expressions Each side of the and can be any valid expression that evaluates to True or False.
In [ ]:
age = 25
income = 55000

# Check if age is in an acceptable range AND income meets the minimum threshold
if age > 18 and income >= 50000:
    print("Input is valid")
else:
    print("Input does not meet the required criteria.")

# Store the result of the logical check
is_valid = (age > 18 and income >= 50000)
print(is_valid)  # Output: True
Input is valid
True

2. as (Keyword for Aliasing)¶

Point Description
Use Case The as keyword is used to assign an alias to a module, function, class, or exception, making it easier or more convenient to refer to it in code.
Syntax import module_name as alias_name
Parameter Values module_name is the actual module being imported, and alias_name is the name you want to use as its shorthand.

Useful Information¶

No. Point Description
1 Improves Code Readability Useful for shortening long module names or simplifying repeated references.
2 Common in Data Science Libraries Frequently used with libraries like numpy as np, pandas as pd, etc.
3 Can Alias Exceptions or Functions Not just for modules—you can also alias exceptions during try...except blocks.
4 Alias Must Be a Valid Identifier The alias name must follow Python variable naming rules.
In [ ]:
# Example: Using 'as' to create a short alias for a commonly used library
import pandas as pd

# Create a small sample DataFrame
data = {
    'Name': ['Alice', 'Bob'],
    'Score': [85, 92]
}

# Use the alias to create and display a DataFrame
df = pd.DataFrame(data)
print(df)

# Output:
#     Name  Score
# 0  Alice     85
# 1    Bob     92
    Name  Score
0  Alice     85
1    Bob     92

3. assert (Keyword for Debugging and Validation)¶

Point Description
Use Case The assert keyword is used to test whether a condition evaluates to True. If the condition is False, an AssertionError is raised. Commonly used for debugging, testing assumptions, and validating internal states.
Syntax assert condition[, optional_message]
Parameter Values condition is a Boolean expression. Optionally, you can provide a custom error message that is displayed when the assertion fails.

Useful Information¶

No. Point Description
1 Used for Debugging Helps catch bugs by verifying assumptions during development.
2 Raises AssertionError If the condition is False, the program halts with an error unless caught.
3 Optional Message for Clarity You can provide a message to describe what went wrong.
4 Can Be Disabled in Production Assertions are ignored when Python runs in optimized mode (python -O).
In [ ]:
# Basic usage of assert for debugging
x = "Intensity"

# This condition is True, so nothing happens
assert x == "Intensity"

# This condition is False, raises AssertionError
assert x == "coding"

# Output:
# Traceback (most recent call last):
#   File "demo.py", line X, in <module>
#     assert x == "goodbye"
# AssertionError
In [ ]:
# Example: Validate input
input_age = 17

# Assert that age is above a minimum threshold for model input
assert input_age >= 18, "Age must be 18 or older for model input."

# Output:
# Traceback (most recent call last):
#   File "validation.py", line 5, in <module>
#     assert input_age >= 18, "Age must be 18 or older for model input."
# AssertionError: Age must be 18 or older for model input.

4. async (Keyword for Declaring Asynchronous Functions)¶

Point Description
Use Case The async keyword is used to declare an asynchronous function, also known as a coroutine. These functions allow non-blocking execution using the await keyword for asynchronous operations.
Syntax async def function_name():
Parameter Values The function can accept parameters just like a normal function. async only changes the behavior of the function's execution flow.

Useful Information¶

No. Point Description
1 Defines a Coroutine Marks a function to be executed asynchronously using an event loop.
2 Must Be Paired with await Inside an async function, you use await to pause until a task completes.
3 Useful for I/O-Heavy Tasks Ideal for network calls, file access, and parallel data processing in AI workflows.
4 Cannot Be Called Like Normal Functions Must be awaited or scheduled via an event loop.
In [ ]:
# Async function to simulate delayed greeting
import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(1)  # Simulate a delay
    print("World")

# Compatible way to run in Jupyter/Colab
await greet()

# Output:
# Hello
# (waits 1 second)
# World
Hello
World

5. await (Keyword to Pause Coroutine Execution)¶

Point Description
Use Case The await keyword is used inside an async function to pause execution until the awaited coroutine (or awaitable object) completes. It allows non-blocking execution of asynchronous code.
Syntax await coroutine_or_awaitable
Parameter Values Accepts a coroutine, async function call, or any awaitable object (e.g., asyncio.sleep(), I/O tasks, API calls).

Useful Information¶

No. Point Description
1 Only Usable Inside async Functions You must define the enclosing function using async def.
2 Pauses Without Blocking the Event Loop Execution is paused at the await statement until the awaited task finishes.
3 Works With Built-in Async I/O Commonly used with asyncio.sleep(), aiohttp, file/network I/O, and async DB calls.
4 Enables Concurrency Multiple coroutines can run in parallel without blocking each other.
In [ ]:
# Async function to simulate delayed greeting
import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(1)  # Simulate a delay
    print("World")

# Compatible way to run in Jupyter/Colab
await greet()

# Output:
# Hello
# (waits 1 second)
# World
Hello
World

6. break (Keyword for Loop Termination)¶

Point Description
Use Case The break keyword is used to immediately exit a for or while loop when a specific condition is met, regardless of whether the loop has finished iterating.
Syntax break
Parameter Values The break statement does not take any parameters.

Useful Information¶

No. Point Description
1 Immediately Exits the Loop Skips the remaining loop iterations and exits the loop body.
2 Common in Conditional Loops Often used when a stopping condition occurs before reaching the loop's natural end.
3 Affects Only the Innermost Loop If nested, break only exits the loop where it’s written.
4 Often Combined with if Typically used inside an if condition to break based on logic.
In [ ]:
# Basic Example: Exit loop when value exceeds 5
for i in range(7):
    if i > 5:
        break
    print(i)

# Output:
# 0
# 1
# 2
# 3
0
1
2
3
4
5

7. class (Keyword for Defining Classes)¶

Point Description
Use Case The class keyword is used to define a class in Python, which acts as a blueprint for creating objects (instances). A class bundles data and functions (methods) together.
Syntax class ClassName:
Parameter Values The keyword itself takes no parameters, but the class may include attributes and methods within its body.

Useful Information¶

No. Point Description
1 Defines Custom Types Classes allow the creation of custom object types with attributes and behaviors.
2 Supports Object-Oriented Programming Enables encapsulation, inheritance, and polymorphism.
3 Class vs Instance Attributes defined directly under the class are shared; those defined inside __init__ are instance-specific.
In [ ]:
# Example: Define a class
class ModelInfo:
    model_name = "RandomForestClassifier"
    version = "1.0.2"
    trained_by = "Intensity Coding"
    accuracy = 0.93

# Accessing class-level attributes
print("Model:", ModelInfo.model_name)
print("Accuracy:", ModelInfo.accuracy)

# Output:
# Model: RandomForestClassifier
# Accuracy: 0.93
Model: RandomForestClassifier
Accuracy: 0.93

8. continue (Keyword for Skipping Loop Iterations)¶

Point Description
Use Case The continue keyword is used to skip the current iteration of a for or while loop and proceed to the next iteration. It is commonly used to ignore certain values or conditions during iteration.
Syntax continue
Parameter Values The continue statement does not accept any parameters.

Useful Information¶

No. Point Description
1 Skips Only Current Iteration The loop moves to the next item without executing remaining code in the current loop cycle.
2 Common in Filtering Useful to skip invalid, unwanted, or special cases in a loop.
3 Works in Both for and while Loops Supported in all loop types.
4 Often Paired with if Usually used inside conditional blocks to decide what to skip.
In [ ]:
# Basic Example: Skip when i is 5
for i in range(7):
    if i == 5:
        continue
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4
# 6
0
1
2
3
4
6

9. def (Keyword to Define a Function)¶

Point Description
Use Case The def keyword is used to define a function in Python. Functions are reusable blocks of code that perform specific tasks.
Syntax def function_name(parameters):
Parameter Values Functions can take zero or more parameters as input. Parameters are optional but help make functions more flexible.

Useful Information¶

No. Point Description
1 Enables Code Reuse Functions can be called multiple times to avoid repetition.
2 Can Accept Parameters Inputs to a function allow dynamic processing based on provided values.
3 Supports Return Values Functions can optionally return results using the return statement.
In [ ]:
# Basic Example: Defining and calling a function
def my_function():
    print("Hello from Intensity")

# Call the function
my_function()

# Output:
# Hello from Intensity
Hello from Intensity

10. del (Keyword to Delete Objects)¶

Point Description
Use Case The del keyword is used to delete objects in Python. This can include variables, list elements, dictionaries, object attributes, or even class definitions.
Syntax del object_name
Parameter Values object_name can be a variable, item, slice, or reference to any Python object.

Useful Information¶

No. Point Description
1 Deletes the Reference del removes the reference to an object, and the object is garbage-collected if no other references exist.
2 Works with Slices You can delete a specific index or range of items in a list using slicing.
3 Can Delete Entire Objects You can delete classes, dictionaries, or custom objects completely.
4 Raises NameError if Accessed After Deletion Attempting to use a deleted variable results in an error.
In [ ]:
# Basic Examples of using del
# Delete a variable
x = "Intensity"
del x
# print(x)  # Raises NameError because x is deleted
In [ ]:
# Delete an item from a list
fruits = [0,1,2,4,5]
del fruits[0]
print(fruits)  # Output: [1,2,3,4]
[1, 2, 4, 5]
In [ ]:
# Delete a class
class ModelClass:
    model_name = "ANN"

del ModelClass
# print(MyClass)  # Raises NameError

11. elif (Keyword for Multi-Branch Conditions)¶

Point Description
Use Case The elif keyword (short for else if) is used in conditional statements to handle multiple conditions in sequence. It allows you to check several expressions one by one.
Syntax if condition1: # code elif condition2:  #code else:  #code
Parameter Values Each elif is followed by a Boolean condition (like x == 0) that determines if its block should execute.

Useful Information¶

No. Point Description
1 Evaluated After if The elif block is only evaluated if the if condition is False.
2 Supports Multiple Branches You can have multiple elif conditions between if and else.
3 Stops at First Match Once a condition is True, Python skips the rest of the elif/else blocks.
In [ ]:
# Example: Categorize confidence levels
confidence_score = 0.62

if confidence_score > 0.85:
    print("High Confidence")
elif confidence_score >= 0.60:
    print("Medium Confidence")
else:
    print("Low Confidence")

# Output:
# Medium Confidence
Medium Confidence

12. else (Keyword for Default Branch & Post-Exception Handling)¶

Point Description
Use Case The else keyword defines a fallback block in an if statement when the condition is False, and a post-success block in a try…except construct when no exception is raised.
Parameter Values The else clause does not take parameters. It attaches to the preceding if or try…except block.

Syntax¶

# Conditional
if condition:
    …
else:
    …
# Exception handling
try:
    …
except SomeException:
    …
else:
    …

Useful Information¶

No. Point Description
1 Fallback in Conditionals Executes only if the if condition is False.
2 Post-Try Success Block In try…except…else, the else block runs only when no exception occurs.
3 Cannot Stand Alone Must follow an if or except block.
4 Improves Readability Separates the “success” path from error handling or default logic.
In [ ]:
# Example: Categorize confidence levels
confidence_score = 0.30

if confidence_score > 0.85:
    print("High Confidence")
elif confidence_score >= 0.60:
    print("Medium Confidence")
else:
    print("Low Confidence")

# Output:
# Low Confidence
Low Confidence
In [ ]:
# Basic Example: try…except…else
x = 6
try:
    # This code does not raise an exception
    result = x / 2
except ZeroDivisionError:
    print("Division by zero!")
else:
    print("No errors—result is", result)
    # Output: No errors—result is 3.0
No errors—result is 3.0

13. except (Keyword for Handling Exceptions)¶

Point Description
Use Case The except keyword is used in a try...except block to define a block of code that executes when an exception occurs in the try block. You can also catch specific exception types.
Parameter Values Optionally, you can specify an exception type (e.g., TypeError, ValueError) to catch only that kind of error. You can also catch all exceptions using a generic except: block.

Syntax¶

try:  
 # code that may raise an error  
except ExceptionType:  
 # code to handle that specific error  

Useful Information¶

No. Point Description
1 Used with try except must follow a try block and cannot be used on its own.
2 Catches Runtime Errors It handles errors like undefined variables, wrong data types, division by zero, etc.
3 Multiple except Blocks Allowed You can define different handlers for different error types.
4 Optional else Block Code under else runs only when no exception occurs.
5 Prevents Program Crashes Helps in creating robust and fault-tolerant code.
In [ ]:
def evaluate_model(score):
    try:
        if score > 0.9:
            print("Excellent model performance.")
        elif score > 0.7:
            print("Good model performance.")
        else:
            print("Model performance needs improvement.")
    except TypeError:
        print("Invalid score type. Please provide a numerical value.")
    except:
        print("Unexpected error during evaluation.")

# Test with valid and invalid inputs
evaluate_model(0.92)     # Output: Excellent model performance.
evaluate_model("high")   # Output: Invalid score type. Please provide a numerical value.
Excellent model performance.
Invalid score type. Please provide a numerical value.

14. False (Boolean Constant)¶

Point Description
Use Case The False keyword is a Boolean constant that represents a logical false value. It is often the result of comparison operations and conditions that evaluate to untrue.
Syntax False
Parameter Values It is a constant and does not take any parameters. It behaves like 0 in numeric contexts.

Useful Information¶

No. Point Description
1 Boolean Type False is one of Python’s two Boolean values (True and False).
2 Evaluates to 0 Internally, False behaves like the integer 0 in numeric operations.
3 Used in Conditions Returned from logical and comparison operations.
4 Case-Sensitive Must be written as False (capital F), not false.
In [ ]:
print(10 > 11)
print(7 in [1,2,3])
print("Intensity" is "coding")
print(4 == 6)
print(7 == 6 or 6 == 7)
print(4 == 6 and 6 == 8)
print("Intensity" is not "Intensity")
print(not(4 == 4))
print(3 not in [1,2,3])
False
False
False
False
False
False
False
False
False
<>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:7: SyntaxWarning: "is not" with a literal. Did you mean "!="?
<>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:7: SyntaxWarning: "is not" with a literal. Did you mean "!="?
/tmp/ipython-input-8-1210529282.py:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
  print("Intensity" is "coding")
/tmp/ipython-input-8-1210529282.py:7: SyntaxWarning: "is not" with a literal. Did you mean "!="?
  print("Intensity" is not "Intensity")

15. finally (Guaranteed Execution Block in Exception Handling)¶

Point Description
Use Case The finally keyword defines a block of code that is always executed after a try...except (and optionally else) block, regardless of whether an exception was raised or not.
Parameter Values The finally block does not take any parameters. It follows try, except, or else blocks.

Syntax¶

try:  
 # code that may raise an error  
except ExceptionType:  
 # handle the error  
finally:  
 # this always runs  

Useful Information¶

No. Point Description
1 Always Executes Runs whether or not an error occurred.
2 Common for Cleanup Tasks Often used to close files, release resources, or disconnect from databases.
3 Runs After try/except/else Executes last, after all error handling or success logic.
4 Optional but Useful Helps maintain reliability in code that manages external or sensitive resources.
In [ ]:
try:
    x > 5  # x is undefined, raises NameError
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")
finally:
    print("The try...except block is finished")

# Output:
# Something went wrong
# The try...except block is finished
Something went wrong
The try...except block is finished

16. for (Keyword for Looping Through Iterables)¶

Point Description
Use Case The for keyword is used to create a loop that iterates over a sequence (such as a list, tuple, string, or range). It is commonly used for repetitive tasks like processing data or traversing structures.
Syntax for variable in iterable:
Parameter Values The iterable can be a list, string, tuple, dictionary, set, or any object that implements the iterator protocol.

Useful Information¶

No. Point Description
1 Sequence-Based Iteration Iterates over elements one by one in the given sequence.
2 Works With Ranges Commonly used with range() to create numeric loops.
3 Loop Variable Changes Per Iteration The loop variable is assigned each item of the sequence on each loop cycle.
In [ ]:
# Loop through numbers 1 to 5
for x in range(1, 6):
    print(x)

# Output:
# 1
# 2
# 3
# 4
# 5
1
2
3
4
5

17. from (Keyword for Selective Importing)¶

Point Description
Use Case The from keyword is used to import specific parts (like functions, classes, or constants) from a Python module, rather than importing the entire module.
Syntax from module_name import object_name
Parameter Values module_name: The name of the module (e.g., datetime)
object_name: The specific function/class/variable to import (e.g., time)

Useful Information¶

No. Point Description
1 Reduces Namespace Clutter Only imports what’s needed instead of the whole module.
2 Enables Direct Use Imported items can be used without module prefix (e.g., time() instead of datetime.time()).
3 Supports Aliasing Can be used with as to rename the imported object.
In [ ]:
from datetime import time

# Create a time object representing 5:00 PM
x = time(hour=17)
print(x)

# Output:
# 17:00:00
17:00:00

18. global (Keyword to Declare Global Scope Variables)¶

Point Description
Use Case The global keyword is used inside a function to refer to or create a global variable — one that exists outside the function’s local scope.
Syntax global variable_name
Parameter Values The variable_name is the identifier to be treated as global. No additional parameters are accepted.

Useful Information¶

No. Point Description
1 Affects Variable Scope Allows a variable defined inside a function to persist outside of it.
2 Avoids Local Binding Without global, assignments inside functions create local variables.
3 Should Be Used Cautiously Overuse may lead to hard-to-debug code due to unintended side effects.
4 Useful in Simple State Sharing Helpful in small scripts where a shared state is needed across multiple functions.
In [ ]:
# Define a function that modifies a global variable
def myfunction():
    global x
    x = "intensity"

# Call the function
myfunction()

# x is now available in the global scope
print(x)  # Output: intensity
intensity

19. if (Keyword for Conditional Execution)¶

Point Description
Use Case The if keyword is used to create conditional statements. It allows execution of a specific block of code only when a condition evaluates to True.

| Syntax | if condition: # block of code
| Parameter Values | The condition is any expression that evaluates to a Boolean (True or False). |

Useful Information¶

No. Point Description
1 Starts a Conditional Block The code block under if executes only if the condition is True.
2 Can Be Combined with else else executes a fallback block when the condition is False.
3 Works with elif Allows building multi-branch decision logic using if...elif...else.
In [ ]:
accuracy = 0.88

if accuracy >= 0.90:
    print("Model is Excellent")
elif accuracy >= 0.75:
    print("Model is Good")
else:
    print("Model needs improvement")

# Output:
# Model is Good
Model is Good

20. import (Keyword for Bringing External Modules into Scope)¶

Point Description
Use Case The import keyword is used to include external Python modules or libraries into the current script, giving access to their classes, functions, and variables.
Syntax import module_name
Parameter Values Accepts the name of the module to import. You can import built-in, third-party, or custom modules.

Useful Information¶

No. Point Description
1 Enables Code Reuse Grants access to code from standard libraries and external packages.
2 Must Be at Top-Level Usually placed at the top of the script for clarity and organization.
3 Can Be Combined with as Used to assign an alias to the module (e.g., import numpy as np).
In [ ]:
import datetime

# Get the current date and time
x = datetime.datetime.now()
print(x)
2025-06-25 11:09:10.896099

21. in (Keyword for Membership Testing and Iteration)¶

Point Description
Use Case The in keyword is used for two main purposes: (1) to check if a value exists within a sequence, and (2) to loop through elements in a sequence using a for loop.

| Syntax | value in sequence — for membership test | | for variable in sequence: — for iteration | | Parameter Values | Accepts any iterable (e.g., list, tuple, string, set, dictionary, range, etc.). |

Useful Information¶

No. Point Description
1 Checks Membership Returns True if the value exists in the given iterable.
2 Drives Iteration Used in for loops to iterate over sequence elements.
3 Common in Conditions Often used in if statements to validate presence of an item.
In [ ]:
# Example 1: Membership Testing

# Check if a label exists in a list of target labels
target_labels = ["cat", "dog", "bird"]

if "dog" in target_labels:
    print("Label 'dog' is present.")

# Output:
# Label 'dog' is present.
Label 'dog' is present.
In [ ]:
# Example 2: Iterating Through a List

# Iterate through model evaluation metrics
metrics = ["accuracy", "precision", "recall"]

for metric in metrics:
    print("Evaluating:", metric)

# Output:
# Evaluating: accuracy
# Evaluating: precision
# Evaluating: recall
Evaluating: accuracy
Evaluating: precision
Evaluating: recall

22. is (Keyword for Identity Comparison)¶

Point Description
Use Case The is keyword is used to check whether two variables reference the exact same object in memory. It returns True only if both variables point to the same object (not just equal values).
Syntax object1 is object2
Parameter Values Accepts any valid Python object (e.g., list, dict, string, custom objects, etc.).

Useful Information¶

No. Point Description
1 Checks Identity, Not Equality is checks memory identity, while == checks value equality.
2 Use With Care Objects that look the same (same values) may not be the same object.
3 Often Used for Singleton Checks Commonly used to compare with None, e.g., if x is None.
4 Useful in Debugging Object References Helps determine whether variables reference the same underlying object.
In [ ]:
# Example 1: Same Values, Different Objects

x = ["accuracy", "precision", "recall"]
y = ["accuracy", "precision", "recall"]

print(x == y)  # True: Values are equal
print(x is y)  # False: Different objects in memory
True
False
In [ ]:
# Example 2: Same Object in Memory

x = ["accuracy", "precision", "recall"]
y = x  # y refers to the same object as x

print(x is y)  # True: Both refer to the same memory location
True

23. lambda (Anonymous Function Keyword)¶

Point Description
Use Case The lambda keyword is used to define small, anonymous (unnamed) functions in a single line of code. These functions can take any number of arguments but must contain only one expression, which is implicitly returned.
Syntax lambda arguments: expression
Parameter Values Accepts any number of input arguments

| | Can include default parameters (optional) | | Only one expression is allowed (no statements like loops or assignments) |

Useful Information¶

No. Point Description
1 Returns a Function Object A lambda expression creates and returns a function object just like def.
2 Useful for Short Tasks Ideal for short, inline functions often used with map(), filter(), sorted(), etc.
3 Cannot Contain Multiple Statements Only a single expression is allowed — no loops, assignments, or return.
In [ ]:
# Lambda function with one argument
x = lambda a: a * 10
print(x(3))  # Output: 30

# Lambda function with multiple arguments
x = lambda a, b, c: a * b * c
print(x(1,2,3))  # Output: 6
30
6

24. None (Represents Null or Absence of Value)¶

Point Description
Use Case The None keyword is used to indicate no value, no result, or null state. It represents a special built-in constant in Python and is commonly used to initialize variables or signal missing data.
Syntax variable = None
Parameter Values None is a singleton object — it does not take any parameters and is always written with a capital N.

Useful Information¶

No. Point Description
1 Represents "Nothing" Used to denote absence of a value or uninitialized state.
2 Type is NoneType It's a distinct data type (type(None) returns NoneType).
3 Not Equal to Other Falsy Values None is not the same as 0, False, or an empty string ("").
In [ ]:
x = None
print(x)
None
In [ ]:
response = None  # No response received yet

print("Response value:", response)  # Output: Response value: None

if response:
    print("Response is considered True.")
elif response is False:
    print("Response is explicitly False.")
elif response is None:
    print("Response is None — no value was assigned yet.")

# Output:
# Response value: None
# Response is None — no value was assigned yet.
Response value: None
Response is None — no value was assigned yet.

25. nonlocal (Keyword for Referencing Outer Non-Global Variables)¶

Point Description
Use Case The nonlocal keyword is used to indicate that a variable belongs to an enclosing (non-global) scope, typically when working with nested functions. It allows the inner function to modify the outer function’s variable.
Syntax nonlocal variable_name
Parameter Values Only the name of a variable declared in the immediate outer enclosing function. It cannot reference global or top-level variables.

Useful Information¶

No. Point Description
1 Modifies Enclosing Scope Variable Without nonlocal, assigning a value in the inner function creates a new local variable.
2 Works Only in Nested Functions Cannot be used at the top level — must exist within a nested structure.
3 Different from global nonlocal affects enclosed scopes, whereas global targets the module/global scope.
4 Useful in Closures Often used in decorators, closures, or functions returning functions.

Basic Example: Using nonlocal in Nested Functions¶

In [ ]:
def outer():
    msg = "original"

    def inner():
        nonlocal msg
        msg = "modified inside inner function"

    inner()
    return msg

print(outer())

# Output:
# modified inside inner function
modified inside inner function

Comparison Example: Without nonlocal¶

In [ ]:
def outer():
    msg = "original"

    def inner():
        msg = "changed locally"  # This creates a new local variable

    inner()
    return msg

print(outer())

# Output:
# original
original

26. not (Logical Negation Operator)¶

Point Description
Use Case The not keyword is a logical operator used to invert the truth value of a Boolean expression. If the expression is True, not makes it False, and vice versa.
Syntax not condition
Parameter Values Accepts any expression that evaluates to True or False.

Useful Information¶

No. Point Description
1 Inverts Boolean Values not True becomes False, and not False becomes True.
2 Used in Conditional Logic Often used in if statements to check for the absence of a condition.
3 Works with Comparisons Can be used to reverse conditions like not x > 5 (i.e., x <= 5).
In [ ]:
x = False
print(not x)  # Output: True
True

27. or (Logical OR Operator)¶

Point Description
Use Case The or keyword is a logical operator used to combine multiple conditions. It returns True if at least one of the conditions is True.
Syntax condition1 or condition2
Parameter Values Accepts two or more expressions that evaluate to Boolean (True or False).

Useful Information¶

No. Point Description
1 Short-Circuit Evaluation If the first condition is True, the second is not evaluated.
2 Works With Boolean and Comparisons Can combine comparisons like x > 5 or x == 0.
3 Useful in Defaults Often used to assign default values: x = input_val or "default".

Logical OR Behavior Table¶

Condition A Condition B A or B
True True True
True False True
False True True
False False False
In [ ]:
x = (7 > 5 or 1 > 10)
print(x)  # Output: True
True
In [ ]:
gpu_available = False
tpu_available = True

# Use logical OR to check if at least one accelerator is available
if gpu_available or tpu_available:
    print("Training will proceed using available hardware acceleration.")
else:
    print("No GPU or TPU available. Training cannot continue.")

# Output:
# Training will proceed using available hardware acceleration.
Training will proceed using available hardware acceleration.

28. pass (Null Statement / Placeholder Keyword)¶

Point Description
Use Case The pass statement is used as a placeholder where syntactically some code is required but no action needs to be taken. It prevents errors due to empty code blocks.
Syntax pass
Parameter Values The pass statement takes no arguments. It simply does nothing when executed.

Useful Information¶

No. Point Description
1 Prevents Syntax Errors Used where a code block is required but no logic is implemented yet.
2 Useful During Prototyping Helps define the structure of functions, loops, or classes before implementing actual logic.
3 Common in Conditional Branching Allows stubbing of branches like if, elif, else, try, except without causing syntax errors.
4 Different From None pass is a control flow statement, whereas None is a data type.
In [ ]:
# Empty function definition
def preprocess_data():
    pass  # Implementation to be added later

# Empty class definition
class DataModel:
    pass  # Placeholder for class attributes and methods

# Empty loop
for i in range(3):
    pass  # Loop intentionally does nothing

29. raise (Used to Trigger Exceptions Manually)¶

Point Description
Use Case The raise keyword is used to manually trigger an exception in your code. It can be used with built-in exception types or custom exceptions to handle invalid states or unexpected inputs.
Syntax raise ExceptionType("custom error message")
Parameter Values Accepts any exception class (e.g., ValueError, TypeError, Exception, or custom-defined exceptions) along with an optional error message.

Useful Information¶

No. Point Description
1 Interrupts Program Flow Raising an exception stops execution unless caught by a try...except block.
2 Accepts Custom Error Messages Provides context for debugging and user feedback.
3 Common in Validation and Input Checks Frequently used to validate inputs in functions, APIs, or ML models.
4 Can Be Used with Custom Exceptions You can define your own error classes for advanced error handling.
In [ ]:
# Example 1: Raise Exception if Value is Invalid
x = -5

if x < 0:
    raise Exception("Negative values are not allowed")

# Output:
# Exception: Negative values are not allowed
In [ ]:
# Example 2: Raise TypeError for Invalid Data Type
x = "intensity"

if not isinstance(x, int):
    raise TypeError("Only integers are allowed")

# Output:
# TypeError: Only integers are allowed

30. return (Exit a Function and Send Back a Result)¶

Point Description
Use Case The return keyword is used to exit a function and optionally send back a result to the caller. It stops execution of the function immediately.
Syntax return [expression]
Parameter Values An optional expression or value to return (e.g., integer, string, list, object, etc.). If omitted, the function returns None by default.

Useful Information¶

No. Point Description
1 Ends Function Execution Any code after return will not be executed.
2 Can Return Any Data Type Supports returning numbers, strings, lists, tuples, objects, etc.
3 Multiple Values Can Be Returned You can return multiple values using a tuple (return a, b).
In [ ]:
def multiplication():
    return 3 * 3
    print("This line will not run.")

result = multiplication()
print("Result:", result)

# Output:
# Result: 9
Result: 9

31. True (Boolean Constant Representing Truth)¶

Point Description
Use Case The True keyword represents the Boolean value truth in Python. It's commonly used in conditions, logical operations, and control flow.
Syntax True
Parameter Values True is a built-in constant with a fixed value of 1. It accepts no arguments.

Useful Information¶

No. Point Description
1 Equivalent to 1 Internally, True == 1 evaluates to True.
2 Used in Conditions Commonly used in if, while, and other conditional blocks.
3 Result of Comparison Comparison operations like 5 > 3 return True.
4 Not the Same as 'True' "True" (string) is different from the Boolean True.
In [ ]:
print(7 < 10)                   # True
print(7 in [7, 8, 9])          # True
print(7 is 7)                  # True
print(7 == 7)                  # True
print(4 == 4 or 6 == 7)        # True
print(5 == 5 and 7 == 7)       # True
print("intensity" is not "coding")  # True
print(not(5 == 7))             # True
print(4 not in [1, 2, 3])      # True
True
True
True
True
True
True
True
True
True
<>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:7: SyntaxWarning: "is not" with a literal. Did you mean "!="?
<>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:7: SyntaxWarning: "is not" with a literal. Did you mean "!="?
/tmp/ipython-input-45-142740151.py:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
  print(7 is 7)                  # True
/tmp/ipython-input-45-142740151.py:7: SyntaxWarning: "is not" with a literal. Did you mean "!="?
  print("intensity" is not "coding")  # True

32. try (Start of an Exception-Handling Block)¶

Point Description
Use Case The try keyword is used to wrap a block of code that may potentially cause an error. If an error occurs, it allows graceful handling using except.
Parameter Values Does not accept parameters. Works with the paired except, else, and finally blocks.

Syntax¶

try:  
    # code to test  
except ExceptionType:  
    # code to handle the error  

Useful Information¶

No. Point Description
1 Prevents Program Crashes Allows catching errors to keep the application running.
2 Can Handle Specific Exceptions Use different except blocks for different error types.
3 Can Be Combined with else and finally else runs if no error occurs; finally always runs.
In [ ]:
def evaluate_model(score):
    try:
        if score > 0.9:
            print("Excellent model performance.")
        elif score > 0.7:
            print("Good model performance.")
        else:
            print("Model performance needs improvement.")
    except TypeError:
        print("Invalid score type. Please provide a numerical value.")
    except:
        print("Unexpected error during evaluation.")

# Test with valid and invalid inputs
evaluate_model(0.92)     # Output: Excellent model performance.
evaluate_model("high")   # Output: Invalid score type. Please provide a numerical value.
Excellent model performance.
Invalid score type. Please provide a numerical value.

33. while (Create a Conditional Loop)¶

Point Description
Use Case The while keyword is used to create a loop that continues executing as long as a specified condition remains True.
Syntax while condition: # block of code
Parameter Values Accepts a condition that evaluates to True or False. Execution stops when the condition becomes False.

Useful Information¶

No. Point Description
1 Requires Manual Update The loop control variable must be updated inside the loop to avoid infinite looping.
2 Runs Zero or More Times If the condition is initially False, the loop will not run.
3 Often Used for Unknown Iteration Counts Best used when the number of iterations isn’t known ahead of time.
In [ ]:
x = 0

while x < 5:
    print(x)
    x += 1

# Output:
# 0
# 1
# 2
# 3
# 4
0
1
2
3
4

34. with (Context Manager for Resource Management)¶

Point Description
Use Case The with keyword is used to wrap the execution of a block of code within methods defined by a context manager (e.g., open files, lock resources, manage sessions). It ensures proper setup and cleanup of resources.
Syntax with expression [as variable]:
Parameter Values Accepts any object that implements context management methods (__enter__() and __exit__()) such as files, database connections, or custom classes.

Useful Information¶

No. Point Description
1 Automatically Closes Resources Frees file handles, memory, or locks after execution completes — even if an error occurs.
2 Cleaner Than Manual try...finally Eliminates the need for explicit cleanup blocks.
3 Common in File and Model Management Ideal for file reading/writing, opening datasets, or loading models.
4 Can Be Used with Multiple Contexts Supports managing multiple resources in a single with statement.
In [ ]:
# Using 'with' to handle file operations
with open("data.txt", "r") as file:
    content = file.read()
    print(content)

# No need to call file.close() — it's handled automatically.
Intensity Coding

35. yield (Create a Generator from a Function)¶

Point Description
Use Case The yield keyword is used in place of return to produce a generator, allowing a function to return values one at a time and pause its state between each call. Useful for memory-efficient iteration.
Syntax yield expression
Parameter Values Accepts an expression (like a value or object) to yield to the caller. Execution resumes from the same point on next call.

Useful Information¶

No. Point Description
1 Creates a Generator The function returns a generator object instead of a final value.
2 Supports Lazy Evaluation Values are computed on demand, not all at once.
3 Retains Function State Execution pauses at yield and resumes from there on the next iteration.
4 Cannot Use return with a Value If return is used in a generator, it ends the generator (optionally with StopIteration).
In [ ]:
def generate_numbers():
    for i in range(3):
        yield i

gen = generate_numbers()
for num in gen:
    print(num)

# Output:
# 0
# 1
# 2
0
1
2
Category
Python Natural Language Processing Generative AI
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing
  • Generative AI

Tags

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer