Python Reference
Essential Python commands, functions, and concepts for beginners and developers.
>Variables
Variables
Store information.
name = "Sam"type()
Checks data type.
type(name)int()
Converts to integer.
int("5")float()
Converts to decimal.
float("5.2")str()
Converts to string.
str(100)>Output & Input
print()
Displays output.
print("Hello")input()
Gets user input.
name = input()f-strings
Insert variables into text.
f"Hello {name}">Math
+
Add numbers.
5 + 2-
Subtract numbers.
10 - 3*
Multiply numbers.
4 * 5/
Divide numbers.
20 / 4//
Floor division.
10 // 3%
Remainder operator.
10 % 3**
Power operator.
2 ** 3round()
Rounds number.
round(4.7)abs()
Absolute value.
abs(-5)>Strings
len()
String length.
len("Hello").upper()
Uppercase text.
"hello".upper().lower()
Lowercase text.
"HELLO".lower().replace()
Replace text.
"Hi".replace("H","B").split()
Splits string.
"a,b".split(",").strip()
Removes spaces.
" hi ".strip()>Conditions
if
Runs code if true.
if age > 18:elif
Another condition.
elif age > 10:else
Alternative code.
else:==
Equal comparison.
5 == 5>
Greater than.
10 > 5<
Less than.
2 < 5and
Both conditions true.
x > 1 and y > 1or
One condition true.
x > 1 or y > 1not
Reverses condition.
not True>Loops
for
Repeats code.
for x in range(5):while
Loops while true.
while x < 5:range()
Creates number range.
range(10)break
Stops loop.
breakcontinue
Skips loop step.
continue>Functions
def
Creates function.
def test():return
Returns value.
return totalParameters
Function inputs.
def add(a,b):lambda
Short function.
lambda x: x+1>Lists
[]
Creates list.
fruits = [].append()
Adds item.
fruits.append("Apple").remove()
Removes item.
fruits.remove("Apple").pop()
Removes last item.
fruits.pop()len()
List size.
len(fruits)sorted()
Sorts list.
sorted(numbers)>Dictionaries
{}
Creates dictionary.
user = {}Dictionary Key
Stores value.
user["name"] = "Sam".keys()
Gets keys.
user.keys().values()
Gets values.
user.values().items()
Gets keys and values.
user.items()>Files
open()
Opens file.
open("file.txt").read()
Reads file.
file.read().write()
Writes to file.
file.write("Hello")with
Safely handles files.
with open() as file:>Modules
import
Imports module.
import mathfrom
Imports part of module.
from math import sqrtmath.sqrt()
Square root.
math.sqrt(25)random.randint()
Random number.
random.randint(1,10)>Error Handling
try
Tests code for errors.
try:except
Handles errors.
except:finally
Runs after try.
finally: