Python Mosh 1-6 Hrs
Python Mosh 1-6 Hrs
Cheat Sheet
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.
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
Lists
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
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.
coordinates = (1, 2, 3)
x, y, z = coordinates
Dictionaries
We use dictionaries to store key/value pairs.
customer = {
“name”: “John Smith”,
“age”: 30,
“is_verified”: True
}
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.
class Point:
def init (self, x, y):
self.x = x
self.y = y
def move(self):
print(“move”)
point1 = Point(10, 5)
point2 = Point(2, 4)
Random Module
import random
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.
pip install openpyxl pip uninstall openpyxl