Skip to content

Instantly share code, notes, and snippets.

@IoTeacher
Forked from EVanGorkom/Python Cheatsheet.md
Created February 7, 2024 23:21
Show Gist options
  • Save IoTeacher/d68534c6cd5f4fe95e426fb37c694be4 to your computer and use it in GitHub Desktop.
Save IoTeacher/d68534c6cd5f4fe95e426fb37c694be4 to your computer and use it in GitHub Desktop.

Mosh Python Cheatsheet

Disclaimer: I did not create this cheatsheet or the ideas within. All credit goes to Mosh Hamedani and his Python Cheatsheet that can be acquired through an email link, by visiting his YouTube tutorials or visiting his tutorial pages. This is a Markdown version of the original pdf that I retyped with a few typo corrections and notes for my own understanding.

Variables

We use variables to temporarily store data in computer's memory.

price = 10 # Integer
rating = 4.9 # Float
course_name = 'Python' # String
is_published = True # Boolean

Receiving Input

We can receive input from the user by calling the input() function.

birth_year = int(input('Birth year: '))

The input() function always returns data as a string. So, we convert the result into an integer by calling the built-in int() function.

Strings

We can define strings using single or double quotes. To define a multi-line string, we surround our string with triple quotes (""").

We can get individual characters in a string using square brackets[].

course = 'Python'
course[0] # returns 'P'
course[1] # returns 'y'
course[-1] # returns 'n'
course[-2] # returns 'o'

We can slice a string using the index values.

course = 'Python'
course[1:5]

The above expression returns all the characters starting from the index position of 1 to 5 (but excluding 5). The result will be ytho If we were to leave our the starting index, 0 will be the assumed value. If we leave out the end index, the length of the string will be assumed.

We can use formatted strings to dynamically insert values into our strings:

name = 'Ethan'
message = f'Hi, my name is {name}'

message.upper()  # to convert to uppercase
message.lower()  # to convert to lowercase
message.title()  # to capitalize the first letter of every word
message.find('p')  # returns the index of the first occurence of 'p' (or -1 if not found)
message.replace('p', 'q')  # replaces the first value with the second value

To check if a string contains a character (or a sequence of characters), we use the in operator:

contains = 'Python' in course

Arithmetic Operations

+   # addition
-   # subtraction
*   # multiplication 
/   # division returns a float
//  # division returns a int
%   # returns the remainder of division
**  # exponentiation   - x ** y = x to the power of y

Augmented assignment operator:

x = x + 10
# These do the same thing
x += 10

Operator Precedence:

  1. parenthesis
  2. exponentiation
  3. multiplication / division
  4. addition / subtraction

If Statements

if is_hot:
	print("Hot Day")
elif is_cold:
	print("Cold Day")
else:
	print("Beautiful Day")
Logical operators:
if has_high_income and has_good_credit:
	# code here

if has_high_income or has_good_credit:
	# code here

is_day = True
is_night = not is_day
Comparison operators:
a > b
a >= b
a < b
a <= b
a == b
a != b
# All comparison operators are the same as in Ruby

Loops

While Loops
i = 1

while i < 5:
	print(i)
	i += 1
# While the value for 'i' is less than 5, we will print the value and then add one to it, and reassign the value.
For Loops
i = 1

for i in range(1, 5):
	print(i)
# For the value of 'i' take the range of 1 - 5 and print all of the numbers, starting from 'i's value and stopping at 5.
  • range(5): generates 0, 1, 2, 3, 4
  • range(1, 5): generates 1, 2, 3, 4
  • range(1, 5, 2): generates 1, 3 (Counting by 2)

Lists (Arrays)

numbers = [1, 2, 3, 4, 5] 
numbers[0]  # returns the first item 
numbers[1]  # returns the second item 
numbers[-1] # returns the first item from the end 
numbers[-2] # returns the second item from the end 

numbers.append(6)     # adds 6 to the end 
numbers.insert(0, 6)  # adds 6 at index position of 0 
numbers.remove(6)     # removes 6 numbers.pop() # removes the last item 
numbers.clear()       # removes all the items 
numbers.index(8)      # returns the index of first occurrence of 8 
numbers.sort()        # sorts the list 
numbers.reverse()     # reverses the list 
numbers.copy()        # returns a copy of the list

Tuples

The are like read-only lists. We use them to store a list of items. But once we define a tuple, we cannot add or remove items or change the existing items. coordinates = (1, 2, 3)

We can unpack a list or a tuple into separate variables: x, y, z = coordinates

Dictionaries (Hashes)

We use dictionaries to store key/value pairs.

customer = {
	"name": "John Smith",
	"age": 30,
	"is_verified": True
}

We can use strings or numbers to define keys. They should be unique. We can use any types for the values.

customer["name"]            # returns "John Smith"
customer["type"]            # throws an error at the moment
customer.get("type", "silver") # returns "silver"
customer["name"] = "new name" # reassigns the value of the name to "new name"

Functions

We use functions to break up our code into small chunks. These chucks are easier to read, understand, and maintain. If there are bugs, it's easier to find bugs in a small chunk than the entire program. We also re-use these chunks.

def greet_user(name):
	print(f"Hi {name})

greet_user("John")  # Returns "Hi John"

Parameters - are placeholders for the data we can pass into functions. Arguments - are the actual values we pass in.

We have two types of arguments:

  • Positional arguments: their position (order) matters
  • Keyword arguments: position doesn't matter - we prefix them with the parameter name.
# Two positional arguments
greet_user("John", "Smith")

# Keyword arguments
calculate_total(order=50, shipping=5, tax=0.1)

Our functions can return values. If we don't use the return statement, then by default None is returned. None is an object that represents the absence of a value.

def square(number):
	return number * number

result = square(2)
print(result)    # prints 4

Exceptions

Exceptions are errors that crash our programs. They often happen becasue of bad input or programming erros. It's our job to anticipate and handle these exceptions to prevent our programs from crashing.

try:
	age = int(input('Age: '))
	income = 20000
	risk = income / age
	print(age)
except ValueError:
	print('Not a valid number')
except ZeroDivisionError:
	print('Age cannot be 0')

Classes

We use classes to define new types.

class Point:
	def __init__(self, x, y):
		self.x = x
		self.y = y

	def move(self):
		print("move")
  • When a function is a part of a class, we refer to it as a method.
  • __int__ is a special method called constructor. It gets called at the time of creating new objects. We use it to initialize our objects.

Classes define templates or blueprints for creating objects. An object is an instance of a class. Every time we create a new instance, that instance follows the structure we define using the class.

point1 = Point(10, 5)
point2 = Point(2, 4)

Inheritance

Inheritance is a technique to remove code duplication. We can create a base class to define the common methods and then have other classes inherit these methods.

class Mammal:
	def walk(self):
		print("walk")

class Dog(Mammal):
	def bark(self):
		print("bark")

dog = Dog()
dog.walk()   # this method is inherited from the 'Mammal' base class
dog.bark()   # this method is defined in the 'Dog' class

Modules

A module is a file with some Python code. We use modules to break up our program into multiple files. This way, our code will be better organized. We won't have one gigantic file with a million lines of code in it!

There are two ways to import modules:

  • We can import the entire module
  • We can import specific objects in a module
# Importing the entire converters module
import converters
converters.kg_to_lbs(5)

# Importing one function in the converters module
from converters import kg_to_lbs
kg_to_lbs(5)

Packages

A package is a directory with __init__.py in it. It can contain one or more modules.

# Importing the entire sales module
from ecommerce import sales
sales.calc_shipping()

# Importing one function in the sales module
from ecommerce.sales import calc_shipping
calc_shipping()

Python Standard Library

Python comes with a huge library of modules for performing common tasks such as sending emails, working with date/time, generating random values, etc.

Random Module
import random

random.random()       # returns a float between 0 to 1
random.randint(1, 6)  # returns an integer between 1 to 6

members = ['John', 'Bob', 'Mary']
leader = random.choice(members)  # randomly picks an item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment