Assignment |
Assigns a value to a variable. |
x = 10 |
Uses the = operator to store a value in a variable. |
Augmented Assignment |
Combines an arithmetic operation with assignment. |
x += 5 |
Short form for x = x + 5 . Similar operators include -= , *= , /= , and %= . |
Expression |
A combination of values, variables, and operators that produces a result. |
y = x + 2 * 3 |
Python evaluates the expression and assigns the result to y . |
Print |
Outputs a message or value to the console. |
print("Hello World") |
The print() function is used to display output. |
If Statement |
Executes a block of code if a condition is true. |
if x > 0: print("Positive") |
Used for conditional execution. |
If-Else Statement |
Provides an alternative block of code if the if condition is false. |
if x > 0: print("Positive") else: print("Zero") |
Executes the else block if the condition in if is false. |
Elif Statement |
Provides multiple conditional checks. |
if x > 0: print("Positive") elif x < 0: print("Negative") |
Checks multiple conditions in sequence. |
For Loop |
Iterates over a sequence (list, tuple, string, etc.). |
for i in range(5): print(i) |
Repeats a block of code for each element in a sequence. |
While Loop |
Repeats a block of code while a condition is true. |
while x > 0: x -= 1 |
Continues looping until the condition becomes false. |
Break |
Exits the nearest enclosing loop prematurely. |
for i in range(10): if i == 5: break |
Immediately stops the loop execution. |
Continue |
Skips the rest of the current loop iteration. |
for i in range(10): if i == 5: continue |
Skips to the next iteration of the loop. |
Pass |
A null operation; does nothing. |
if x > 0: pass |
Used as a placeholder in code where syntax requires a statement but nothing needs to be done. |
Return |
Exits a function and optionally returns a value. |
def add(x, y): return x + y |
Used to send a result back to the caller of a function. |
Import |
Loads a module for use in the current script. |
import math |
Enables access to functions and variables defined in a module. |
From-Import |
Imports specific parts of a module. |
from math import pi, sqrt |
Allows selective import of module contents. |
Try-Except |
Handles exceptions (runtime errors) gracefully. |
try: x = 1 / 0 except ZeroDivisionError: pass |
Catches and handles specific exceptions. |
Try-Finally |
Ensures that a block of code is executed no matter what. |
try: x = 1 / 0 finally: print("Done") |
The finally block is always executed after the try , regardless of exceptions. |
Raise |
Manually raises an exception. |
raise ValueError("Invalid input") |
Used to signal an error condition. |
With |
Simplifies resource management (e.g., opening files). |
with open("file.txt") as f: |
Ensures proper cleanup of resources, such as closing a file. |
Global |
Declares a variable as global, allowing it to be modified inside a function. |
global count |
Makes count a global variable so that changes persist outside the function. |
Nonlocal |
Refers to a variable in the nearest enclosing scope that is not global. |
nonlocal x |
Used in nested functions to modify variables from the outer, non-global scope. |
Del |
Deletes an object or a variable reference. |
del my_list[0] |
Removes the first element from my_list . |
Lambda |
Creates an anonymous (inline) function. |
add = lambda x, y: x + y |
Defines a small, unnamed function in a single line. |
Yield |
Pauses a generator and returns a value to the caller. |
yield x |
Used in generator functions to produce a sequence of values lazily. |
Assertion |
Tests an assumption, raising an error if the assumption is false. |
assert x > 0, "x must be positive" |
Used for debugging to ensure conditions are met. |
List Comprehension |
A concise way to create lists. |
[x**2 for x in range(10) if x % 2 == 0] |
Creates a list of squares of even numbers from 0 to 9. |
Dictionary Comprehension |
A concise way to create dictionaries. |
{x: x**2 for x in range(5)} |
Creates a dictionary where keys are numbers and values are their squares. |
Function Definition |
Defines a function. |
def greet(name): print(f"Hello, {name}") |
Functions encapsulate reusable blocks of code. |
Class Definition |
Defines a class. |
class MyClass: |
Classes encapsulate data and behavior in object-oriented programming. |
Docstring |
A string that documents a module, class, or function. |
"""This is a docstring""" |
Used as the first statement in a block to provide documentation. |