Python Cheat Sheet: Mosh Hamedani
Python Cheat Sheet: Mosh Hamedani
Cheat Sheet
Mosh Hamedani
This cheat sheet includes the materials I’ve covered in my Python tutorial for
Beginners on YouTube. Both the YouTube tutorial and this cheat cover the core
language constructs but they are not complete by any means.
If you want to learn everything Python has to offer and become a Python expert,
check out my Complete Python Programming Course:
http://bit.ly/complete-python-course
About the Author
https://codewithmosh.com
https://youtube.com/user/programmingwithmosh
https://twitter.com/moshhamedani
https://facebook.com/programmingwithmosh/
Variables .................................................................................................. 5
Comments ................................................................................................. 5
Receiving Input ........................................................................................5
Strings ......................................................................................................6
Arithmetic Operations .............................................................................7
If Statements ............................................................................................8
Comparison operators ............................................................................ 8
While loops ............................................................................................... 8
For loops ...................................................................................................9
Lists ........................................................................................................... 9
Tuples ........................................................................................................9
Dictionaries.............................................................................................10
Functions .................................................................................................10
Exceptions................................................................................................ 11
Classes...................................................................................................... 11
Inheritance .............................................................................................12
Modules ................................................................................................... 12
Packages ..................................................................................................13
Python Standard Library ......................................................................13
Pypi .........................................................................................................14
Want to Become a Python Expert? ........................................................ 14
Variables
We use variables to temporarily store data in computer’s memory.
price = 10
rating = 4.9
is_published = True
Comments
We use comments to add notes to our code. Good comments explain the hows and
whys, not what the code does. That should be reflected in the code itself. Use
comments to add reminders to yourself or other developers, or also explain your
assumptions and the reasons you’ve written code in a certain way.
Receiving Input
We can receive input from the user by calling the input() function.
The input() function always returns data as a string. So, we’re converting 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 tripe quotes (“””).
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 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 = ‘Mosh’
message.replace(‘p’, ‘q’)
To check if a string contains a character (or a sequence of characters), we use the in
operator:
Arithmetic Operations
+
/ # returns a float
// # returns an int
x = x + 10
x += 10
Operator precedence:
1. parenthesis
2. exponentiation
3. multiplication / division
4. addition / subtraction
EX: Conversion of weight to Lbs and Kg
weight = input("your weight: ")
unit = input ("L(lbs) or k(kg): ")
unit_final = unit.upper()
if unit_final == 'L':
If Statements weightkg = int(weight) * 0.45
print (f'Your weight = {weightkg} kg')
if is_hot: elif unit_final == 'K':
print(“hot day”) weightkg = int(weight) / 0.45
print (f'Your weight = {weightkg} lbs')
elif is_cold: else:
print(“cold day”) print ('please enter your weight either in lbs or
Kg only')
else:
print(“beautiful day”)
Logical operators:
break
is used to end the loop
For loop is used to iterate EX:Summation of list
over items of a collection prices = [10,20,30]
total = 0 output
for i in prices: total : 60
For loops total = total + i
print(f"total : {total}")
for i in range(1, 5):
print(i)
EX:Drawing F xxxxx
numbers = [1,1,1,1,7]
for x_count in numbers: output xx
output = '' xxxxx
• range(5): generates 0, 1, 2, 3, 4 for i in range(x_count): xx
output += 'x' xx
print(output)
• range(1, 5): generates 1, 2, 3, 4
Tuples
They 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.
we use square brackets [] to make list and rounded
coordinates = (1, 2, 3) brackets ()to make a Tuples
x, y, z = coordinates
split
is a method used to generate a list
from a string.
code"This is amazing".split()
Dictionaries result ["This","is","amazing"]
We use dictionaries to store key/value pairs. it takes a space is a separator
by default
customer = {
code"this is amazing".split('s')
“name”: “John Smith”,
result['thi', ' i', ' amazing']
“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.
Functions
We use functions to break up our code into small chunks. These chunks 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 can also re-use these chunks.
def greet_user(name):
parameter
print(f”Hi {name}”)
greet_user(“John”) argument
Parameters are placeholders for the data we can pass to functions. Arguments
are the actual values we pass.
• Keyword arguments: position doesn’t matter - we prefix them with the parameter
name. 1- Usually if w use keyword argument to increase the readability of the numerical
arguments.
2- Usually if you have to write 2 arguments in the same function, the positional ar-
gument must be written before keyword argument.
EX:
greet_user("John", last_name = "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, 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 because of bad
input or programming errors. It’s our job to anticipate and handle these exceptions
to prevent our programs from cashing.
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. the first letter of the Class
has to be Uppercase
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print(“move”)
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() # inherited from Mammal
dog.bark() # defined in Dog
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 2 ways to import modules: we can import the entire module, or specific
objects in a module.
# importing the entire converters module
import converters
converters.kg_to_lbs(5)
Packages
A package is a directory with __init__.py in it. It can contain one or more
modules.
Random Module
import random
random.random() # returns a float between 0 to 1
random.randint(1, 6) # returns an int between 1 to 6
members = [‘John’, ‘Bob’, ‘Mary’]
leader = random.choice(members) # randomly picks an item
Pypi
Python Package Index (pypi.org) is a directory of Python packages published by
Python developers around the world. We use pip to install or uninstall these
packages.
• 12 hours of HD video
The price for this course is $149 but the first 200 people who have downloaded this
cheat sheet can get it for $14.99 using the coupon code CHEATSHEET:
http://bit.ly/complete-python-course