Terminate execution when no input is provided:
import sys
print("No input detected, terminating.")
sys.exit()
Safely open and read a file:
try:
handle = open(file_path, "r")
except IOError:
print("Failed to open file:", file_path)
sys.exit()
content = handle.read()
handle.close()
print(content)
String Definition and Multiline Handling
Strings may use single ('), double ("), or triple quotes ("""). Triple quotes allow multiline literals without escape sequences. For line breaks in double-quoted strings, use backslashes:
chunk = "112" \
+ "33" \
+ "44"
print(chunk)
print('\a' + r'\n') # raw string disables escape processing
Multiple Statements per Line
Separate sequential statements with semicolons:
user_name = input("\n\nEnter name:"); print("Received:", user_name)
Variable Assignment Patterns
Assign a common value to several variables at once, or assign distinct values in one line:
x = y = z = 1
u, v, w = 1, 2, "123dd"
String Slicing and Repetition
sample = "abcdefghijklmn"
print(sample * 2)
print(sample[0])
print(sample[2:6])
print(sample[3:])
print(sample + "___new characters")
List, Tuple, and Dictionary Usage
Listss permit item modification; tuples are immutable:
arr = [1, 2, 3, 4, 6, 'g', 'h', 'j']
immutable_seq = (1, 2, 3, 'f', 'g', 'h', 't', 'h')
lookup = {}
lookup["key_one"] = 123
lookup["key_two"] = 456
print(arr, immutable_seq)
print(arr[2])
print(lookup["key_one"], lookup["key_two"], lookup)
print(repr(arr))
print(eval("13"))
Type Conversion Functions
| Function | Purpose |
|---|---|
int(x [, base]) |
Convert to integer |
float(x) |
Convert to floating point |
complex(real [, imag]) |
Create complex number |
str(x) |
Convert to string |
repr(x) |
Convert to printable expression |
eval(str) |
Evaluate string as Python expression |
tuple(s) |
Convert iterable to tuple |
list(s) |
Convert iterable to list |
set(s) |
Convert iterable to set |
dict(d) |
Convert to dictionary |
chr(x) |
Integer to Unicode character |
ord(x) |
Character to integer code |
hex(x) |
Integer to hexadecimal string |
oct(x) |
Integer to octal string |
Operators
Python supports arithmetic, bitwise, comparison, and assignment operators. Note the absence of increment/decrement operators (++, --):
print(2 ** 2) # exponentiation
print(12 // 5) # floor division
Pass Statement
pass acts as a placeholder for empty blocks:
for ch in 'Python':
pass
print('Letter:', ch)
length = len('Python')
idx = 0
while idx < length:
print("Index:", idx)
idx += 1
Built-in Numeric Types
Python provides int, legacy long (merged into int in Python 3), float, and complex types for numerical computation.