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

Finxter CheatSheets Python

The document summarizes key Python keywords and their uses. It covers boolean values and operators, control flow keywords like if/else and for/while loops, data types including integers, floats, strings, and their basic operations. Functions are defined using def and return values. Classes are defined using class to create user-defined data types.

Uploaded by

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

Finxter CheatSheets Python

The document summarizes key Python keywords and their uses. It covers boolean values and operators, control flow keywords like if/else and for/while loops, data types including integers, floats, strings, and their basic operations. Functions are defined using def and return values. Classes are defined using class to create user-defined data types.

Uploaded by

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

Python Cheat Sheet: Keywords 

“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 

Keyword  Description  Code example 

False​, ​True  Data values from the data type Boolean  False​ == (​1 ​> ​2​), ​True​ == (​2 ​> ​1​)

and​, ​or​, ​not  Logical operators:  x, y = ​True​, ​False


(x ​and​ y)​ → both x and y must be True  (x ​or​ y) == ​True​ ​# True
(x ​or​ y)​ → either x or y must be True  (x ​and​ y) == ​False​ ​ True
#
(​not​ x)​ → x must be false  (​not​ y) == ​True​ ​ True
#

break  Ends loop prematurely  while​(​True​):


​break​ ​# no infinite loop
print(​"hello world"​)

continue  Finishes current loop iteration  while​(​True​):


​continue
print(​"43"​) ​# dead code

class Defines a new class → a real-world concept   class​ ​Beer​:


(object oriented programming)  ​def​ ​__init__​(self)​:
  self.content = ​1.0
def  Defines a new function or class method. For latter,  ​def​ ​drink​(self)​:
first parameter (“self”) points to the class object.  self.content = ​0.0
When calling class method, first parameter is implicit. 
becks = Beer() ​# constructor - create class
becks.drink() ​# beer empty: b.content == 0

if​, ​elif​, ​else  Conditional program execution: program starts with  x = int(input(​"your value: "​))
“if” branch, tries the “elif” branches, and finishes with  if​ x > ​3​: print(​"Big"​)
“else” branch (until one branch evaluates to True).  elif​ x == ​3​: print(​"Medium"​)
else​: print(​"Small"​)

for​, ​while  # For loop declaration # While loop - same semantics


for​ i ​in​ [​0​,​1​,​2​]: j = ​0
print(i)  while​ j < ​3​:
print(j)
j = j + ​1

in  Checks whether element is in sequence  42​ ​in​ [​2​, ​39​, ​42​] ​# True

is  Checks whether both elements point to the same  y = x = 3


object  x​ ​is​ ​y​ ​# True
[​3​] ​is​ [​3​] ​# False

None  Empty value constant  ​ ​()​:


def​ f
x = ​2
f() ​is​ ​None​ ​# True

lambda  Function with no name (anonymous function)  (lambda​ x: x + ​3)(3)​ ​# returns 6

return  Terminates execution of the function and passes the  def​ ​incrementor​(x)​:
flow of execution to the caller. An optional value after  ​return​ x + ​1
the return keyword specifies the function result.  incrementor(​4​) ​# returns 5
Python Cheat Sheet: Basic Data Types 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
  Description  Example 

Boolean  The Boolean data type is a truth value, either  ## 1. Boolean Operations
True​ ​or F​ alse​.  x, y = ​True​, ​False
  print(x ​and​ ​not​ y) ​# True
The Boolean operators ordered by priority:  print(​not​ x ​and​ y ​or​ x) ​# True
not​ x​ ​ → “if x is False, then x, else y” 
x ​and​ y​ → “if x is False, then x, else y”  ## 2. If condition evaluates to False
x ​or​ y​ ​ → “if x is False, then y, else x”  if​ ​None​ ​or​ ​0​ ​or​ ​0.0​ ​or​ ​''​ ​or​ [] ​or​ {} ​or​ set():
  ​# None, 0, 0.0, empty strings, or empty
These comparison operators evaluate to ​True​:  ​# container types are evaluated to False
1​ < ​2​ ​and​ ​0​ <= ​1​ ​and​ ​3​ > ​2​ ​and​ ​2​ >=​2​ ​and
print(​"Dead code"​) ​# Not reached
1​ == ​1​ ​and​ ​1​ != ​0​ ​# True 

Integer,  An integer is a positive or negative number  ## 3. Arithmetic Operations


