100% satisfaction guarantee Immediately available after payment Both online and in PDF No strings attached 4.2 TrustPilot
logo-home
Other

Python cheatsheat

Rating
-
Sold
-
Pages
7
Uploaded on
30-03-2024
Written in
2023/2024

My documents covers python languages fundamentals like data types, manipulation,web development,data science so on.

Institution
Course









Whoops! We can’t load your doc right now. Try again or contact support.

Connected book

Written for

Institution
Course

Document information

Uploaded on
March 30, 2024
Number of pages
7
Written in
2023/2024
Type
Other
Person
Unknown

Subjects

Content preview

Python Notes/Cheat Sheet

Comments Operators
# from the hash symbol to the end of a line Operator Functionality
+ Addition (also string, tuple, list
Code blocks concatenation)
Delineated by colons and indented code; and not the - Subtraction (also set difference)
curly brackets of C, C++ and Java. * Multiplication (also string, tuple, list
def is_fish_as_string(argument): replication)
if argument:
return ‘fish’
/ Division
else: % Modulus (also a string format function,
return ‘not fish’ but use deprecated)
Note: Four spaces per indentation level is the Python // Integer division rounded towards minus
standard. Never use tabs: mixing tabs and spaces infinity
produces hard-to-find errors. Set your editor to convert ** Exponentiation
tabs to spaces. =, -=, +=, /=, Assignment operators
*=, %=, //=,
Line breaks **=
Typically, a statement must be on one line. Bracketed ==, !=, <, <=, Boolean comparisons
code - (), [] or {} - can be split across lines; or (if you >=, >
must) use a backslash \ at the end of a line to continue a and, or, not Boolean operators
statement on to the next line (but this can result in hard in, not in Membership test operators
to debug code). is, is not Object identity operators
|, ^, &, ~ Bitwise: or, xor, and, compliment
Naming conventions
<<, >> Left and right bit shift
Style Use
; Inline statement separator
StudlyCase Class names # inline statements discouraged
joined_lower Identifiers, functions; and class Hint: float('inf') always tests as larger than any number,
methods, attributes including integers.
_joined_lower Internal class attributes
__joined_lower Private class attributes Modules
# this use not recommended Modules open up a world of Python extensions that can
joined_lower Constants be imported and used. Access to the functions, variables
ALL_CAPS and classes of a module depend on how the module
was imported.
Basic object types (not a complete list) Import method Access/Use syntax
Type Examples import math math.cos(math.pi/3)
None None # singleton null object import math as m m.cos(m.pi/3)
Boolean True, False # import using an alias
integer -1, 0, 1, sys.maxint from math import cos,pi cos(pi/3)
long 1L, 9787L # arbitrary length ints # only import specifics
float 3.14159265 from math import * log(e)
inf, float('inf') # infinity # BADish global import
-inf # neg infinity Global imports make for unreadable code!!!
nan, float('nan') # not a number
complex 2+3j # note use of j Oft used modules
string 'I am a string', "me too" Module Purpose
'''multi-line string''', """+1""" datetime Date and time functions
r'raw string', b'ASCII string' time
u'unicode string' math Core math functions and the constants pi
tuple empty = () # empty tuple and e
(1, True, 'dog') # immutable list pickle Serialise objects to a file
list empty = [] # empty list os Operating system interfaces
[1, True, 'dog'] # mutable list os.path
set empty = set() # the empty set re A library of Perl-like regular expression
set(1, True, 'a') # mutable operations
dictionary empty = {} # mutable object string Useful constants and classes
{'a': 'dog', 7: 'seven’, True: 1} sys System parameters and functions
file f = open('filename', 'rb') numpy Numerical python library
Note: Python has four numeric types (integer, float, long pandas R DataFrames for Python
and complex) and several sequence types including matplotlib Plotting/charting for Python
strings, lists, tuples, bytearrays, buffers, and xrange
objects.

Version 14 March 2015 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter] 1"

, If - flow control Objects and variables (AKA identifiers)
if condition: # for example: if x < 5: • Everything is an object in Python (in the sense that it
statements can be assigned to a variable or passed as an
elif condition: # optional – can be multiple argument to a function)
statements • Most Python objects have methods and attributes.
else: # optional
For example, all functions have the built-in attribute
statements
__doc__, which returns the doc string defined in the
function's source code.
For - flow control
• All variables are effectively "pointers", not "locations".
for x in iterable:
They are references to objects; and often called
statements
else: # optional completion code identifiers.
statements • Objects are strongly typed, not identifiers
• Some objects are immutable (int, float, string, tuple,
While - flow control frozenset). But most are mutable (including: list, set,
while condition: dictionary, NumPy arrays, etc.)
statements • You can create our own object types by defining a
else: # optional completion code new class (see below).
statements
Booleans and truthiness
Ternary statement Most Python objects have a notion of "truth".
id = expression if condition else expression False True
x = y if a > b else z - 5 None
0 Any number other than 0
Some useful adjuncts: int(False) # ! 0 int(True) # ! 1
• pass - a statement that does nothing "" " ", 'fred', 'False'
• continue - moves to the next loop iteration # the empty string # all other strings
• break - to exit for and while loop () [] {} set() [None], (False), {1, 1}
Trap: break skips the else completion code # empty containers # non-empty containers,
including those containing
Exceptions – flow control False or None.
try:
statements You can use bool() to discover the truth status of an
except (tuple_of_errors): # can be multiple object.
statements a = bool(obj) # the truth of obj
else: # optional no exceptions
statements
finally: # optional all It is pythonic to use the truth of objects.
statements if container: # test not empty
# do something
while items: # common looping idiom
Common exceptions (not a complete list) item = items.pop()
Exception Why it happens # process item
AsserionError Assert statement failed
AttributeError Class attribute assignment or Specify the truth of the classes you write using the
reference failed __nonzero__() magic method.
IOError Failed I/O operation
ImportError Failed module import Comparisons
IndexError Subscript out of range Python lets you compare ranges, for example
KeyError Dictionary key not found if 1 < x < 100: # do something ...
MemoryError Ran out of memory
NameError Name not found Tuples
TypeError Value of the wrong type Tuples are immutable lists. They can be searched,
ValueError Right type but wrong value indexed and iterated much like lists (see below). List
methods that do not change the list also work on tuples.
a = () # the empty tuple
Raising errors
a = (1,) # " note comma # one item tuple
Errors are raised using the raise statement
a = (1, 2, 3) # multi-item tuple
raise ValueError(value) a = ((1, 2), (3, 4)) # nested tuple
a = tuple(['a', 'b']) # conversion
Creating new errors Note: the comma is the tuple constructor, not the
class MyError(Exception): parentheses. The parentheses add clarity.
def __init__(self, value):
self.value = value The Python swap variable idiom
def __str__(self):
return repr(self.value) a, b = b, a # no need for a temp variable
This syntax uses tuples to achieve its magic.




Version 14 March 2015 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter] 2"
$11.39
Get access to the full document:

100% satisfaction guarantee
Immediately available after payment
Both online and in PDF
No strings attached

Get to know the seller
Seller avatar
harinim

Get to know the seller

Seller avatar
harinim Pallapatti Higher Secondary School
Follow You need to be logged in order to follow users or courses
Sold
0
Member since
1 year
Number of followers
0
Documents
1
Last sold
-

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Frequently asked questions