Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
1156 lines (855 loc) · 16.2 KB

File metadata and controls

1156 lines (855 loc) · 16.2 KB
titlePython
date2020-12-23 10:41:20 -0800
iconicon-python
backgroundbg-blue-600
tags
script
interpret
categories
Programming
introThe [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.

Getting Started {.cols-3}

Introduction

Hello World

>>>print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python

Variables

x=4# x is of type intx="Sally"# x is now of type strprint(x)

Python has no command for declaring a variable.

Data Types {.row-span-2}

strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary
See: Data Types

Slicing String

>>>b="Hello, World!">>>print(b[2:5])
llo

See: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
forxinmylist:
print(x) # prints out 1,2

See: Lists

If Else

a=200ifa>0:
print("a is greater than 0")
else:
print("a is not greater than 0")

See: Flow control

Loops

forxinrange(6):
ifx==3: breakprint(x)
else:
print("Finally finished!")

See: Loops

Functions

>>>defmy_function():
... print("Hello from a function")
...
>>>my_function()
Hellofromafunction

See: Functions

File Handling {.col-span-2}

withopen("myfile.txt", "r", encoding='utf8') asfile:
forxinfile:
print(x)

See: File Handling

Arithmetic

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4result=25%2# => 1result=5**3# => 125

Plus-Equals

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

Python Data Types {.cols-3}

Strings

s="Hello World"s='Hello World'a="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

See: Strings

Numbers

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

Booleans

a=Trueb=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

See: Lists

Tuple

a= (1, 2, 3)
a=tuple((1, 2, 3))

Similar to List but immutable

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

Set of unique items/objects

Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key: Value pair, JSON like object

Casting

Integers

x=int(1) # x will be 1y=int(2.8) # y will be 2z=int("3") # z will be 3

Floats

x=float(1) # x will be 1.0y=float(2.8) # y will be 2.8z=float("3") # z will be 3.0w=float("4.2") # w will be 4.2

Strings

x=str("s1") # x will be 's1'y=str(2) # y will be '2'z=str(3.0) # z will be '3.0'

Python Strings {.cols-3}

Array-like

>>>a="Hello, World">>>print(a[1])
e>>>print(a[len(a)-1])
d

Get the character at position 1

Looping

>>>forxin"abc":
... print(x)
abc

Loop through the letters in the word "banana"

Slicing string {.row-span-4}

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'
>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'
>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

With a stride

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

String Length

>>>a="Hello, World!">>>print(len(a))
13

The len() function returns the length of a string

Multiple copies

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

Check String

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

Concatenates

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

Formatting {.col-span-2}

name="John"print("Hello, %s!"%name)
name="John"age=23print("%s is %d years old."% (name, age))

format() Method

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John",36)
txt3="My name is {}, I'm {}".format("John",36)

Input

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

Get input data from console

Join

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith

>>>"Hello, world!".endswith("!")
True

Python Lists {.cols-3}

Defining

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Generate {.col-span-2}

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

Append

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List Slicing {.col-span-2 .row-span-3}

Syntax of list slicing:

a_list[start:end]
a_list[start:end:step]

Slicing

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Remove

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

Access

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

Concatenating {.row-span-2}

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

Sort & Reverse {.row-span-2}

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

Count

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

Repeating

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python Flow control {.cols-3}

Basic

a=5ifa>10:
print("a is totally bigger than 10.")
elifa<10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

One line

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python Loops {.cols-3}

Basic

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

With index

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

Range

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

With zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

List Comprehension {.col-span-2}

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python Functions {.cols-3}

Basic

defhello_world(): print('Hello, World!')

Return

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

Positional arguments

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

Keyword arguments

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

Returning multiple

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

Default Value

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

Anonymous functions

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python Modules {.cols-3}

Import modules

importmathprint(math.sqrt(16)) # => 4.0

From a module

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

Import all

frommathimport*

Shorten module

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

Functions and attributes

importmathdir(math)

Python File Handling {.cols-3}

Read file

Line by line

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

With line number

input=open('myfile.txt', 'r')
fori,lineinenumerate(input, start=1):
print("Number %s: %s"% (i, line))

String

Write a string

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

Read a string

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

Object

Write an object

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

Read an object

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

Delete a File

importosos.remove("myfile.txt")

Check and Delete

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

Delete Folder

importosos.rmdir("myfolder")

Python Classes & Inheritance {.cols-3}

Defining

classMyNewClass:
'''This is a docstring.'''pass# Class Instantiationmy=MyNewClass()

Constructors

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

Method

classDog:
# Method of the classdefbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

Class Variables {.row-span-2}

classmy_class:
class_variable="A class variable!"x=my_class()
y=my_class()
# => A class variable!print(x.class_variable)
# => A class variable!print(y.class_variable)

Super() Function {.row-span-2}

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# Calls the parent's print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() method

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

User-defined exceptions

classCustomError(Exception):
pass

Polymorphism

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

Overriding

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

Inheritance

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

Miscellaneous {.cols-3}

Comments

# This is a single line comments.
""" Multiline strings can be written using three "s, and are often used as documentation."""
''' Multiline strings can be written using three 's, and are often used as documentation.'''

Generators

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

Generators help you make lazy code.

Generator to list

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

Handle exceptions {.col-span-3}

try:
# Use "raise" to raise an errorraiseIndexError("This is an index error")
exceptIndexErrorase:
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 blocksprint("All good!") # Runs only if the code in try raises no exceptionsfinally: # Execute under all circumstancesprint("We can clean up resources here")