Float  without floating point (e.g. ​3​). A float is a  x, y = ​3​, ​2
positive or negative number with floating point  print(x + y) ​# = 5
precision (e.g.​ ​3.14159265359​).  print(x - y) ​# = 1
  print(x * y) ​# = 6
The ‘​//​’ operator performs integer division.  print(x / y) ​# = 1.5
The result is an integer value that is rounded  print(x // y) ​# = 1
toward the smaller integer number   print(x % y) ​# = 1s
(e.g. 3​ ​ // ​2​ == ​1​).  print(-x) ​# = -3
  print(abs(-x)) ​# = 3
print(int(​3.9​)) ​# = 3
print(float(​3​)) ​# = 3.0
print(x ** y) ​# = 9

String  Python Strings are sequences of characters.   ## 4. Indexing and Slicing


  s = ​"The youngest pope was 11 years old"
The four main ways to create strings are the  print(s[​0​]) ​# 'T'
following.  print(s[​1​:​3​]) ​# 'he'
  print(s[​-3​:​-1​]) ​# 'ol'
1. Single quotes  print(s[​-3​:]) ​# 'old'
'Yes' x = s.split() ​# creates string array of words
2. Double quotes  print(x[​-3​] + ​" "​ + x[​-1​] + ​" "​ + x[​2​] + ​"s"​)
"Yes"
# '11 old popes'
3. Triple quotes (multi-line) 
"""Yes
## 5. Most Important String Methods
We Can"""
y = ​" This is lazy\t\n "
4. String method 
print(y.strip()) ​# Remove Whitespace: 'This is lazy'
str(​5​) == ​'5'​ ​# True 
print(​"DrDre"​.lower()) ​# Lowercase: 'drdre'
5. Concatenation 
print(​"attention"​.upper()) ​# Uppercase: 'ATTENTION'
"Ma"​ + ​"hatma"​ ​# 'Mahatma' 
print(​"smartphone"​.startswith(​"smart"​)) ​# True
  print(​"smartphone"​.endswith(​"phone"​)) ​# True
print(​"another"​.find(​"other"​)) ​# Match index: 2
These are whitespace characters in strings. 
print(​"cheat"​.replace(​"ch"​, ​"m"​)) ​# 'meat'
● Newline \​ n
print(​','​.join([​"F"​, ​"B"​, ​"I"​])) ​# 'F,B,I'
● Space ​ s
\
print(len(​"Rumpelstiltskin"​)) ​# String length: 15
● Tab ​ t
\ print(​"ear"​ ​in​ ​"earth"​) ​# Contains: True
Python Cheat Sheet: Complex Data Types 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
  Description  Example 

List  A container data type that stores a  l = [​1​, ​2​, ​2​]


sequence of elements. Unlike strings, lists  print(len(l)) ​# 3
are mutable: modification possible. 

Adding  Add elements to a list with (i) append, (ii)  [​1​, 2


​ ​, 2 ​ ​].append(​4​) ​# [1, 2, 2, 4]
elements  insert, or (iii) list concatenation.  [​1​, 2​ ​, 4 ​ ​].insert(​2​,​2​) ​# [1, 2, 2, 4]
The append operation is very fast.  [​1​, 2 ​ ​, 2 ​ ​] + [​4​] # [1, 2, 2, 4]

Removal  Removing an element can be slower.  [​1​, ​2​, ​2​, ​4​].remove(​1​) ​# [2, 2, 4]

Reversing  This reverses the order of list elements.  [​1​, ​2​, ​3​].reverse() ​# [3, 2, 1]

Sorting  Sorts a list. The computational complexity  [​2​, ​4​, ​2​].sort() ​# [2, 2, 4]
of sorting is linear in the no. list elements. 

Indexing  Finds the first occurence of an element in  [​2​, 2


​ ​, 4​ ​].index(​2​) ​# index of element 4 is "0"
the list & returns its index. Can be slow as  [​2​, 2​ ​, 4​ ​].index(​2​,​1​) ​# index of element 2 after pos 1 is "1"
the whole list is traversed. 

Stack  Python lists can be used intuitively as  stack = [3]


stacks via the two list operations append()  stack.append(​42​) ​# [3, 42]
and pop().  stack.pop() ​# 42 (stack: [3])
stack.pop() ​# 3 (stack: []​)

Set  A set is an unordered collection of unique  basket = {​'apple'​, ​'eggs'​, ​'banana'​, ​'orange'​}
elements (“at-most-once”).  same = set([​'apple'​, ​'eggs'​, ​'banana'​, ​'orange']​)

Dictionary  The dictionary is a useful data structure for  calories = {​'apple'​ : ​52​, ​'banana'​ : ​89​, ​'choco'​ : ​546​}
storing (key, value) pairs.  

Reading and  Read and write elements by specifying the  print(calories[​'apple'​] < calories[​'choco'​]) ​# True
writing  key within the brackets. Use the keys() and  calories[​'cappu'​] = ​74
elements  values() functions to access all keys and  print(calories[​'banana'​] < calories[​'cappu'​]) ​# False
values of the dictionary.  print(​'apple'​ ​in​ calories.keys()) ​# True
print(​52​ ​in​ calories.values()) ​# True

Dictionary  You can access the (key, value) pairs of a  for k, v in calories.items():
Looping  dictionary with the​ items()​ method.  print(k) if v > 500 else None​ ​# 'chocolate'

Membership  Check with the ‘in’ keyword whether the  basket = {​'apple'​, ​'eggs'​, ​'banana'​, ​'orange'​}
operator  set, list, or dictionary contains an element.  print(​'eggs'​ ​in​ basket) ​# True
Set containment is faster than list  print(​'mushroom'​ ​in​ basket) ​# False
containment. 

List and Set  List comprehension is the concise Python  # List comprehension
Comprehens way to create lists. Use brackets plus an  l = [(​'Hi '​ + x) ​for​ x ​in​ [​'Alice'​, ​'Bob'​, ​'Pete'​]]
ion  expression, followed by a for clause. Close  print(l) ​# ['Hi Alice', 'Hi Bob', 'Hi Pete']
with zero or more for or if clauses.   l2 = [x * y ​for​ x ​in​ range(​3​) ​for​ y ​in​ range(​3​) ​if​ x>y]
  print(l2) ​# [0, 0, 2]
Set comprehension is similar to list  # Set comprehension
comprehension.  squares = { x**​2​ ​for​ x ​in​ [​0​,​2​,​4​] ​if​ x < ​4​ } ​# {0, 4}
Python Cheat Sheet: Classes 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
  Description  Example 

Classes  A class encapsulates data and functionality: data as  class​ ​Dog​:
attributes, and functionality as methods. It is a blueprint  """ Blueprint of a dog """
for creating concrete instances in memory.  
# class variable shared by all instances
species = [​"canis lupus"​]

def​ ​__init__​(self, name, color)​:


self.name = name
self.state = ​"sleeping"
self.color = color

def​ ​command​(self, x)​:


if​ x == self.name:
self.bark(​2​)
elif​ x == ​"sit"​:
Instance  You are an instance of the class human. An instance is a  self.state = " ​ sit"
concrete implementation of a class: all attributes of an  else​:
instance have a fixed value. Your hair is blond, brown, or  self.state = " ​ wag tail"
black--but never unspecified. 
  def​ ​bark​(self, freq)​:
Each instance has its own attributes independent of  for​ i ​in​ range(freq):
other instances. Yet, class variables are different. These  print(​"["​ + self.name
are data values associated with the class, not the  + ​"]: Woof!"​)
instances. Hence, all instance share the same class 
variable ​species ​in the example. 
​ black"​)
bello = Dog(​"bello"​, "
Self  The first argument when defining any method is always  alice = Dog(​"alice"​, "​ white"​)
the ​self ​argument. This argument specifies the 
​ black
print(bello.color) #
instance on which you call the method. 
  print(alice.color) #​ white
self ​gives the Python interpreter the information about 
the concrete instance. To ​define ​a method, you use s ​ elf bello.bark(​1​) ​# [bello]: Woof!
​ n instance 
to modify the instance attributes. But to ​call a
method, you do not need to specify ​self​.  alice.command(​"sit"​)
print(​"[alice]: "​ + alice.state)
Creation  You can create classes “on the fly” and use them as  # [alice]: sit
logical units to store complex data types. 
  bello.command(​"no"​)
class​ ​Employee()​: print(​"[bello]: "​ + bello.state)
pass # [bello]: wag tail
employee = Employee()
employee.salary = ​122000 alice.command(​"alice"​)
employee.firstname = ​"alice" # [alice]: Woof!
employee.lastname = ​"wonderland" # [alice]: Woof!

print(employee.firstname + ​" " bello.species += [​"wulf"​]


+ employee.lastname + ​" " print(len(bello.species)
+ str(employee.salary) + ​"$"​) == len(alice.species)) ​# True (!)
# alice wonderland 122000$ 
Python Cheat Sheet: Functions and Tricks 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
    Description  Example  Result 

A map(func, iter)  Executes the function on all elements of  list(map(​lambda​ x: x[​0​], [​'red'​, [​'r'​, ​'g'​, ​'b'​]
D the iterable  'green'​, ​'blue'​]))
V
A map(func, i1, ..., Executes the function on all k elements of  list(map(​lambda​ x, y: str(x) + ​' '​ + [​'0 apples'​, ​'2
ik)  the k iterables  y + ​'s'​ , [​0​, ​2​, ​2​], [​'apple'​, oranges'​, ​'2
N
C 'orange'​, ​'banana'​])) bananas'​]
E
string.join(iter)  Concatenates iterable elements  ' marries '​.join(list([​'Alice'​, 'Alice marries Bob'
D separated by ​string  'Bob'​]))

F filter(func, Filters out elements in iterable for which  list(filter(​lambda​ x: ​True​ ​if​ x>​17 [​18​]
U iterable)  function returns ​False​ ​(or 0)  else​ ​False​, [​1​, ​15​, ​17​, ​18​]))
N
C string.strip()  Removes leading and trailing  print(​" \n \t 42 \t "​.strip()) 42
T whitespaces of string 
I
O sorted(iter)  Sorts iterable in ascending order  sorted([​8​, ​3​, ​2​, ​42​, ​5​]) [​2​, ​3​, ​5​, ​8​, ​42​]
N
sorted(iter, Sorts according to the key function in  sorted([​8​, ​3​, 2 ​ ​, ​42​, ​5​], key=​lambda [​42​, ​2​, ​3​, ​5​, ​8​]
S
key=key)  ascending order  x: ​0​ ​if​ x==​42​ e​ lse​ x)

help(func)  Returns documentation of ​func  help(str.upper()) '... to uppercase.'

zip(i1, i2, ...)  Groups the i-th elements of iterators ​i1, list(zip([​'Alice'​, ​'Anna'​], [​'Bob'​, [(​'Alice'​, ​'Bob'​),
i2, ...​ together  'Jon'​, ​'Frank'​])) (​'Anna'​, ​'Jon'​)]

Unzip  Equal to: 1) unpack the zipped list, 2) zip  list(zip(*[(​'Alice'​, ​'Bob'​), [(​'Alice'​, ​'Anna'​),
the result  (​'Anna'​, ​'Jon'​)])) (​'Bob'​, ​'Jon'​)]

enumerate(iter)  Assigns a counter value to each element  list(enumerate([​'Alice'​, ​'Bob'​, [(​0​, ​'Alice'​), (​1​,
of the iterable  'Jon'​])) 'Bob'​), (​2​, ​'Jon'​)]

T python -m http.server  Want to share files between PC and phone? Run this command in PC’s shell. <P> is any port number 0–65535. Type < 
R <P>  IP address of PC>:<P> in the phone’s browser. You can now browse the files in the PC directory. 
I
C Read comic  import​ antigravity Open the comic series xkcd in your web browser
K
S
Zen of Python  import​ this  '...Beautiful is better than ugly. Explicit is ...'

Swapping numbers  Swapping variables is a breeze in Python.  a, b = ​'Jane'​, ​'Alice' a = ​'Alice'


No offense, Java!  a, b = b, a b = '​ Jane'

Unpacking arguments  Use a sequence as function arguments  def​ ​f​(x, y, z)​:​ return​ x + y * z
via asterisk operator *. Use a dictionary  f(*[​1​, ​3​, ​4​]) 13
(key, value) via double asterisk operator **  f(**{​'z'​ : ​4​, ​'x'​ : ​1​, ​'y'​ : 3
​ ​}) 13

Extended Unpacking  Use unpacking for multiple assignment  a, *b = [​1​, ​2​, ​3​, ​4​, ​5​] a = ​1
feature in Python  b = [​2​, ​3​, ​4, 5​]

Merge two dictionaries  Use unpacking to merge two dictionaries  x={​'Alice'​ : ​18​} z = {​'Alice'​: ​18​,
into a single one  y={​'Bob'​ : ​27​, ​'Ann'​ : ​22​} 'Bob'​: ​27​, ​'Ann'​: ​22​}
z = {**x,**y}
Python Cheat Sheet: 14 Interview Questions 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 

Question Code Question Code

Check if list l = [​3​, ​3​, ​4​, ​5​, ​2​, ​111​, ​5​] Get missing def​ g​ et_missing_number​(lst):
contains print(​111​ ​in​ l) ​# True  number in ​return​ set(range(lst[len(lst)​-1​])[​1:
​ ]) - set(l)
integer x [1...100] l = list(range(​1​,​100​))
l.remove(​50​)
print(get_missing_number(l)) ​# 50 

