Python Cheat Sheet for Begginers
Python Cheat Sheet for Begginers
com/in/anamika-k-s-b17955286
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.
1
linkedin.com/in/anamika-k-s-b17955286
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.find(‘p’) # returns the index of the first occurrence of p (or -1 if not found)
2
linkedin.com/in/anamika-k-s-b17955286
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
3
linkedin.com/in/anamika-k-s-b17955286
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:
......
if has_high_income or has_good_credit:
.....
is_day = True
Comparison operators
a>b
a<b
a <= b
a == b (equals)
a != b (not equals)
4
linkedin.com/in/anamika-k-s-b17955286
While loops
i=1
while i < 5:
print(i)
i += 1
For loops
for i in range(1, 5):
print(i)
• range(5): generates 0, 1, 2, 3, 4
Lists
numbers = [1, 2, 3, 4, 5]
numbers.remove(6) # removes 6
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 = {
“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.
6
linkedin.com/in/anamika-k-s-b17955286
def greet_user(name):
print(f”Hi {name}”)
greet_user(“John”)
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.
greet_user(“John”, “Smith”)
# Keyword arguments
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):
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:
income = 20000
7
linkedin.com/in/anamika-k-s-b17955286
print(age)
except ValueError:
except ZeroDivisionError:
Classes
We use classes to define new types.
class Point:
self.x = x
self.y = y
def move(self):
print(“move”)
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)
__init__ is a special method called constructor. It gets called at the time of creating new
objects. We use it to initialize our objects.
8
linkedin.com/in/anamika-k-s-b17955286
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()
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.
import converters
converters.kg_to_lbs(5)
kg_to_lbs(5)
9
linkedin.com/in/anamika-k-s-b17955286
Packages
A package is a directory with __init__.py in it. It can contain one or more modules.
sales.calc_shipping()
calc_shipping()
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.
uninstall openpyxl
10