Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Ultimate Python Cheat Sheet
Eric The Coder
Eric The Coder

Posted on • Edited on • Originally published ateric-the-coder.com

     

Ultimate Python Cheat Sheet

In this post you will find a very handy Python memory aid

Dont miss my next python post:Follow @EricTheCoder_



Here is my cheat sheet I created along my learning journey. If you have any recommendations (addition/subtraction) let me know.

Python Cheat Sheet

Naming conventions

# Variable lower_snakefirst_name='Mike'# Class and module CamelCaseclassInvoiceDetail:# ConstantMAX_USER=100# All uppercase# Indentation : 4 spacesifnum>9:print('Small number')
Enter fullscreen modeExit fullscreen mode

Data type

name='Mike'# stringage=42# intprice=199.99# floatis_active=True# booleancolors=['red','green','blue']# liststates=('inactive','active','archive')# tupleproducts={'name':'iPad Pro','price':199.99}# dict
Enter fullscreen modeExit fullscreen mode

Type conversion

# Python is a strong type languagenumber=50+"50"# TypeError# Convert to stringnumber=50+int("50")# 100# Convert to stringmy_text=str(199.99)# "199.99"# Convert to numbermy_number=int(21.99)# 21my_number=float('21.99')# 21.99# Get typetype(my_text)# <class 'str'>type(my_number)# <class 'float'># Check if number 0 to 9isdigit('8')# True# Check typeisinstance(my_number,int)# True
Enter fullscreen modeExit fullscreen mode

Strings

name='Mike'# orname="Mike"# ormessage="""This is multilinestring that is easier toread and assign"""# escape characters \n will do a line breakmessage="Hello\nWorld"# raw string (ignore escape characters)message=r"https:\\example.com\index.html"# Convert to lower casename.lower()# mike# Convert to upper casename.upper()# MIKE# Convert first char to Capital lettername.capitalize()# Mike# Convert first char of all words to Capital lettername='mike taylor'name.title()# Mike Taylor# Chain methodsname='MIKE'name.lower().capitalize()# Mikename='Mike'# Start with ?name.startswith('M')# true# End with ?name.endswith('ke')# true# String lengthlen(name)# 4# String concatenationfull_name=first_name+' '+last_name# String formatfull_name=f"{first_name}{last_name}"# String format number (2 decimal point)number=12.9997number_string="{:.2f}".format(number)# '12.99'# Remove leading and trailing characters (like space or \n)text=' this is a text with white space 'text.strip()# 'this is a test with white space'name='Mike'# Get string first charactername[0]# M# Get string last charactername[-1]# e# Get partial stringname[1:3]# ik# Replacename.replace('M','P')# Pike# Find (return pos or -1 if not found)name.find('k')# 2# List to stringcolors=['red','green','blue']', '.join(colors)# 'red, green, blue'
Enter fullscreen modeExit fullscreen mode

Commons fonctions

# Print to consoleprint('Hello World')# Print multiple stringprint('Hello','World')# Hello World# Multiple printprint(10*'-')# ----------# Variable pretty printer (for debug)frompprintimportpprintpprint(products)# will output var with formatting# Get keyboard inputname=input('What is your name? ')# Random (between 0 and 1)fromrandomimportrandomprint(random())# 0.26230234411558273# Random beween x and yfromrandomimportrandintprint(randint(3,9))# 5# Roundingnumber=4.5print(round(number))# 5number=4.5163print(round(number,2))# 4.52# Pathimportoscurrent_file_path=__file__folder_name=os.path.dirname(current_file_path)new_path=os.path.join(folder_name,'new folder')# Round numbersolution=round(12.9582,2)# 12.96
Enter fullscreen modeExit fullscreen mode

Conditionals

ifx==4:print('x is 4')elifx!=5andx<11:print('x is between 6 and 10')else:print('x is 5 or greater than 10')#In or not incolors=['red','green','blue','yellow']if'blue'incolors:if'white'notincolors:# Ternaryprint('y = 10')ify==10elseprint('y != 10')# ShortHand Ternaryis_valid='Valid'msg=is_validor"Not valid"# 'Valid'# FalsyFalse,None,0,emptystring"",emptylist[],(),{}# TruthyTrue,notzeroandnotemptyvalue
Enter fullscreen modeExit fullscreen mode

Interations