Find duplicate def​ ​find_duplicates​(elements): Compute def​ i ​ ntersect​(lst1, lst2):


number in duplicates, seen = set(), set() the res, lst2_copy = [], lst2[:]
integer list ​for​ element ​in​ elements: intersection ​for​ el ​in​ lst1:
​if​ element ​in​ seen: of two lists ​if​ el ​in​ lst2_copy:
duplicates.add(element) res.append(el)
seen.add(element) lst2_copy.remove(el)
​return​ list(duplicates)  ​return​ res

Check if two def​ i​ s_anagram​(s1, s2): Find max l = [​4​, ​3​, ​6​, 3
​ ​, ​4,
​ ​888​, ​1,
​ ​-11​, ​22​, ​3]

strings are ​return​ set(s1) == set(s2) and min in print(max(l)) # ​ 888
anagrams print(is_anagram(​"elvis"​, ​"lives"​)) ​# True unsorted list print(min(l)) # ​ -11 

Remove all lst = list(range(​10​)) + list(range(​10​)) Reverse def​ ​reverse​(string):


duplicates from lst = list(set(lst)) string using ​if​ len(string)<=​1​: r
​ eturn​ string
list print(lst) recursion ​return​ reverse(string[​1​:])+string[​0​]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  print(reverse(​"hello"​)) ​# olleh

