You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# For loopforiteminiterable:
print(item)
# While loopwhilecondition:
pass# Loop controlbreak# Exit loopcontinue# Skip to next iteration
Comprehensions
# List comprehensionsquares= [x**2forxinrange(10) ifx%2==0]
# Dict comprehensionsquare_dict= {x: x**2forxinrange(5)}
# Set comprehensionunique_squares= {x**2forxinrange(-5, 6)}
Functions
Basic Functions
deffunction_name(param1, param2, default_param=10):
"""Docstring describing the function"""returnparam1+param2+default_param# Lambda functionssquare=lambdax: x**2
Args and Kwargs
defflexible_func(*args, **kwargs):
# args is a tuple of positional arguments# kwargs is a dict of keyword argumentspass
Decorators
defdecorator(func):
defwrapper(*args, **kwargs):
# Do something beforeresult=func(*args, **kwargs)
# Do something afterreturnresultreturnwrapper@decoratordefmy_function():
pass
Data Structures
Lists
lst= [1, 2, 3, 4, 5]
lst.append(6) # Add to endlst.insert(0, 0) # Insert at indexlst.remove(3) # Remove first occurrencelst.pop() # Remove and return last itemlst.extend([7, 8]) # Add multiple itemslst.sort() # Sort in placesorted_lst=sorted(lst) # Return sorted copy
Dictionaries
d= {"a": 1, "b": 2}
d["c"] =3# Add/updated.get("a", default=0) # Safe get with defaultd.keys() # Get all keysd.values() # Get all valuesd.items() # Get (key, value) pairsd.pop("a") # Remove and return value
Sets
s= {1, 2, 3}
s.add(4) # Add elements.remove(2) # Remove (error if not found)s.discard(2) # Remove (no error)s1.union(s2) # s1 | s2s1.intersection(s2) # s1 & s2s1.difference(s2) # s1 - s2
Strings
s="Hello World"s.lower() # Convert to lowercases.upper() # Convert to uppercases.strip() # Remove whitespaces.split() # Split into lists.replace("Hello", "Hi") # Replace substrings.startswith("Hello") # Check prefixs.endswith("World") # Check suffixf"{variable}"# f-string formatting
try:
risky_operation()
exceptSpecificErrorase:
handle_error(e)
except (Error1, Error2):
handle_multiple()
exceptExceptionase:
handle_generic(e)
else:
# Runs if no exceptionpassfinally:
# Always runscleanup()
Common Built-in Functions
len(iterable) # Lengthmax(iterable) # Maximum valuemin(iterable) # Minimum valuesum(iterable) # Sum of elementsrange(start, stop, step) # Generate sequenceenumerate(iterable) # Index, value pairszip(iter1, iter2) # Combine iterablesmap(func, iterable) # Apply functionfilter(func, iterable) # Filter elementsany(iterable) # True if any element is trueall(iterable) # True if all elements are true
importos# OS operationsimportsys# System operationsimportmath# Math functionsimportrandom# Random numbersimportdatetime# Date and timeimportjson# JSON handlingimportre# Regular expressionsimportcollections# Specialized containersimportitertools# Iterator functionsimportfunctools# Higher-order functions