Python Cheat Sheets (Python, Django, Pipenv) Reading Time 18 minutes Aug 10, 2020
Table Of Contents Python Python Variables Adding comments in python Input from the console Python strings Basic python arithmetic Loops in python Python lists Dictionaries in Python Exceptions Django Cheat Sheet Pipenv Cheat Final notes In this article I’ll be posting a series of code snippets, gotchas and syntax description for Python and some of its notable projects like Django, Flask, Pandas, Numpy, etc.
The idea is to have a single stop resource for those obscure and sometimes forgettable snippets that you need in your Python projects.
Depending on your level of experience, some of this snips will be too basic or to complex for you.
Python
A more complete PDF version can be found in the Python Crash Course Site .
Python Variables
Syntax Comments True FalseContrary to other languages, they are capitalized "string" 'string'Both quotes are valid a,b = b,aVariable swap
Syntax Notes # ...Pound sign comment a line """Triple quotes allow you to comment a function or class when placed After the function declaration
Syntax Notes input()Receives input from the console. You can pass a string as parameter as a label on the console
Python strings
Syntax Comments hello = """ ... """Triple quotes allow you to create a multiline string f'Hello {name}'Allows you to pass the variable name to the string and have it parsed mystr.title()Capitalizes every word of a string mystr.find('str')Returns the index where str is in mystr mystr.replace('a', 'b')Replaces a to b in a string 'Name' in mystrReturns True if Name is the string mystr
Basic python arithmetic
Operand Notes //Returns an int x ** yx to the power of yx += 1Increment by 1
Loops in python
Example Notes for i in my_list:Loop trough each item of a list for i in range(1, 12, 3):Loop from 1 to 12 on an interval of 3
Python lists
Method Notes .pop()Removes the last item .clear()Empties the list ",".join(mylist)Creates a string separated by , .index('str')Returns the index of the first occurrence of str .copy()Returns a copy of the list. Useful for functional programming mylist[:]Returns a copy of the list (like above) mylist[:2]Returns from the start of the list to the 2nd item mylist[::-1]Reverse a list or string [x**2 for x in range(2,8)]List comprehension [x**2 for x in range(2,8) if x % 2]List comprehension with conditional
Dictionaries in Python
Method Notes mydict.get('invalidx', 'default')Return the value of mydict['invalidx'] if exits. If not, returns default for key in my_dict.keys():Loop trough a dictionary keys for key, val in my_dict.values():Loop trough a dictionary values for key, val in my_dict.items():Loop trough a dictionary {**dic1, **dic2}Merge dictionaries
Exceptions
Method Notes raise Exception("desc")Throws a new exception except Exception as e:Catches the exception in the e variable finally:Allows you tu use variables declared in the try section
Django Cheat Sheet
Command Action django-admin startproject <project_name> [path]Creates a new project on path (preferably .) django-admin startapp <app_name>Creates a new application on app_name path python manage.py runserver 0:8080Starts the development server python manage.py startapp <appname>Creates a new app in the project python manage.py makemigrations [appname]Creates the migration from the models python manage.py migrate [appname]Executes the migrations in the database python manage.py sqlmigrate [appname] [#id]Returns the SQL for the migration specified by <#id> and <appname> python manage.py shellCreates an interactive shell where you can import models and execute queries python manage.py createsuperuserCreates a super user
Pipenv Cheat
I’ve included here a list of useful pipenv commands in case you are curious.
Command Action pipenv --python 3.7Create a project with another Python version pipenv install --devInstall packages including dev dependencies pipenv lockBurns the package versions on Pipfile.lock filepipenv cleanRemoves all packages not in Pipfile.lock pipenv run <command>Runs a command using the current virtualenv pipenv syncInstalls the packages from Pipfile.lock pipenv uninstallRemoves a package from the env and from the Pipfile pipenv --whereLocates the project pipenv --systemInstall the packages system wide and not in a venv pipenv --rmRemove the current virtual environment pipenv --venvLocates the virtual environment pipenv ---pyLocates the Python interpreter
Final notes
You can access additional Python Cheat Sheets in the SinxLooud site