Find pairs of def​ ​find_pairs​(l, x): Compute a, b = ​0​, ​1


integers in list pairs = [] the first n n = ​10
so that their ​for​ (i, el_1) ​in​ enumerate(l): Fibonacci for​ i ​in​ range(n):
sum is equal to ​for​ (j, el_2) ​in​ enumerate(l[i+​1​:]): numbers print(b)
integer x ​if​ el_1 + el_2 == x: a, b = b, a+b
pairs.append((el_1, el_2)) # 1, 1, 2, 3, 5, 8, ...
​return​ pairs 

Check if a def​ ​is_palindrome​(phrase): Sort list with def​ ​qsort​(L):


string is a ​return​ phrase == phrase[::​-1​] Quicksort ​if​ L == []: ​return​ []
palindrome print(is_palindrome(​"anna"​)) ​# True algorithm ​return​ qsort([x ​for​ x ​in​ L[​1​:] ​if​ x< L[​0​]]) + L[​0​:1
​ ​] +
qsort([x ​for​ x ​in​ L[​1​:] ​if​ x>=L[​0​]])
lst = [​44​, ​33​, 2​ 2​, 5
​ ​, ​77​, ​55​, ​999​]
print(qsort(lst))
# [5, 22, 33, 44, 55, 77, 999] 

Use list as # as a list ... Find all def​ ​get_permutations​(w):


stack, array, l = [​3​, ​4​] permutation ​if​ len(w)<=​1​:
and queue l += [​5​, ​6​] ​# l = [3, 4, 5, 6] s of string ​return​ set(w)
smaller = get_permutations(w[​1: ​ ])
# ... as a stack ... perms = set()
l.append(​10​) ​# l = [4, 5, 6, 10] ​for​ x ​in​ smaller:
l.pop() ​# l = [4, 5, 6] ​for​ pos ​in​ range(​0,
​ len(x)+​1​):
perm = x[:pos] + w[​0​] + x[pos:]
# ... and as a queue perms.add(perm)
l.insert(​0​, ​5​) ​# l = [5, 4, 5, 6] ​return​ perms
l.pop() ​# l = [5, 4, 5]  print(get_permutations(​"nan"​))
# {'nna', 'ann', 'nan'}

You might also like