Python: Ultimate Cheat Sheet

๐Ÿ Python Basics

Data Structures

Data types

NameTypeDescriptionExample
IntegerintWhole numbers-3, 25, 300
Floating pointfloatNumber with a decimal point-2.3, 4.6, 100.0
StringstrOrdered sequence of characters"hello world!"
ListlistOrdered sequence of objects[20, "hello", 4.6]
DictionarydictUnordered Key:Value pairs{"name":"Frankie", "surname":"Smith"}
TupletupOrdered immutable sequence of objects[20, "hello", 4.6]
SetsetUnordered collection of unique objects{"a","b","c"}
BooleanboolBinary valueTrue or False

Strings

MethodDescriptionExampleResult
capitalize()Convert first character to upper case
count()Return number of times a specified value occurs in a string
encode()Returns an encoded version of the string
format()Format specified values in a string
index()Return the index position of a specified value
join()Convert the elements of an iterable into a string
lower()Convert string into lower case
lstrip()Trim the left portion of the string
replace()Replace a specified value with a specified value
rindex()Return the last position of a specified value
rsplit()Split the string with a specified seperator and return a list
rsplit()Trim the right portion of a string
splitlines()Split the string at line breaks and return a list
strip()Trim the string
title()Convert the first character of each word to upper case
upper()Convert string into upper case

Lists

MethodDescriptionExampleResult
append()
clear()
copy()
count()
extend()
index()
insert()
pop()
remove()
reverse()
sort()

Dictionaries

MethodDescriptionExampleResult
clear()
copy()
fromkeys()
get()
items()
keys()
pop()
popitem()
setdefault()
update()
values()

Tuples

MethodDescriptionExampleResult
count()Return number of times a specified value occurs
index()Return index position of a specified value

Sets

MethodDescriptionExampleResult
add()
clear()
copy()
difference()
difference_update()
discard()
intersection()
intersection_update()
isdisjoint()
issubset()
issuperset()
pop()
remove()
remove()
symmetric_difference()
symmetric_difference_update()
union()
update()

Date and time

ValueDescriptionExample
%aAbbreviated weekdaySun
%AWeekdaySunday
%bAbbreviated month nameJan
%BMonth nameJanuary
%cDate and time
%dDay of month01 to 31
%H24 hour00 to 23
%I12 hour01 to 12
%jDay of year001 to 366
%mMonth number01 to 12
%MMinute00 to 59
%pTime periodAM or PM
%SSecond00 to 61
%UWeek number00 to 53
%wWeekday0 to 6
%WWeek number00 to 53
%xDate
%XTime
%yYear without century00 to 99
%YYear2021
%ZTime zoneGMT

Operators

Arithmetic operators

NameOperatorDescriptionExampleResult
Addition+Add a and b5+27
Subtraction-Subtract b from a5-23
Multiplication*Multiply a by b5*210
Division/Divide a by b5/22.5
Modulus%Remainder of a divided by b5%21
Exponent**Raise a to the power of b5**225
Integer division//Divide a by b and only return integer5//22

Comparison operators

NameOperatorDescriptionExampleResult
Equal ==True if a equals b5==2False
Not equal!=True if a is not equal to b5!=2True
Less than<True if a is less than b5<2False
Less than or equal<=True if a is less than or equal to b5<=2False
Greater than>True if a is greater than b5>2True
Greater than or equal>=True if a is greater than or equal to b5>=2True

Logical operators

OperatorDescriptionExample
andReturn True if both statements are truex>2 and x<5
orReturn True if at least one statement is truex==2 or x>5
notReturn False if the statement is truenot(x>2 and x<5)

Conditional Statements

StatementDescription
ifExecute code if condition is true
elifExecute code if previous condition was false
elseExecute code if all of the previous conditions were false
passSkip executing code of condition is true

Conditional statement

if a > b:
    print("a is greater than b")
elif a == b:
    print("a and b are equal")
else:
    print("b is greater than a")

Nested if statement