# iterating over a sequence (list, string, etc.)foriteminitems:print(item)# With indexforindex,iteminenumerate(items):print(index,item)# Rangeforiinrange(10):#0..9print(i)foriinrange(5,10):#5..9print(i)# While loopwhilex>10:print(x)# exit loopifx==5:break# Jump to next whileifx==3:continuex+=1# For loop dicforkey,valueinmy_dict.items():print(key,value)# List comprehension: # values = [(expression) for (value) in (collection)]items=[value*2forvalueinitems]# List comprehension filtering# values = [expression for value in collection if condition]even_squares=[x*xforxinrange(10)ifx%2==0]
Enter fullscreen modeExit fullscreen mode

List and Tuple

# Create a listfruits=['orange','apple','melon']# Append to Listfruits.append('banana')# List lengthnb_items=len(fruits)# Remove from listdelfruits[1]#remove apple# List accessfruits[0]# first itemfruits[-1]# last item# Slice my_list[start:finish:step] ([::-1] reverse list)fruits=fruits[1:3]fruits[:3]# first 3fruits[2:]# last 2copy_fruits=fruits[:]# copy# List lengthnb_entry=len(fruits)#Create list from stringcolors='red, green, blue'.split(', ')# Array concactcolor1=['red','blue']color2=['green','yellow']color3=color1+color2# Concat by unpackingcolor3=[*color1,*color2]# Multiple assignmentname,price=['iPhone',599]#Create a Tuple (kind of read only list)colors=('red','green','blue')# Sortcolors.sort()# ['blue', 'green', 'red']colors.sort(reverse=True)# ['red', 'green', 'blue']colors.sort(key=lambdacolor:len(color))# ['red', 'blue', 'green']
Enter fullscreen modeExit fullscreen mode

Dictionaries

# Create a empty dictproduct={}#Create a dict with key/valueproduct={'id':100,'name':'iPadPro'}# Access dict value by keyprint(product['name'])# iPadPro# Access dictproduct.get('name')# if key not exist return Noneproduct.get('name','default value')# if key not exist return default value# Adding a new key/valueproduct['description']="Modern mobile device"# Get dict keysproduct.keys()# ['id', 'name', 'description']# Get dic valuesproduct.values()# ['100', 'iPadPro', 'Modern mobile device']# Create a list of dictproducts=[{'id':100,'name':'iPadPro'},{'id':200,'name':'iPhone 12'},{'id':300,'name':'Charger'},]# Access list of dictprint(products[2]['name'])# Charger# Search list dictitems_match=[itemforproductinproductsifproduct['id']==300]# [{'id': 300, 'name': 'Charger'}]# Sum list dicttotal=sum([product['price']forproductinproducts])
Enter fullscreen modeExit fullscreen mode

Functions

# Create a functiondefsay_hello():print('Hello World')# Function with argument (with default value)defsay_hello(name='no name'):print(f"Hello{name}")# Function with argument (with optional value)defsay_hello(name=None):ifname:print(f"Hello{name}")else:print('Hello World')# Call a functionsay_hello('Mike')# Hello Mike# Call using keyword argumentsay_hello(name='Mike')# Function returning a valuedefadd(num1,num2):returnnum1+num2num=add(10,20)# 30# Arbitrary numbers of arguments *argsdefsay_hello(*names):fornameinnames:print(f"Hello{name}")# Arbitrary numbers of keywords arguments **kwargsdefsay_hello(**kwargs):print(kwargs['name'])print(kwargs['age'])say_hello(name='Mike',age=45)# Lambda functionx=lambdanum:num+10print(x(20))# 30
Enter fullscreen modeExit fullscreen mode

Date and time

fromdatetimeimportdatetime,timedelta# Return the current date and time.datetime.now()# Create a date time objectdate=datetime(2020,12,31)# Dec 31 2020# Add to date/time (weeks, days, hours, minutes, seconds)new_year=date+timedelta(days=1)# Jan 1 2021# Format a date to stringnew_year.strftime('%Y/%m/%d %H %M %S')# 2021/01/01 00 00 00new_year.strftime('%A, %b %d')# Friday, Jan 01# Extract from dateyear=new_year.year# 2021month=new_year.month# 01
Enter fullscreen modeExit fullscreen mode

File

