Basic Operations and Tricks in Python Basic Operations and Tricks in Python Basic Operations and Tricks in Python Basic Operations and Tricks in Python Basic Operations and Tricks in Python
Programming Programming Programming
Python Python
ProgrammingPython
Table of Contents
Reading Data From stdin
Python 3 - Read all input at once
import sys See [Python Guide](/programming/python/) for more context. See [Python Guide](/programming/python/) for more context.# Read all data as a stringdata = sys.stdin.read()
# Split into a list of stringsdata = data.split()
# Press Ctrl+D (Linux/Mac) or Ctrl+Z (Windows) to complete input
Python 3 - Read line by line
import sys
# Read single lineline = sys.stdin.readline().strip()
# Read multiple linesfor line in sys.stdin:
process(line.strip())
Reading structured input
# Read two integers from first linen_tables, n_queries =map(int, input().split())
# Read a list of integers from second linecounts =list(map(int, input().split()))
Reading Data in Bash Shell
# Redirect file to stdinpython3 main.py < tests/test.txt
# Pipe data to stdinecho"1 2 3" | python3 main.py
# Here documentpython3 main.py << EOF
1 2 3
4 5 6
EOF
Creating Lists of Numbers
n =10# Initialize all values to the same number (1D only)# WARNING: Don't use this for 2D arrays - use list comprehension or numpyl1 = [1] * n
# Result: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]# Create sequence of numbersl2 =list(range(n))
# Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# Range with start and stepl3 =list(range(1, 11, 2))
# Result: [1, 3, 5, 7, 9]# Create 2D array (correct way)rows, cols =3, 4matrix = [[0] * cols for _ inrange(rows)]
# Using numpy for 2D arraysimport numpy as np
matrix = np.zeros((3, 4))
Floor Division (Integer Division)
# Floor division rounds down to nearest integer# Examples:# floor(2.4) = 2# floor(2.8) = 2# floor(-2.4) = -3 # Note: rounds toward negative infinity# Floor division in Python using //3//2# Result: 14//2# Result: 25//2# Result: 2-7//2# Result: -4# Regular division5/2# Result: 2.5# Using math.floor()import math
math.floor(2.8) # Result: 2
Swapping Values of Two Variables
a =1b =2# Pythonic way (single line)a, b = b, a
# Result: a = 2, b = 1# Multiple variable swapx, y, z =1, 2, 3x, y, z = z, y, x
# Result: x = 3, y = 2, z = 1
Line Continuation (Breaking Long Lines)
# Using backslasha =1+ \
1a = dostuff(blahblah1, blahblah2, blahblah3,
blahblah4, blahblah5, blahblah6,
blahblah7)
# Conditional statementsif a ==Trueand \
b ==False:
pass# String concatenationa ='1'+'2'+'3'+ \
'4'+'5'# Using parentheses (preferred - no backslash needed)a = ('1'+'2'+'3'+'4'+'5')
# Long function callsresult = function_name(
argument1,
argument2,
argument3,
argument4
)
# Lists and dictionaries (no continuation needed)my_list = [
1, 2, 3,
4, 5, 6]
my_dict = {
'key1': 'value1',
'key2': 'value2'}
Quick Debugging with pdb
# Insert breakpointimport pdb; pdb.set_trace()
# Python 3.7+ built-in breakpointbreakpoint() # Preferred method# Common pdb commands:# n (next) - Execute next line# s (step) - Step into function# c (continue) - Continue execution# l (list) - Show current code# p var - Print variable value# pp var - Pretty print variable# w (where) - Show stack trace# u (up) - Move up in stack# d (down) - Move down in stack# b n - Set breakpoint at line n# cl - Clear breakpoints# q (quit) - Exit debugger# Example usagedefbuggy_function(x):
breakpoint() # Execution pauses here result = x *2return result
Additional Useful Operations
List Comprehensions
# Create list with conditionsquares = [x**2for x inrange(10)]
evens = [x for x inrange(10) if x %2==0]
# Nested comprehensionmatrix = [[i*j for j inrange(3)] for i inrange(3)]
String Operations
# String formattingname ="Python"version =3.9print(f"{name} version {version}") # f-strings (Python 3.6+)print("{} version {}".format(name, version)) # format method# Multi-line stringstext ="""
This is a
multi-line string
"""
Dictionary Operations
# Get with default valued = {'a': 1}
value = d.get('b', 0) # Returns 0 if 'b' doesn't exist# Dictionary comprehensionsquares_dict = {x: x**2for x inrange(5)}
Enumerate and Zip
# Enumerate - get index and valuefor i, value inenumerate(['a', 'b', 'c']):
print(f"{i}: {value}")
# Zip - combine listsnames = ['Alice', 'Bob']
ages = [25, 30]
for name, age inzip(names, ages):
print(f"{name} is {age} years old")
Comments