{"id":3596,"date":"2023-08-20T00:21:16","date_gmt":"2023-08-20T07:21:16","guid":{"rendered":"https:\/\/ioflood.com\/blog\/?p=3596"},"modified":"2023-08-20T03:07:58","modified_gmt":"2023-08-20T10:07:58","slug":"python-syntax-cheat-sheet","status":"publish","type":"post","link":"https:\/\/ioflood.com\/blog\/python-syntax-cheat-sheet\/","title":{"rendered":"Python Syntax Cheat Sheet"},"content":{"rendered":"<p>Whether you&#8217;re a seasoned developer looking to brush up on Python&#8217;s intricacies or a beginner stepping into the world of programming, this <strong>Python Cheat Sheet<\/strong> is your handy companion. Within this guide, you&#8217;ll find concise explanations, practical examples, and quick references for Python&#8217;s core concepts and functionalities.<\/p>\n<p>This cheat sheet is designed to be both comprehensive and digestible. From data types to control structures, function usage to error handling, dive in to get a snapshot of Python&#8217;s capabilities. And remember, the key to mastering Python (or any language, for that matter) is consistent practice and application. Happy coding!<\/p>\n<h2>Command Reference<\/h2>\n<p>In this section, we&#8217;ve compiled a handy list of essential Python-related commands. Whether you&#8217;re setting up a new environment, installing packages, or managing dependencies, these commands will help streamline your workflow and ensure you&#8217;re making the most of Python&#8217;s robust ecosystem.<\/p>\n<h3>Data Types<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>int<\/td>\n<td>Integer numbers<\/td>\n<td><code>x = 10<\/code><\/td>\n<\/tr>\n<tr>\n<td>float<\/td>\n<td>Decimal number<\/td>\n<td><code>y = 10.5<\/code><\/td>\n<\/tr>\n<tr>\n<td>str<\/td>\n<td>String, or text<\/td>\n<td><code>text = \"Hello, World!\"<\/code><\/td>\n<\/tr>\n<tr>\n<td>list<\/td>\n<td>Ordered collection of items<\/td>\n<td><code>fruits = [\"apple\", \"banana\"]<\/code><\/td>\n<\/tr>\n<tr>\n<td>tuple<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/mutable-vs-immutable-in-python-object-data-types-explained\/\">Immutable<\/a> ordered collection<\/td>\n<td><code>colors = (\"red\", \"blue\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>set<\/td>\n<td>Unordered collection of unique items<\/td>\n<td><code>unique_numbers = {1, 2, 3}<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-dictionary-guide-examples-syntax-and-advanced-uses\/\">dict<\/a><\/td>\n<td>Unordered collection of key-value pairs<\/td>\n<td><code>person = {\"name\": \"John\"}<\/code><\/td>\n<\/tr>\n<tr>\n<td>bool<\/td>\n<td>Boolean value (True or False)<\/td>\n<td><code>is_valid = False<\/code><\/td>\n<\/tr>\n<tr>\n<td>frozenset<\/td>\n<td>Immutable version of a set<\/td>\n<td><code>immutable_set = frozenset([1, 2, 3])<\/code><\/td>\n<\/tr>\n<tr>\n<td>bytes<\/td>\n<td>Immutable sequence of bytes<\/td>\n<td><code>byte_data = b\"Hello\"<\/code><\/td>\n<\/tr>\n<tr>\n<td>bytearray<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/mutable-vs-immutable-in-python-object-data-types-explained\/\">Mutable<\/a> sequence of bytes<\/td>\n<td><code>mutable_byte_data = bytearray(b\"Hello\")<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/does-python-null-exist-how-to-use-the-none-keyword-in-python\/\">None<\/a><\/td>\n<td>Represents absence of a value or null object<\/td>\n<td><code>x = None<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Common Built-in Functions<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/get-length-of-array-in-python-guide-and-examples\/\">len()<\/a><\/td>\n<td>Returns the number of items in an object<\/td>\n<td><code>length = len([1, 2, 3])<\/code><\/td>\n<\/tr>\n<tr>\n<td>print()<\/td>\n<td>Outputs text or variables to the console<\/td>\n<td><code>print(\"Hello, World!\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>type()<\/td>\n<td>Returns the type of the object<\/td>\n<td><code>obj_type = type(123)<\/code><\/td>\n<\/tr>\n<tr>\n<td>isinstance()<\/td>\n<td>Check if an object is an instance of a certain class or tuple of classes<\/td>\n<td><code>check = isinstance(5, int)<\/code><\/td>\n<\/tr>\n<tr>\n<td>sorted()<\/td>\n<td>Return a sorted list of the specified iterable&#8217;s elements<\/td>\n<td><code>sorted_list = sorted([3, 1, 2])<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-sum-list-how-to-calculate-the-sum-of-the-elements-in-a-list\/\">sum()<\/a><\/td>\n<td>Returns the sum of all items in an iterable<\/td>\n<td><code>total = sum([1, 2, 3])<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-max-function-guide-uses-and-examples\/\">max()<\/a>, <a href=\"https:\/\/ioflood.com\/blog\/python-min-function-guide-uses-and-examples\/\">min()<\/a><\/td>\n<td>Return the largest\/smallest item in an iterable or two or more arguments<\/td>\n<td><code>maximum = max([1, 2, 3])<\/code><\/td>\n<\/tr>\n<tr>\n<td>abs()<\/td>\n<td>Returns the absolute value of a number<\/td>\n<td><code>absolute_value = abs(-5)<\/code><\/td>\n<\/tr>\n<tr>\n<td>round()<\/td>\n<td>Round a number to the nearest integer or to the given number of decimals<\/td>\n<td><code>rounded_value = round(3.14159, 2)<\/code><\/td>\n<\/tr>\n<tr>\n<td>input()<\/td>\n<td>Read a line from input, optionally using the provided prompt string<\/td>\n<td><code>user_input = input(\"Enter your name: \")<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/using-deque-in-python-python-queues-and-stacks-made-easy\/\">deque()<\/a><\/td>\n<td>Returns a new deque object initialized from data<\/td>\n<td><code>from collections import deque; d = deque([1, 2, 3])<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-range-function-guide-examples-syntax-and-advanced-uses\/\">range()<\/a><\/td>\n<td>Returns a sequence of numbers<\/td>\n<td><code>range(start, stop, step)<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-merge-dictionaries-5-easy-methods-with-examples\/\">dict.update()<\/a><\/td>\n<td>Updates the dictionary with the specified key-value pairs<\/td>\n<td><code>dict1.update(dict2)<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-list-extend-method-usage-and-examples\/\">list.extend()<\/a><\/td>\n<td>Adds the elements of a list to the end of the current list<\/td>\n<td><code>list1.extend(list2)<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/string-slicing-in-python-usage-and-examples\/\">slice<\/a><\/td>\n<td>Returns a slice of an object<\/td>\n<td><code>my_list[start:stop:step]<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-set-difference-usage-guide-with-examples\/\">set.difference()<\/a><\/td>\n<td>Returns a set containing the difference between two or more sets<\/td>\n<td><code>a.difference(b)<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Basic Math Operators<\/h3>\n<table>\n<thead>\n<tr>\n<th>Operator<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>+<\/td>\n<td>Addition<\/td>\n<td><code>a + b<\/code><\/td>\n<\/tr>\n<tr>\n<td>&#8211;<\/td>\n<td>Subtraction<\/td>\n<td><code>a - b<\/code><\/td>\n<\/tr>\n<tr>\n<td>*<\/td>\n<td>Multiplication<\/td>\n<td><code>a * b<\/code><\/td>\n<\/tr>\n<tr>\n<td>\/<\/td>\n<td>Division<\/td>\n<td><code>a \/ b<\/code><\/td>\n<\/tr>\n<tr>\n<td>\/\/<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-integer-division-how-to-use-the-floor-operator\/\">Integer division<\/a> (floors the result)<\/td>\n<td><code>a \/\/ b<\/code><\/td>\n<\/tr>\n<tr>\n<td>%<\/td>\n<td>Modulus (remainder of division)<\/td>\n<td><code>a % b<\/code><\/td>\n<\/tr>\n<tr>\n<td>**<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-exponent-guide-how-to-raise-a-number-to-a-power-in-python\/\">Exponentiation<\/a><\/td>\n<td><code>a ** b<\/code><\/td>\n<\/tr>\n<tr>\n<td>&amp;<\/td>\n<td>Bitwise AND<\/td>\n<td><code>a &amp; b<\/code><\/td>\n<\/tr>\n<tr>\n<td>&#124;<\/td>\n<td>Bitwise OR<\/td>\n<td><code>a \\| b<\/code><\/td>\n<\/tr>\n<tr>\n<td>^<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/xor-in-python-usage-guide-to-bitwise-xor\/\">Bitwise XOR<\/a><\/td>\n<td><code>a ^ b<\/code><\/td>\n<\/tr>\n<tr>\n<td>&lt;&lt;<\/td>\n<td>Left shift<\/td>\n<td><code>a &lt;&lt; 1<\/code><\/td>\n<\/tr>\n<tr>\n<td>>><\/td>\n<td>Right shift<\/td>\n<td><code>a &gt;&gt; 1<\/code><\/td>\n<\/tr>\n<tr>\n<td>~<\/td>\n<td>Bitwise NOT<\/td>\n<td><code>~a<\/code><\/td>\n<\/tr>\n<tr>\n<td>+=<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-increment-by-1-quick-and-easy-examples\/\">Increment <\/a> a variable&#8217;s value<\/td>\n<td><code>variable += 1<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Type Conversion<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>int<\/td>\n<td>Converts a value to an integer<\/td>\n<td><code>int(\"123\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>str<\/td>\n<td>Converts a value to a string<\/td>\n<td><code>str(123)<\/code><\/td>\n<\/tr>\n<tr>\n<td>list<\/td>\n<td>Converts a value to a list<\/td>\n<td><code>list(\"hello\")<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>String Manipulation<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>.format()<\/td>\n<td>Format strings using positional and keyword arguments<\/td>\n<td><code>'{} {}'.format('one', 'two')<\/code><\/td>\n<\/tr>\n<tr>\n<td>f-string<\/td>\n<td>Embed expressions inside string literals<\/td>\n<td><code>f\"The sum is {1+2}\"<\/code><\/td>\n<\/tr>\n<tr>\n<td>.split()<\/td>\n<td>Splits a string into a list<\/td>\n<td><code>\"Hello, World\".split(\", \")<\/code><\/td>\n<\/tr>\n<tr>\n<td>.join()<\/td>\n<td>Joins elements of an iterable with a string separator<\/td>\n<td><code>\", \".join([\"apple\", \"banana\", \"cherry\"])<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>String Methods<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>lower<\/td>\n<td>Converts string to lowercase<\/td>\n<td><code>\"HELLO\".lower()<\/code><\/td>\n<\/tr>\n<tr>\n<td>upper<\/td>\n<td>Converts string to uppercase<\/td>\n<td><code>\"hello\".upper()<\/code><\/td>\n<\/tr>\n<tr>\n<td>strip<\/td>\n<td>Removes whitespace from start and end<\/td>\n<td><code>\" hello \".strip()<\/code><\/td>\n<\/tr>\n<tr>\n<td>replace<\/td>\n<td>Replaces a substring with another<\/td>\n<td><code>\"hello\".replace(\"e\", \"a\")<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/ord-python-and-chr-python-ordinal-value-character-conversions-in-python\/\">ord()<\/a><\/td>\n<td>Returns an integer representing the Unicode character<\/td>\n<td><code>ord('a')<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/ord-python-and-chr-python-ordinal-value-character-conversions-in-python\/\">chr()<\/a><\/td>\n<td>Returns a string representing a character whose Unicode code point is the integer<\/td>\n<td><code>chr(97)<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>List Methods<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>append<\/td>\n<td>Adds an item to the end of the list<\/td>\n<td><code>fruits.append(\"orange\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>remove<\/td>\n<td>Removes the first occurrence of the item<\/td>\n<td><code>fruits.remove(\"apple\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>pop<\/td>\n<td>Removes the item at the specified index<\/td>\n<td><code>fruits.pop(1)<\/code><\/td>\n<\/tr>\n<tr>\n<td>sort<\/td>\n<td>Sorts the list<\/td>\n<td><code>numbers.sort()<\/code><\/td>\n<\/tr>\n<tr>\n<td>index<\/td>\n<td>Returns the index of the first occurrence of the item<\/td>\n<td><code>colors.index(\"red\")<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Control Structures<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>if<\/td>\n<td>Conditional statement<\/td>\n<td><code>if x &gt; 10:<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/else-if-python-how-to-use-python-conditional-statements\/\">if-elif-else<\/a><\/td>\n<td>Conditional statements<\/td>\n<td><code>if x &gt; 10: ... elif x == 10: ... else: ...<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/pyhton-if-not-how-to-use-advanced-conditionals-in-python\/\">if not<\/a><\/td>\n<td>Logical NOT condition<\/td>\n<td><code>if not x:<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/for-loop-in-python-syntax-usage-and-examples\/\">for<\/a><\/td>\n<td>Loop over a sequence<\/td>\n<td><code>for i in range(3):<\/code><\/td>\n<\/tr>\n<tr>\n<td>while<\/td>\n<td>Loop as long as condition is true<\/td>\n<td><code>while x &lt; 5:<\/code><\/td>\n<\/tr>\n<tr>\n<td>break<\/td>\n<td>Exits the current loop<\/td>\n<td><code>if x == 5: break<\/code><\/td>\n<\/tr>\n<tr>\n<td>continue<\/td>\n<td>Skips the rest of the loop&#8217;s current iteration<\/td>\n<td><code>if x == 3: continue<\/code><\/td>\n<\/tr>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-exit-how-to-terminate-a-python-program-immediately\/\">exit<\/a><\/td>\n<td>Exits the current Python script<\/td>\n<td><code>exit()<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Functions and Modules<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><a href=\"https:\/\/ioflood.com\/blog\/learn-python-functions-python-def-examples-and-usage\/\">def<\/a><\/td>\n<td>Define a function<\/td>\n<td><code>def&lt; my_func():<\/code><\/td>\n<\/tr>\n<tr>\n<td>import<\/td>\n<td>Import a module or library<\/td>\n<td><code>import math<\/code><\/td>\n<\/tr>\n<tr>\n<td>from<\/td>\n<td>Import a specific part from a module<\/td>\n<td><code>from datetime import date<\/code><\/td>\n<\/tr>\n<tr>\n<td>return<\/td>\n<td>Returns a value from a function<\/td>\n<td><code>def sum(a, b): return a+b<\/code><\/td>\n<\/tr>\n<tr>\n<td>class<\/td>\n<td>Defines a class<\/td>\n<td><code>class Person: ...<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Exception Handling<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>raise<\/td>\n<td>Raises an exception<\/td>\n<td><code>raise ValueError(\"A value error occurred!\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>assert<\/td>\n<td>Used for debugging, raises an error if false<\/td>\n<td><code>assert x &gt; 0, \"Only positive numbers are allowed\"<\/code><\/td>\n<\/tr>\n<tr>\n<td>try-except<\/td>\n<td>Catches and handles exceptions<\/td>\n<td><code>try: ... except SomeError: ...<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>List Comprehensions &amp; Generators<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>List comprehension<\/td>\n<td>Generates a new list by applying an expression<\/td>\n<td><code>[x**2 for x in range(5)]<\/code><\/td>\n<\/tr>\n<tr>\n<td>Generator<\/td>\n<td>Produces items one at a time and requires less memory<\/td>\n<td><code>(x**2 for x in range(5))<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Decorators &amp; Metaclasses<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Decorator<\/td>\n<td>Modifies or extends the behavior of functions\/classes<\/td>\n<td><code>@staticmethod<\/code><\/td>\n<\/tr>\n<tr>\n<td>Metaclass<\/td>\n<td>A class of a class that defines how a class behaves<\/td>\n<td><code>class MyClass(metaclass=Meta): ...<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>File Handling<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>open<\/td>\n<td>Opens a file<\/td>\n<td><code>file = open(\"filename.txt\", \"r\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>close<\/td>\n<td>Closes a file<\/td>\n<td><code>file.close()<\/code><\/td>\n<\/tr>\n<tr>\n<td>with<\/td>\n<td>Used with file operations to automatically close a file<\/td>\n<td><code>with open(\"filename.txt\", \"r\") as file: ...<\/code><\/td>\n<\/tr>\n<tr>\n<td>os.rename()<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-rename-file-7-easy-methods-with-examples\/\">Rename a file or directory<\/a><\/td>\n<td><code>import os; os.rename('old_name.txt', 'new_name.txt')<\/code><\/td>\n<\/tr>\n<tr>\n<td>os.remove()<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-delete-file-how-to-remove-a-file-or-folder-in-python\/\">Remove a file<\/a><\/td>\n<td><code>import os; os.remove('filename.txt')<\/code><\/td>\n<\/tr>\n<tr>\n<td>shutil.copy()<\/td>\n<td><a href=\"https:\/\/ioflood.com\/blog\/python-copy-file-guide-8-ways-to-copy-a-file-in-python\/\">Copy a file<\/a><\/td>\n<td><code>import shutil; shutil.copy('source.txt', 'dest.txt')<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Environment Variables &amp; OS Interactions<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>os.environ<\/td>\n<td>Access <a href=\"https:\/\/ioflood.com\/blog\/python-dotenv-guide-how-to-use-environment-variables-in-python\/\">environment variables<\/a><\/td>\n<td><code>user = os.environ.get(\"USERNAME\")<\/code><\/td>\n<\/tr>\n<tr>\n<td>os.system()<\/td>\n<td>Execute a shell command<\/td>\n<td><code>os.system('echo Hello World')<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Web Server Interactions<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>GET method<\/td>\n<td>Retrieve data from a server<\/td>\n<td><code>response = requests.get(url)<\/code><\/td>\n<\/tr>\n<tr>\n<td>POST method<\/td>\n<td>Send data to a server<\/td>\n<td><code>response = requests.post(url, data=payload)<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Miscellaneous<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>pass<\/td>\n<td>A null statement, a placeholder for future code<\/td>\n<td><code>def my_function(): pass<\/code><\/td>\n<\/tr>\n<tr>\n<td>global<\/td>\n<td>Accesses a global variable inside a function<\/td>\n<td><code>def set_global_x(): global x; x = 10<\/code><\/td>\n<\/tr>\n<tr>\n<td>nonlocal<\/td>\n<td>Accesses a variable in the nearest enclosing scope<\/td>\n<td><code>def outer_func(): x = 10; def inner_func(): nonlocal x; x = 20<\/code><\/td>\n<\/tr>\n<tr>\n<td>deepcopy<\/td>\n<td>Creates a new object that&#8217;s a copy of the original<\/td>\n<td><code>from copy import deepcopy; new_obj = deepcopy(obj)<\/code><\/td>\n<\/tr>\n<tr>\n<td>lambda<\/td>\n<td>Creates a small anonymous function<\/td>\n<td><code>x = lambda a : a + 10<\/code><\/td>\n<\/tr>\n<tr>\n<td>map<\/td>\n<td>Applies a function to all items in an input list<\/td>\n<td><code>squared = map(lambda x: x**2, [1, 2, 3, 4])<\/code><\/td>\n<\/tr>\n<tr>\n<td>filter<\/td>\n<td>Filters elements in a list based on a function<\/td>\n<td><code>filter(lambda x: x%2 == 0, [1, 2, 3])<\/code><\/td>\n<\/tr>\n<tr>\n<td>reduce<\/td>\n<td>Apply a function to items, reducing list to a single value<\/td>\n<td><code>from functools import reduce; reduce(lambda x, y: x*y, [1, 2, 3])<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>JSON Handling<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>json.load()<\/td>\n<td>Load JSON data from a file<\/td>\n<td><code>with open(\"data.json\") as f: data = json.load(f)<\/code><\/td>\n<\/tr>\n<tr>\n<td>json.loads()<\/td>\n<td>Parse JSON string<\/td>\n<td><code>data = json.loads(json_string)<\/code><\/td>\n<\/tr>\n<tr>\n<td>json.dump()<\/td>\n<td>Write JSON data to a file<\/td>\n<td><code>with open(\"output.json\", \"w\") as f: json.dump(data, f)<\/code><\/td>\n<\/tr>\n<tr>\n<td>json.dumps()<\/td>\n<td>Convert Python object to JSON string<\/td>\n<td><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Web Server Request Handling with Flask<\/h3>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<th>Syntax Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Flask route (GET)<\/td>\n<td>Define a route that listens for HTTP GET requests<\/td>\n<td><code>@app.route('\/endpoint')<\/code><\/td>\n<\/tr>\n<tr>\n<td>Flask route (POST)<\/td>\n<td>Define a route that listens for HTTP POST requests<\/td>\n<td><code>@app.route('\/endpoint', methods=['POST'])<\/code><\/td>\n<\/tr>\n<tr>\n<td>Request.args<\/td>\n<td>Access GET (query string) parameters<\/td>\n<td><code>value = request.args.get('param_name')<\/code><\/td>\n<\/tr>\n<tr>\n<td>Request.form<\/td>\n<td>Access POST form data<\/td>\n<td><code>value = request.form.get('field_name')<\/code><\/td>\n<\/tr>\n<tr>\n<td>Request.data<\/td>\n<td>Access raw data sent in the request (e.g., for JSON payloads)<\/td>\n<td><code>raw_data = request.data<\/code><\/td>\n<\/tr>\n<tr>\n<td>Request.json<\/td>\n<td>Access parsed JSON data in the request body<\/td>\n<td><code>data_obj = request.json<\/code><\/td>\n<\/tr>\n<tr>\n<td>Return Response<\/td>\n<td>Return a specific response to the client<\/td>\n<td><code>return \"Hello World\", 200<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Illustrative Example Program<\/h2>\n<p>After acquainting ourselves with the key commands, it&#8217;s time to see Python in action! Below, we&#8217;ll walk you through setting up a Python environment and then delve into an illustrative program. This example serves to showcase the various Python concepts we&#8217;ve covered, integrating them into a single, cohesive script.<\/p>\n<blockquote><p>\n  It&#8217;s one thing to understand a concept in isolation; it&#8217;s another to see how it fits within the larger picture of Python programming. Dive in and observe how these individual pieces come together!\n<\/p><\/blockquote>\n<h3>Setting up the environment<\/h3>\n<p>First, let&#8217;s learn how to install a module dependency. You can use pip or poetry to install Python modules.<\/p>\n<p>PiP installs the dependency on the OS as a whole, available to all python scripts.<\/p>\n<p>Poetry on the other hand, creates a virtual environment for each Python application, allowing you to use different versions of a  module for each Python application. This is great for compatibility and tidyness!<\/p>\n<pre><code class=\"language-bash line-numbers\"># Install a specific version of a module with pip\npip install requests==2.25.1\n\n# Or using poetry\npoetry add requests@2.25.1\n\n# Specify a particular version for poetry in the pyproject.toml\necho 'requests = \"^2.25.1\"' &gt;&gt; pyproject.toml\n\n# Open your Python file using nano to start coding\nnano my_python_script.py\n<\/code><\/pre>\n<h3>Python Code Example<\/h3>\n<p>Now, you can copy \/ paste the example program and run it.<\/p>\n<p>Read over it to see how the different Python commands and functions are actually used in a program.<\/p>\n<blockquote><p>\n  It&#8217;s one thing to read a syntax specification, and quite another to see how you actually type it out and see what it does!\n<\/p><\/blockquote>\n<pre><code class=\"language-python line-numbers\">import os\nimport json\nimport requests\nimport math\nfrom copy import deepcopy\n\n# Using \"requests\" to get IP with error handling\n\ntry:\n    response = requests.get('https:\/\/api.ipify.org?format=json')\n    ip_data = json.loads(response.text)\n    my_ip = ip_data[\"ip\"]\n    print(f\"Your IP is: {my_ip}\")\nexcept requests.ConnectionError:\n    print(\"Failed to connect to the website!\")\nexcept Exception as e:\n    print(f\"An unknown error occurred: {e}\")\n\n\n# Data Types\n\n# Immutable Object Types\n\nmy_str = \"Hello\"\nmy_num = 123\nmy_float = 3.14\nmy_tuple = (4, 5, 6)\n\n# Mutable Object Types:\n\nmy_list = [1, 2, 3]\nmy_set = {7, 8, 9}\nmy_dict = {'a': 1, 'b': 2}\n\n\n# Careful: mutable variables are passed by reference\n\ndef modify_list(lst):\n    # Appending a new item to the list\n    lst.append(4)\n\n# Test the function\nmy_list = [1, 2, 3]\nmodify_list(my_list)\nprint(my_list)  # Output: [1, 2, 3, 4]\n\n\n# Avoid mutable default arguments with \"None\"\n# Avoid altering passed variables using deepcopy\n\ndef add_to_list(value, my_list_argument=None):\n    # If no list is provided, use an empty one\n    if my_list_argument is None:\n        my_list = []\n    else:\n        my_list = deepcopy(my_list_argument)\n\n    my_list.append(value)\n    return my_list\n\n# Test the function\noriginal_list = [1, 2, 3]\nnew_list = add_to_list(4, original_list)\n\nprint(original_list)  # Output: [1, 2, 3] - remains unchanged\nprint(new_list)       # Output: [1, 2, 3, 4] - value added to new list\n\n\n# Built-in Functions &amp; Methods\n\nprint(\"Hello, World!\")  # This is a comment\nmy_str = f\"My IP address is {my_ip} and it's {len(my_ip)} characters long.\"\nprint my_str\n\nrounded_down = math.floor(3.6)\nprint(f\"Rounded down: {rounded_down}\")\n# Prints \"Rounded down: 3\"\n\n\n# Data type conversions and String concatenation\n\nnum_str = \"15\"\nnum_int = 20\nprint(num_str + \" + \" + str(num_int) + \" = \" + str(int(num_str) + num_int))\n# Outputs \"15 + 20 = 35\"\n\n\n# Using decorator functions\n\ndef log_decorator(func):\n    def wrapper(*args, **kwargs):\n        print(f\"Calling function: {func.__name__}\")\n        return func(*args, **kwargs)\n    return wrapper\n\n@log_decorator\ndef greet(name):\n    return f\"Hello, {name}\"\n\nprint(greet(\"Alice\"))\n# Prints Two lines:\n# Calling function: greet\n# Hello, Alice\n\n\n# Classes &amp; OOP\n\nclass Animal:\n    def __init__(self, species):\n        self.species = species\n\nclass Dog(Animal):\n    def bark(self):\n        return \"Woof!\"\n\ndog = Dog(\"Canine\")\nprint(dog.bark())\n\n\n# Control Structures &amp; List Comprehensions\n\nnumbers = [1, 5, 8, 10] # Sample list of numbers\n\n# Using a for loop to extract odd numbers\nodds = []\nfor num in numbers:\n    if num % 2 != 0:\n        odds.append(num)\n\n# % modulo gives the remainder of a division. If the remainder dividing by 2 is not 0, the number is odd.\n\n# Using a list comprehension to extract even numbers (compact equivalent to the above logic)\nevens = [num for num in numbers if num % 2 == 0]\n\n# Calculate the sum of the even numbers\neven_sum = sum(evens)\n\n# Print results\nprint(f\"Odd numbers: {odds}\") # 1, 5\nprint(f\"Sum of even numbers: {even_sum}\") # 18\n\n\n\n# Iterating through environment variables\n\n# For loop method\n\nfor key, value in os.environ.items():\n    if key == \"SECRET_PASSWORD\":\n        print(\"Encountered sensitive data. Exiting...\")\n        break\n    print(f\"{key}: {value}\")\n\n# While loop method\n\nenv_items = list(os.environ.items())  # Convert dict items to a list\ni = 0\n\nwhile i &lt; len(env_items):\n    key, value = env_items[i]\n    if key == \"SECRET_PASSWORD\":\n        print(\"Encountered sensitive data. Exiting...\")\n        break\n    print(f\"{key}: {value}\")\n    i += 1\n\n\n# Grabbing a specific environment variable\n\nenvironment_value = os.getenv(\"HOME\")  # Fetch an environment variable\nprint(f\"My home directory is: {environment_value}. String in lowercase: {environment_value.lower()}\")\n\n\nprint(\"End of Program!\")\n<\/code><\/pre>\n<p>After walking through the example program, you&#8217;ve likely noticed how Python beautifully integrates different concepts to achieve a desired outcome. We&#8217;ve seen how it handles errors gracefully with <code>try<\/code> and <code>except<\/code>, how it can interact with the web using <code>requests<\/code>, and how it manipulates various data types seamlessly.<\/p>\n<p>The true strength of Python lies in its versatility and readability. Each module and function has a specific role, and the community-driven packages expand its capabilities even further.<\/p>\n<h2>Conclusion<\/h2>\n<p>Python is a dynamic and versatile language, suitable for a wide range of tasks from web development to data analysis and machine learning. The cheat sheet provided here is a testament to its rich feature set and user-friendly syntax. As you delve deeper into Python, always remember to leverage the vast resources available, including documentation and community forums. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Whether you&#8217;re a seasoned developer looking to brush up on Python&#8217;s intricacies or a beginner stepping into the world of programming, this Python Cheat Sheet is your handy companion. Within this guide, you&#8217;ll find concise explanations, practical examples, and quick references for Python&#8217;s core concepts and functionalities. This cheat sheet is designed to be both [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[121,123],"tags":[],"class_list":["post-3596","post","type-post","status-publish","format-standard","hentry","category-programming-coding","category-python","cat-121-id","cat-123-id"],"_links":{"self":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts\/3596","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/comments?post=3596"}],"version-history":[{"count":12,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts\/3596\/revisions"}],"predecessor-version":[{"id":3647,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts\/3596\/revisions\/3647"}],"wp:attachment":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/media?parent=3596"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/categories?post=3596"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/tags?post=3596"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}