Integer Representations
Python supports integers in four different number systems, identified by their specific prefixes:
- Decimal: The standard base-10 format.
- Binary: Prefixed with
0bor0B(e.g.,0b1010is 10). - Octal: Prefixed with
0oor0O(e.g.,0o17is 15). - Hexadecimal: Prefixed with
0xor0X. It uses digits 0-9 and letters A-F (case-insensitive) to represant values 10-15.
# Hexadecimal example
primary_hex = 0x1A
secondary_hex = 0Xff
print(f"Value 1: {primary_hex}") # 26
print(f"Value 2: {secondary_hex}") # 255
# Binary example
bit_mask_low = 0b101
bit_mask_high = 0B1111
print(f"Low: {bit_mask_low}, High: {bit_mask_high}")
To improve the readability of large numbers, Python 3 allows the use of underscores as visual separators. These do not affect the numeric value.
total_count = 1_000_000_000
print(total_count) # 1000000000
Floating-Point and Complex Numbers
Floating-point numbers represent real numbers with fractional parts. They can be expressed in standard decimal notation or scientific notation (e.g., 3.14e-2).
Complex numbers consist of a real part and an imaginary part, with the latter denoted by the suffix j or J. For advanced complex number operations, the cmath module provides specialized mathematical functions.
String Handling and Manipulation
The input() functon prompts the user for data and always returns the input as a string type.
Multi-line and Raw Strings
Triple quotes (''' or """) define long strings spanning multiple lines. While often used for documentation or multi-line comments, they are technically string literals. If not assigned to a variable, they are ignored by the interpreter.
prose = """First line of text
Second line with "quotes"
Third line of the block"""
print(prose)
You can use a backslash (\) to continue a single string across multiple lines in code without adding a newline character to the string content.
path_fragment = "C:\\Users\\Admin\\Documents\\" \
"projects\\source"
Raw strings, prefixed with r, treat backslashes as literal characters, which is particularly useful for Windows file paths or regular expressions.
raw_path = r'C:\new_folder\test.txt'
print(raw_path)
Basic String Methods
split(): Breaks a string in to a list based on a delimiter.join(): Concatenates a sequence of strings into one using a specific connector.
Operators and Expressions
Arithmetic and Bitwise
Python distinguishes between standard division and floor division:
/performs floating-point division (e.g.,7 / 2is3.5).//performs floor division, discarding the remainder (e.g.,7 // 2is3).
Slicing and Indexing
The indexing operator allows for advanced slicing using the syntax [start:end:step].
alphabet = "abcdefghijk"
# Slice from index 1 to 9 with a step of 2
print(alphabet[1:9:2]) # "bdfh"
Conditional Expressions (Ternary Operator)
Python provides a concise way to write if-else logic in a single line: X if condition else Y. The expression evaluates condition first; if true, it returns X, otherwise it returns Y.
Membership Testing
The in operator checks for the existence of a substring within a string or an element within a sequence (like a list or tuple).
Variables and Functions
Variable Naming and Assignment
Variables must begin with a letter or an underscore and can contain alphanumeric characters. Python is case-sensitive and prohibits using reserved keywords as identifiers. You can assign values to multiple variables simultaneously:
x, y, z = 10, 20, 30
Function Definitions
A function is a named block of code designed to perform a specific task. It consists of a header and a body.
- Header: Defined with the
defkeyword, followed by the function name and parameters in parentheses. - Body: A block of indented code. It typically ends with a
returnstatement, though this is optional. If noreturnis specified, the function returnsNone.
def calculate_area(width, height):
area = width * height
return area
result = calculate_area(5, 10)
Built-in Utilities and Scope
Python includes several built-in functions for common operations:
abs(x): Absolute value.max(...)/min(...): Extremum values.pow(base, exp): Exponentiation.round(x, n): Rounding tondecimal places.
Variables defined inside a function exist in the local scope and are not accessible outside that function. Functions can be composed, where the output of one function serves as the input to another, evaluated from the innermost call outward.