Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Python Sheet

Uploaded by

vthieunhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Sheet

Uploaded by

vthieunhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

counter = counter + 10 # => >>> a = {"one": 1, "two": 2,

Slicing String 10 "three": 3}


>>> msg = "Hello, World!" >>> a["one"]
>>> print(msg[2:5]) message = "Part 1." 1
llo >>> a.keys()
Lists # => Part 1.Part 2. dict_keys(['one', 'two', 'three'])
mylist = [] message += "Part 2." >>> a.values()
mylist.append(1) dict_values([1, 2, 3])
mylist.append(2) f-Strings (Python 3.6+) >>> a.update({"four": 4})
for item in mylist: >>> website = 'Quickref.ME' >>> a.keys()
print(item) # prints out 1,2 >>> f"Hello, {website}" dict_keys(['one', 'two', 'three',
If Else "Hello, Quickref.ME" 'four'])
num = 200 >>> a['four']
if num > 0: >>> num = 10 4
print("num is greater than >>> f'{num} + 10 = {num +
0") 10}' Key: Value pair, JSON like
else: '10 + 10 = 20' object
print("num is not greater #Python Built-in Data Types Casting
than 0") Strings Integers
Loops hello = "Hello World" x = int(1) # x will be 1
for item in range(6): hello = 'Hello World' y = int(2.8) # y will be 2
if item == 3: break z = int("3") # z will be 3
print(item) Numbers
else: x = 1 # int Floats
print("Finally finished!") y = 2.8 # float x = float(1) # x will be 1.0
Functions z = 1j # complex y = float(2.8) # y will be 2.8
>>> def my_function(): z = float("3") # z will be 3.0
... print("Hello from a >>> print(type(x)) w = float("4.2") # w will be 4.2
function") <class 'int'>
... Strings
>>> my_function() Booleans x = str("s1") # x will be 's1'
Hello from a function my_bool = True y = str(2) # y will be '2'
File Handling my_bool = False z = str(3.0) # z will be '3.0'
with open("myfile.txt", "r",
encoding='utf8') as file: bool(0) # => False #Python Advanced Data Types
for line in file: bool(1) # => True Heaps
print(line) import heapq
Arithmetic Lists
result = 10 + 30 # => 40 list1 = ["apple", "banana", myList = [9, 5, 4, 1, 3, 2]
result = 40 - 10 # => 30 "cherry"] heapq.heapify(myList)
result = 50 * 5 # => 250 list2 = [True, False, False] # turn myList into a Min Heap
result = 16 / 4 # => 4.0 (Float list3 = [1, 5, 7, 9, 3] print(myList) # => [1, 3, 2,
Division) list4 = list((1, 5, 7, 9, 3)) 5, 9, 4]
result = 16 // 4 # => 4 (Integer Tuple print(myList[0]) # first value is
Division) my_tuple = (1, 2, 3) always the smallest in the heap
result = 25 % 2 # => 1 my_tuple = tuple((1, 2, 3))
result = 5 ** 3 # => 125 heapq.heappush(myList, 10) #
Similar to List but immutable insert 10
The / means quotient of x and Set x = heapq.heappop(myList) #
y, and the // means floored set1 = {"a", "b", "c"} pop and return smallest item
quotient of x and y, Plus- set2 = set(("a", "b", "c")) print(x) # => 1
Equals
counter = 0 Set of unique items/objects Negate all values to use Min
counter += 10 # => 10 Dictionary Heap as Max Heap
counter = 0 >>> empty_dict = {} myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in >>> s[::-1]
myList] # multiply by -1 to Get the character at position 1 '543215432154321543215432
negate or last 1'
heapq.heapify(myList) Looping
>>> for char in "foo": String Length
x = heapq.heappop(myList) ... print(char) >>> hello = "Hello, World!"
print(-x) # => 9 (making sure f >>> print(len(hello))
to multiply by -1 again) o 13
o
Heaps are binary trees for The len() function returns the
which every parent node has a Loop through the letters in the length of a string
value less than or equal to any word "foo" Multiple copies
of its children. Useful for Slicing string >>> s = '===+'
accessing min/max value ┌───┬───┬───┬───┬ >>> n = 8
quickly. Time complexity: ───┬───┬───┐ >>> s * n
O(n) for heapify, O(log n) |m|y|b|a|c|o|n| '===+===+===+===+===+=
push and pop. See: Heapq └───┴───┴───┴───┴ ==+===+===+'
Stacks and Queues ───┴───┴───┘
from collections import deque 0 1 2 3 4 5 6 7 Check String
-7 -6 -5 -4 -3 -2 -1 >>> s = 'spam'
q = deque() # empty >>> s in 'I saw spamalot!'
q = deque([1, 2, 3]) # with True
values >>> s = 'mybacon' >>> s not in 'I saw The Holy
>>> s[2:5] Grail!'
q.append(4) # append to 'bac' True
right side >>> s[0:2]
q.appendleft(0) # append to 'my' Concatenates
left side >>> s = 'spam'
print(q) # => deque([0, 1, 2, >>> s = 'mybacon' >>> t = 'egg'
3, 4]) >>> s[:2] >>> s + t
'my' 'spamegg'
x = q.pop() # remove & return >>> s[2:] >>> 'spam' 'egg'
from right 'bacon' 'spamegg'
y = q.popleft() # remove & >>> s[:2] + s[2:]
return from left 'mybacon' Formatting
print(x) # => 4 >>> s[:] name = "John"
print(y) # => 0 'mybacon' print("Hello, %s!" % name)
print(q) # => deque([1, 2, 3])
>>> s = 'mybacon' name = "John"
q.rotate(1) # rotate 1 step to >>> s[-5:-1] age = 23
the right 'baco' print("%s is %d years old." %
print(q) # => deque([3, 1, 2]) >>> s[2:6] (name, age))
'baco'
Deque is a double-ended queue format() Method
with O(1) time for append/pop With a stride txt1 = "My name is {fname},
operations from both sides. >>> s = '12345' * 5 I'm
Used as stacks and queues. >>> s {age}".format(fname="John",
See: Deque '123451234512345123451234 age=36)
#Python Strings 5' txt2 = "My name is {0}, I'm
Array-like >>> s[::5] {1}".format("John", 36)
>>> hello = "Hello, World" '11111' txt3 = "My name is {}, I'm
>>> print(hello[1]) >>> s[4::5] {}".format("John", 36)
e '55555'
>>> print(hello[-1]) >>> s[::-5] Input
d '55555'
>>> name = input("Enter your >>> f'{"test":*^10}' # fill >>> f'{0.25:.0%}'
name: ") center '25%'
Enter your name: Tom '***test***'
>>> name >>> f'{12345:0>10}' # fill F-Strings Sign
'Tom' with numbers >>> f'{12345:+}' # [sign]
'0000012345' (+/-)
Get input data from console '+12345'
Join f-Strings Type >>> f'{-12345:+}'
>>> "#".join(["John", "Peter", >>> f'{10:b}' # binary '-12345'
"Vicky"]) type >>> f'{-12345:+10}'
'John#Peter#Vicky' '1010' ' -12345'
>>> f'{10:o}' # octal type >>> f'{-12345:+010}'
Endswith '12' '-000012345'
>>> "Hello, >>> f'{200:x}' #
world!".endswith("!") hexadecimal type #Python Lists
True 'c8' Defining
>>> f'{200:X}' >>> li1 = []
#Python F-Strings (Since 'C8' >>> li1
Python 3.6+) >>> f'{345600000000:e}' # []
f-Strings usage scientific notation >>> li2 = [4, 5, 6]
>>> website = 'Quickref.ME' '3.456000e+11' >>> li2
>>> f"Hello, {website}" >>> f'{65:c}' # character [4, 5, 6]
"Hello, Quickref.ME" type >>> li3 = list((1, 2, 3))
'A' >>> li3
>>> num = 10 >>> f'{10:#b}' # [type] with [1, 2, 3]
>>> f'{num} + 10 = {num + notation (base) >>> li4 = list(range(1, 11))
10}' '0b1010' >>> li4
'10 + 10 = 20' >>> f'{10:#o}' [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
'0o12'
>>> f"""He said {"I'm >>> f'{10:#x}' Generate
John"}""" '0xa' >>> list(filter(lambda x : x %
"He said I'm John" 2 == 1, range(1, 20)))
F-Strings Others [1, 3, 5, 7, 9, 11, 13, 15, 17,
>>> f'5 {"{stars}"}' >>> f'{-12345:0=10}' # 19]
'5 {stars}' negative numbers
>>> f'{{5}} {"stars"}' '-000012345' >>> [x ** 2 for x in range (1,
'{5} stars' >>> f'{12345:010}' # [0] 11) if x % 2 == 1]
shortcut (no align) [1, 9, 25, 49, 81]
>>> name = 'Eric' '0000012345'
>>> age = 27 >>> f'{-12345:010}' >>> [x for x in [3, 4, 5, 6, 7] if
>>> f"""Hello! '-000012345' x > 5]
... I'm {name}. >>> import math # [6, 7]
... I'm {age}.""" [.precision]
"Hello!\n I'm Eric.\n I'm >>> math.pi >>> list(filter(lambda x: x > 5,
27." 3.141592653589793 [3, 4, 5, 6, 7]))
>>> f'{math.pi:.2f}' [6, 7]
f-Strings Fill Align '3.14'
>>> f'{"text":10}' # [width] >>> f'{1000000:,.2f}' # Append
'text ' [grouping_option] >>> li = []
>>> f'{"test":*>10}' # fill left '1,000,000.00' >>> li.append(1)
'******test' >>> f'{1000000:_.2f}' >>> li
>>> f'{"test":*<10}' # fill '1_000_000.00' [1]
right >>> f'{0.25:0%}' # >>> li.append(2)
'test******' percentage >>> li
'25.000000%' [1, 2]
>>> li.append(4) Basic
>>> li Remove num = 5
[1, 2, 4] >>> li = ['bread', 'butter', if num > 10:
>>> li.append(3) 'milk'] print("num is totally bigger
>>> li >>> li.pop() than 10.")
[1, 2, 4, 3] 'milk' elif num < 10:
>>> li print("num is smaller than
List Slicing ['bread', 'butter'] 10.")
Syntax of list slicing: >>> del li[0] else:
a_list[start:end] >>> li print("num is indeed 10.")
a_list[start:end:step] ['butter']
One line
Slicing Access >>> a = 330
>>> a = ['spam', 'egg', 'bacon', >>> li = ['a', 'b', 'c', 'd'] >>> b = 200
'tomato', 'ham', 'lobster'] >>> li[0] >>> r = "a" if a > b else "b"
>>> a[2:5] 'a' >>> print(r)
['bacon', 'tomato', 'ham'] >>> li[-1] a
>>> a[-5:-2] 'd'
['egg', 'bacon', 'tomato'] >>> li[4] else if
>>> a[1:4] Traceback (most recent call value = True
['egg', 'bacon', 'tomato'] last): if not value:
File "<stdin>", line 1, in print("Value is False")
Omitting index <module> elif value is None:
>>> a[:4] IndexError: list index out of print("Value is None")
['spam', 'egg', 'bacon', 'tomato'] range else:
>>> a[0:4] print("Value is True")
['spam', 'egg', 'bacon', 'tomato'] Concatenating
>>> a[2:] >>> odd = [1, 3, 5] #Python Loops
['bacon', 'tomato', 'ham', >>> odd.extend([9, 11, 13]) Basic
'lobster'] >>> odd primes = [2, 3, 5, 7]
>>> a[2:len(a)] [1, 3, 5, 9, 11, 13] for prime in primes:
['bacon', 'tomato', 'ham', >>> odd = [1, 3, 5] print(prime)
'lobster'] >>> odd + [9, 11, 13]
>>> a [1, 3, 5, 9, 11, 13] Prints: 2 3 5 7
['spam', 'egg', 'bacon', 'tomato', With index
'ham', 'lobster'] Sort & Reverse animals = ["dog", "cat",
>>> a[:] >>> li = [3, 1, 3, 2, 5] "mouse"]
['spam', 'egg', 'bacon', 'tomato', >>> li.sort() # enumerate() adds counter to
'ham', 'lobster'] >>> li an iterable
[1, 2, 3, 3, 5] for i, value in
With a stride >>> li.reverse() enumerate(animals):
['spam', 'egg', 'bacon', 'tomato', >>> li print(i, value)
'ham', 'lobster'] [5, 3, 3, 2, 1]
>>> a[0:6:2] Prints: 0 dog 1 cat 2 mouse
['spam', 'bacon', 'ham'] Count While
>>> a[1:6:2] >>> li = [3, 1, 3, 2, 5] x=0
['egg', 'tomato', 'lobster'] >>> li.count(3) while x < 4:
>>> a[6:0:-2] 2 print(x)
['lobster', 'tomato', 'egg'] x += 1 # Shorthand for x =
>>> a Repeating x+1
['spam', 'egg', 'bacon', 'tomato', >>> li = ["re"] * 3
'ham', 'lobster'] >>> li Prints: 0 1 2 3
>>> a[::-1] ['re', 're', 're'] Break
['lobster', 'ham', 'tomato', x=0
'bacon', 'egg', 'spam'] #Python Flow control for index in range(10):
x = index * 10 add(5, 6) # => 11 import math as m
if index == 5:
break Positional arguments # => True
print(x) def varargs(*args): math.sqrt(16) == m.sqrt(16)
return args
Prints: 0 10 20 30 40 Functions and attributes
Continue varargs(1, 2, 3) # => (1, 2, 3) import math
for index in range(3, 8): dir(math)
x = index * 10 Keyword arguments
if index == 5: def keyword_args(**kwargs): #Python File Handling
continue return kwargs Read file
print(x) Line by line
# => {"big": "foot", "loch": with open("myfile.txt") as file:
Prints: 30 40 60 70 "ness"} for line in file:
Range keyword_args(big="foot", print(line)
for i in range(4): loch="ness")
print(i) # Prints: 0 1 2 3 With line number
Returning multiple file = open('myfile.txt', 'r')
for i in range(4, 8): def swap(x, y): for i, line in enumerate(file,
print(i) # Prints: 4 5 6 7 return y, x start=1):
print("Number %s: %s" %
for i in range(4, 10, 2): x=1 (i, line))
print(i) # Prints: 4 6 8 y=2
x, y = swap(x, y) # => x = 2, y String
With zip() =1 Write a string
words = ['Mon', 'Tue', 'Wed'] contents = {"aa": 12, "bb": 21}
nums = [1, 2, 3] Default Value with open("myfile1.txt", "w+")
# Use zip to pack into a tuple def add(x, y=10): as file:
list return x + y file.write(str(contents))
for w, n in zip(words, nums):
print('%d:%s, ' %(n, w)) add(5) # => 15 Read a string
add(5, 20) # => 25 with open('myfile1.txt', "r+")
Prints: 1:Mon, 2:Tue, 3:Wed, as file:
for/else Anonymous functions contents = file.read()
nums = [60, 70, 30, 110, 90] # => True print(contents)
for n in nums: (lambda x: x > 2)(3)
if n > 100: Object
print("%d is bigger than # => 5 Write an object
100" %n) (lambda x, y: x ** 2 + y ** 2) contents = {"aa": 12, "bb": 21}
break (2, 1) with open("myfile2.txt", "w+")
else: as file:
print("Not found!") #Python Modules file.write(json.dumps(conten
Import modules ts))
Also see: Python Tips import math
#Python Functions print(math.sqrt(16)) # => 4.0 Read an object
Basic with open('myfile2.txt', "r+")
def hello_world(): From a module as file:
print('Hello, World!') from math import ceil, floor contents = json.load(file)
print(ceil(3.7)) # => 4.0 print(contents)
Return print(floor(3.7)) # => 3.0
def add(x, y): Delete a File
print("x is %s, y is %s" %(x, Import all import os
y)) from math import * os.remove("myfile.txt")
return x + y
Shorten module Check and Delete
import os class ParentClass: print("Child")
if os.path.exists("myfile.txt"): def print_test(self):
os.remove("myfile.txt") print("Parent Method") child_instance = ChildClass()
else: child_instance.print_self() #
print("The file does not class ChildClass(ParentClass): => Child
exist") def print_test(self):
print("Child Method") Inheritance
Delete Folder # Calls the parent's class Animal:
import os print_test() def __init__(self, name,
os.rmdir("myfolder") super().print_test() legs):
self.name = name
#Python Classes & Inheritance self.legs = legs
Defining >>> child_instance =
class MyNewClass: ChildClass() class Dog(Animal):
pass >>> child_instance.print_test() def sound(self):
Child Method print("Woof!")
# Class Instantiation Parent Method
my = MyNewClass() Yoki = Dog("Yoki", 4)
repr() method print(Yoki.name) # => YOKI
Constructors class Employee: print(Yoki.legs) # => 4
class Animal: def __init__(self, name): Yoki.sound() # => Woof!
def __init__(self, voice): self.name = name
self.voice = voice #Miscellaneous
def __repr__(self): Comments
cat = Animal('Meow') return self.name # This is a single line
print(cat.voice) # => Meow comments.
john = Employee('John')
dog = Animal('Woof') print(john) # => John """ Multiline strings can be
print(dog.voice) # => Woof written
User-defined exceptions using three "s, and are often
Method class CustomError(Exception): used
class Dog: pass as documentation.
"""
# Method of the class Polymorphism
def bark(self): class ParentClass: ''' Multiline strings can be
print("Ham-Ham") def print_self(self): written
print('A') using three 's, and are often
charlie = Dog() used
charlie.bark() # => "Ham- class ChildClass(ParentClass): as documentation.
Ham" def print_self(self): '''
print('B')
Class Variables Generators
class MyClass: obj_A = ParentClass() def double_numbers(iterable):
class_variable = "A class obj_B = ChildClass() for i in iterable:
variable!" yield i + i
obj_A.print_self() # => A
# => A class variable! obj_B.print_self() # => B Generators help you make lazy
print(MyClass.class_variable) code.
Overriding Generator to list
x = MyClass() class ParentClass: values = (-x for x in
def print_self(self): [1,2,3,4,5])
# => A class variable! print("Parent") gen_to_list = list(values)
print(x.class_variable)
class ChildClass(ParentClass): # => [-1, -2, -3, -4, -5]
Super() Function def print_self(self): print(gen_to_list)
Handle exceptions
try:
# Use "raise" to raise an
error
raise IndexError("This is an
index error")
except IndexError as e:
pass # Pass is just
a no-op. Usually you would do
recovery here.
except (TypeError,
NameError):
pass # Multiple
exceptions can be handled
together, if required.
else: # Optional
clause to the try/except block.
Must follow all except blocks
print("All good!") # Runs
only if the code in try raises no
exceptions
finally: # Execute
under all circumstances
print("We can clean up
resources here")

You might also like