if x > 5:
    print("Greater than five")
    if x > 10:
        print("and greater than ten")
    else:
        print("and less than ten")

Pass statement

if x > 5:
    pass

Loops

For loop

For loop

list = [1,2,3,4,5]

for element in list:
    print(element)

# Output: 1,2,3,4,5

Break statement

list = [1,2,3,4,5]

for element in list:
    if element == 3:
        print("Found!")
        break
    print(element)

# Output: 1,2,Found!

Continue statement

list = [1,2,3,4,5]

for element in list:
    if element == 3:
        print("Found!")
        continue
    print(element)

# Output: 1,2,Found!,4,5

Else statement

list = [1,2,3,4,5]

for element in list:
    print(element)
else:
    print("Finally finished!")

# Output: 1,2,3,4,5,Finally finished!

Range loop

Range loop

for i in range(10):
    print(i)

# Output: 0,1,2,3,4,5,6,7,8,9

Range loop with indexing

for i in range(1,11):
    print(i)

# Output: 1,2,3,4,5,6,7,8,9,10

Nested loop

Nested loop

list = [1,2,3]

for element in list:
    for letter in "abc":
        print(element, letter)

# Output: 1a,1b,1c,2a,2b,2c,3a,3b,3c

While loop

While loop

x = 0

while x < 10:
    print(x)
    x += 1

# Output: 0,1,2,3,4,5,6,7,8,9,10

Infinite loop with break statement

x = 0

while True:
    if x == 5:
        break
    print(x)
    x += 1

# Output: 0,1,2,3,4

Functions

  • Function – a collection of instructions that can be initiated by calling a defined function.
  • Parameter – the input that you define for the function.
  • Argument – value for a given parameter.
  • Key word argument – used to make code more readable.
  • *args – used for unknown number of arguments. The function will receive a tuple of arguments.

Function

Create a function

def function1():
    print("Hi there.")
    print("Welcome aboard.")

function1()

# Output: Hi there. Welcome aboard.

Return function

def function2(x):
    return 5*x

print(function2(3))

# Output: 15

Multiple argument function

def function3(x, y):
    return x+y

print(function3(2,7))

# Output: 9

Function example

def function4(x):
    print(x)
    print("still in this function.")
    return 3*x

print(function4(4))

# Output: 4 still in this function. 12

Function variables

def greet(first_name, last_name):
    print(f"Hi {first_name} {last_name}.")
    print("Welcome aboard.")

greet("Frankie", "Smith")

# Output: Hi Frankie Smith. Welcome aboard.

BMI calculator example

Input values

name1 = "Frankie"
height1 = 2
weight1 = 90

name2 = "Kelvin"
height2 = 2.5
weight2 = 160

BMI function


def bmi_calculator(name, height, weight):
    bmi = weight / (height **2)
    print("bmi: ")
    print(bmi)
    if bmi < 25:
        return name + " is not overweight"
    else:
        return name + " is overweight"

Run function

result1 = bmi_calculator(name1, height1, weight1)
result2 = bmi_calculator(name2, height2, weight2)

# Output:
# bmi: 22.5
# bmi: 25.6

print(result1)
print(result2)

# Output:
# Frankie is not overweight
# Kelvin is overweight

Key-word argument

Key-word argument

def function3(x, y):
    return x+y

print(function3(x=2, y=7))

# Output: 9

Arbitrary aruments: *args

*args



# Output: 

Arbitrary key-word aruments: **kwargs

**kwargs



# Output: 

Object Oriented Programming

๐Ÿ”ข Numpy

๐Ÿผ Pandas

โฌ› PyCharm

Shortcuts

Editing

Running

Debugging

Navigation

Refactoring

1 thought on “๐Ÿ Python: Ultimate Cheat Sheet”

  1. I’m very happy to uncover this site. I need to to thank you for ones time due to this fantastic read!! I definitely savored every bit of it and i also have you saved to fav to check out new information in your website.

Leave a Comment

Your email address will not be published. Required fields are marked *