0% found this document useful (0 votes)
360 views2 pages

Begginer's Python Cheat Sheet-Essentials PDF

This document provides a concise cheat sheet summarizing essential Python concepts including: - Data types like integers, floats, strings, booleans, lists, tuples, dictionaries, and sets. - Common operators for comparisons, arithmetic, boolean, and assignment. - Control flow statements such as if/else, while loops, and for loops. - Functions for string formatting, file I/O, exiting programs, and getting user input. - Methods for common list, tuple, string, and dictionary operations. - Exceptions, modules, functions, and snippets of reusable Python code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
360 views2 pages

Begginer's Python Cheat Sheet-Essentials PDF

This document provides a concise cheat sheet summarizing essential Python concepts including: - Data types like integers, floats, strings, booleans, lists, tuples, dictionaries, and sets. - Common operators for comparisons, arithmetic, boolean, and assignment. - Control flow statements such as if/else, while loops, and for loops. - Functions for string formatting, file I/O, exiting programs, and getting user input. - Methods for common list, tuple, string, and dictionary operations. - Exceptions, modules, functions, and snippets of reusable Python code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Essential Python Cheat Sheet

by sschaub via cheatography.com/1000/cs/374/

Data Types Comparison Operators More String Operations (cont)

Integer -256, 15 x< y Less x <= y Less or eq s.st​rip() copy of s with whitespace trimmed

Float -253.23, 1.253e-10 x>y Greater x >= y Greater or eq s.up​per() uppercase copy of s

String "​Hel​lo", 'Goodbye', "​"​"​Mul​til​ine​"​"​" x == y Equal x != y Not equal See also


Boolean True, False http:/​/do​cs.p​yt​hon.or​g/l​ibr​ary​/st​dty​pes.ht​ml#​str​ing​-
Boolean Operators me​thods
List [ value, ... ]

Tuple ( value, ... )1 not x x and y x or y


Mutating List Operations
Dictionary { key: value, ... }
Exception Handling del lst[i] Deletes ith item from lst
Set { value, value, ... }2
try: lst.a​pp​end​( e) Appends e to lst
1 Parent​heses usually optional
​ ​sta​tements lst.i​ns​ert​(i, e) Inserts e before ith item in lst
2 Create an empty set with set()
except [ exception type [ as var ] ]:
lst.s​ort() Sorts lst
​ ​sta​tements
Statements finally: See also
​ ​sta​tements http:/​/do​cs.p​yt​hon.or​g/l​ibr​ary​/st​dty​pes.ht​ml#​typ​ess​
If Statem​ent eq-​mutable
if expre​ssion:
Conversion Functions
​ ​sta​tements Dictionary Operations
elif expre​ssion: int(e​xpr) Converts expr to integer
​ ​sta​tements len(d) Number of items in d
float(​ expr) Converts expr to float
else: del d[key] Removes key from d
str(e​xpr) Converts expr to string
​ ​sta​tements
key in d True if d contains key
While Loop chr(num) ASCII char num
while expre​ssion: d.keys() Returns a list of keys in d

​ ​sta​tements String / List / Tuple Operations See also


For Loop http:/​/do​cs.p​yt​hon.or​g/l​ibr​ary​/st​dty​pes.ht​ml#​map​pi
len(s) length of s
for var in colle​ction: n​g-t​ype​s-dict
​ ​sta​tements s[i] ith item in s (0-based)
Counting For Loop s[s​tart : slice of s from start (included) to Function Defini​tions
for i in range(​st​art, end [, step]): end] end (excluded)
​ ​sta​tements def name​( a​rg1, arg2, ...):
x in s True if x is contained in s
​ s​ ta
​ tem
​ ents
(start is included; end is not)
x not in s True if x is not contained in s ​ ​return expr

Arithmetic Operators s+t the concat​enation of s with t


Enviro​nment
s *n n copies of s concat​enated
x+y add x-y subtract
sys.argv List of command line arguments
x*y multiply x/y divide sorted​(s a sorted copy of s
) (argv[0] is execut​able)
x%y modulus x ** y xy
os.environ Dictionary of enviro​nment
s.in​dex​( position in s of item
Assignment shortcuts: x op= y variables
i​tem)
Example: x += 1 increments x os.curdir String with path of current
More String Operations directory

s.lo​wer() lowercase copy of s import sys; print(​sys.ar​gv)​ ​ ​ ​or


from sys import argv; print(​argv)
s.re​pla​ce(​old, copy of s with old replaced
new) with new

s.split( delim ) list of substrings delimited by


delim

By sschaub Published 21st May, 2012. Sponsored by CrosswordCheats.com


cheatography.com/sschaub/ Last updated 2nd June, 2014. Learn to solve cryptic crosswords!
Page 1 of 2. http://crosswordcheats.com
Essential Python Cheat Sheet
by sschaub via cheatography.com/1000/cs/374/

String Formatting

"​Hello, {0} {1}".fo​rma​t("a​be", "​jon​es")


Hello, abe jones
"​Hello, {fn} {ln}".f​orm​at(​fn=​"​abe​", ln="​jon​es")
Hello, abe jones
"You owe me ${0:,.2​f}​".fo​rma​t(2​534​22.3)
You owe me $253,4​22.30
now = dateti​me.n​ow()
'{:%Y-​%m-%d %H:%M:​%S}​'.f​orm​at(now)
2012-​05-16 15:04:33

See also http:/​/do​cs.p​yt​hon.or​g/l​ibr​ary​/st​rin​g.h​tml​#fo​rma​t-


s​pec​ifi​cat​ion​-mi​ni-​lan​guage

Useful Functions

exit( code ) Terminate program with exit code

raw_in​put​("p​rom​pt​") Print prompt and readline() from stdin1

1 Use input(​"p
​ r​omp​t") in Python 3

Code Snippets

Loop Over Sequence


for index, value in enumer​ate​(seq):
​ ​pri​nt(​"{} : {}".f​or​mat​(index, value))
Loop Over Dictio​nary
for key in sorted​(dict):
​ ​pri​nt(​dic​t[key])
Read a File
with open("f​ile​nam​e", "​r") as f:
​ for line in f:
​ ​ ​ line = line.r​str​ip(​"​\n") # Strip newline
​ ​ ​ ​pri​nt(​line)

Other References

http:/​/rg​rue​t.f​ree.fr/
Great Python 2.x Quick Reference
http:/​/ww​w.c​hea​tog​rap​hy.c​om​/da​vec​hil​d/c​hea​t-s​hee​ts/​python/
More Python Cheatsheet Goodness

By sschaub Published 21st May, 2012. Sponsored by CrosswordCheats.com


cheatography.com/sschaub/ Last updated 2nd June, 2014. Learn to solve cryptic crosswords!
Page 2 of 2. http://crosswordcheats.com

You might also like