Python Cheat Sheet
Python Cheat Sheet
rank = 10
eggs = 12
people = 3
temperature = 10.2
rainfall = 5.98
elevation = 1031.88
Strings represent text:
Lists represent arrays of values that may change during the course of the
program:
phone_numbers.keys()
phone_numbers.values()
Tuples represent arrays of values that are not to be changed during the course
of the program:
dir(str)
dir(list)
dir(dict)
dir(__builtins__)
help(str)
help(str.replace)
help(dict.values)
def cube_volume(a):
return a * a * a
Write if-else conditionals:
if "hello" in message:
print("hi")
else:
print("I don't understand")
Write if-elif-else conditionals:
if "hello" in message:
print("hi")
elif "hi" in message:
print("hi")
elif "hey" in message:
print("hi")
else:
print("I don't understand")
Use the and operator to check if both conditions are True at the same time:
x = 1
y = 1
if x == 1 and y==1:
print("Yes")
x = 1
y = 2
if x == 1 or y==2:
print("Yes")
else:
print("No")
isinstance("abc", str)
isinstance([1, 2, 3], list)
or directly:
type("abc") == str
type([1, 2, 3]) == lst
The input function halts the execution of the program and gets text input from
the user:
The input function converts any input to a string, but you can convert it back to
int or float:
name = "Sim"
experience_years = 1.5
print("Hi {}, you have {} years of experience".format(name, experience_years))
Python Loops
A for-loop is useful to repeatedly execute a block of code.
Output:
A B C
As you can see, the for-loop repeatedly converted all the items of 'abc' to
uppercase.
The name after for (e.g. letter ) is just a variable name
Output:
John Smith Marry Simpsons
Output:
+37682929928 +423998200919
Output:
The loop above will print out the string inside print() over and over again until
the 20th of August, 2090.
List Comprehensions
A list comprehension is an expression that creates a list by iterating over
another container.
A basic list comprehension:
More on Functions
Functions can have more than one parameter:
print(converter(10))
Output: 3.0480370641306997
Arguments can be passed as non-keyword (positional) arguments (e.g. a )
or keyword arguments (e.g. b=2 and c=10 ):
Output: 1001
def find_winner(**kwargs):
return max(kwargs, key = kwargs.get)
Output: Sim
Python Modules
Builtin objects are all objects that are written inside the Python
interpreter in C language.
import time
time.sleep(5)
import sys
sys.builtin_module_names
Windows:
pip install pandas or use python -m pip install pandas if that doesn't
work.