Reserved Keywords
Python utilizes a specific set of keywords that hold special meaning within the language syntax. These identifiers are reserved and cannot be used as variable names or function identifiers. There are approximately 30 such keywords, categorized by their function:
- Boolean Values:
True,False,None - Logical Operators:
and,or,not - Control Flow:
if,elif,else,while,for - Loop Control:
break,continue,pass - Function Definition:
def,return,lambda - Class & Object:
class,is,in - Exception Handling:
try,except,finally,raise - Module Management:
import,from,as,with - Scope Declaration:
global,nonlocal
These keywords insure structural consistency and prevent naming conflicts. For instance, attempting to assign a value to a keyword results in a syntax error.
# Invalid usage causing SyntaxError
# True = 1
Functions
Functions encapsulate reusable blocks of code. They accept arguments, process data, and optionally return results. This modular approach enhances readability and maintenance.
Built-in Functions
Python includes pre-defined functions available without imports.
print(): Outputs data to the standard console.input(): Pauses execution to capture user input as a string.type(): Returns the data type of a object.
# Displaying system status
print("System Ready")
# Capturing user input
user_id = input("Enter User ID: ")
print("Welcome,", user_id)
# Checking data types
print(type(100)) # <class 'int'>
print(type("Data")) # <class 'str'>
User-Defined Functions
Custom functions are created using the def keyword.
def show_status():
print("Operation Successful")
# Calling the function
show_status()
Advanced concepts include anonymous functions (lambda), recursion, and decorators.
Variables
Variables act as labels for memory locations storing data values. Python uses dynamic typing, meaning the type is inferred from the assigned value.
- Naming Rules: Must start with a letter or underscore, followed by letters, numbers, or underscores. Case-sensitive.
- Assignment: Uses the
=operator to bind a value to a name.
# Variable assignment
count = 50
message = "Processing"
# Reassignment
count = 100
message = "Complete"
print(count)
print(message)
Data Types
Data types classify the nature of the stored value.
- int: Whole numbers (e.g.,
5). - float: Decimal numbers (e.g.,
3.14). - str: Text enclosed in quotes (e.g.,
"Hello"). - Others:
list,tuple,dict,set,bool,NoneType.
price = 19.99
item = "Widget"
available = True
Operators
Operators perform operations on variables and values. Precedence determines the order of evaluation.
- Parentheses:
() - Exponentiation:
** - Unary:
+x,-x - Multiplicative:
*,/,%,// - Additive:
+,- - Comparison:
==,!=,>,< - Logical:
not,and,or
Short-Circuit Logic
Logical operators evaluate left-to-right and stop when the result is determined.
x = 10
y = 0
# OR short-circuit: If first is True, second is skipped
result = (x > 5) or (1/y)
print(result) # True
# AND short-circuit: If first is False, second is skipped
result = (x < 5) and (1/y)
print(result) # False
Exception Handling
Exceptions manage runtime errors to prevent crashes. Key keywords include try, except, finally, and raise. This mechanism allows graceful recovery from unexpected conditions.
Control Structures
Control structures dictate the flow of execution.
- Conditionals:
if,elif,elseexecute blocks based on boolean conditions. - Loops:
forandwhilerepeat blocks until a condition is met.
Data Structures
Python provides built-in structures for data organization.
- List: Ordered, mutable sequence.
- Tuple: Ordered, immutable sequence.
- Dictionary: Unordered key-value pairs.
- Set: Unordered collection of unique elements.
- String: Immutable character sequence.
Object-Oriented Programming (OOP)
OOP organizes code into objects containing data (attributes) and methods (functions). This paradigm promotes modularity and code reuse through classes and inheritance.
File Operations
File handling involves reading from and writing to storage using the open() function.
# Reading a file
log_file = open("record.log", "r")
content = log_file.read()
print(content)
log_file.close()
# Writing to a file
out_file = open("output.log", "w")
out_file.write("Log entry 1\n")
out_file.write("Log entry 2\n")
out_file.close()
Methods like seek() allow pointer manipulation for random access.
Modules and Libraries
Code is organized into modules (.py files) and libraries (collections of modules).
# Importing standard library
import math
print(math.sqrt(16)) # 4.0
# Importing third-party library
import numpy as np
data = np.array([1, 2, 3])
print(data)
Imports enable functionality reuse across different scripts.