# Reading a file and storing its linesfilename='demo.txt'withopen(filename)asfile:lines=file.readlines()forlineinlines:print(line)# Writing to a filefilename='settings.txt'withopen(filename,'w')asfile:file.write("MAX_USER = 100")# File exist?fromosimportpathpath.exists('templates/index.html')# True/False# CSVimportcsvcsv_file='export.csv'csv_columns=products[0].keys()# ['id', 'name']withopen(csv_file,'w')ascsvfile:writer=csv.DictWriter(csvfile,fieldnames=csv_columns)writer.writeheader()foriteminproducts:writer.writerow(item)
Enter fullscreen modeExit fullscreen mode

Catching an exception

age_string=input('Your age? ')try:age=int(age_string)exceptValueError:print("Please enter a numeric value")else:print("Your age is saved!")
Enter fullscreen modeExit fullscreen mode

OOP

# Create a classclassProduct:pass# Class attributeclassProduct:nb_products=0print(Product.nb_products)# 0# Create new object instanceproduct_1=Product()# Object instance attributesclassProduct:def__init__(self,name,price):self.name=nameself.price=price# Create instance with attributesproduct_1=Product('iPadPro',699.99)product_2=Product('iPhone12',799.99)print(product_1.name)# iPadPro# instance methodclassProduct()defdisplay_price(self):returnf"Price :{self.price}"print(product_1.display_price())# class methodclassProduct:# ...@classmethoddefcreate_default(cls):# create a instancereturncls('Product',0)# default name, default priceproduct_3=Product.create_default()# static methodclassProduct:# ...@staticmethoddeftrunc_text(word,nb_char):returnword[:nb_char]+'...'product_3=Product.trunc_text('This is a blog',5)# This i...# Python InheritanceclassWebProduct(Product):def__init__(self,name,price,web_code):super().__init__(name,price)self.web_code=web_code# Private scope (naming convention only)def__init__(self,price):self.__price=price# Getter and setterclassProduct:def__init__(self):self.__price=0@propertydefprice(self):returnself.__price@price.setterdefprice(self,value):self.__price=value# MixinsclassMixin1(object):deftest(self):print"Mixin1"classMixin2(object):deftest(self):print"Mixin2"classMyClass(Mixin2,Mixin1,BaseClass):passobj=MyClass()obj.test()# Mixin2
Enter fullscreen modeExit fullscreen mode

Module import

from my_module import my_function# import local file (same folder)# my_module.py will be the file name# my_function is a function inside my_module.py
Enter fullscreen modeExit fullscreen mode

Dont miss my next python post:Follow @EricTheCoder_




Here is my cheat sheet I created along my learning journey. If you have any recommendations (addition/subtraction) let me know.

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
python_jobs_online profile image
Python Jobs Online
Helping great developers find amazing 100% remote Python jobs

Great work!

Some suggestions for improvement:

  1. int('21.99') won't convert it to an integer. It will raise aValueError. To convert the string of21.99 to an int, you need to do thisint(float('21.99')), which will result in 21

  2. MAX_USER = 100 isn't a "const" data type. Constants are a concept vs a data type

  3. You could expand the data types to include another very common Python data structure, the good old tuple. e.g.(1,2,3,4). Plus, you may also want to include sets, e.g.{1, 2, 3}

I didn't read any further, but thought I'd point out those couple of quick items that I noticed.

All the best

CollapseExpand
 
mccurcio profile image
Matt Curcio
Scientist able to bridge multiple disciplines seeks position in data science.
  • Email
  • Location
    MA, USA
  • Education
    Self-Taught Data Scientist with scientific background
  • Joined

Good Job!

BTW, Eric the Coder, meetRoger the Shruber ;)

CollapseExpand
 
mikowhy profile image
Mikolaj Paczkowski
Junior Python Developer 🐍 after 14 years in digital marketing
  • Location
    Poznan / Poland / Europe
  • Work
    Python Dev
  • Joined

Convert to string

number = 50 + int("50") # 100

isn't it conversion to int?

CollapseExpand
 
pliade_border_b3412bc3f6 profile image
Pléiade Border
je suis tchadien, africain un élève de 1ére qui veut apprendre à programmer .
  • Joined

excellent

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Businessman and blogger #Javascript, #Python and #PHP. My favorite frameworks/librairies are #React, #Laravel, and #Django. I am also a fan of #TailwindCSS
  • Location
    Canada
  • Joined

More fromEric The Coder

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp