Show Menu
Cheatography

Python Cheat Sheet (DRAFT) by

Python language Cheat Sheet.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Print statement

print(text) # prints some text 
to the console.
- Example :
print(­'Hello World')
# prints

Hello World

Comments

# This is a comment.

Variables

variable_name = value
- Example :
age = 21 
gpa = 3.2
name = "Jack"
online = True
 

Condit­ionals

if condition:

   …
else:

   …
if condition:

   …
elif condition:

   …
else:

   …
- Example :
num = 4 

if num % 2 == 0:
   print('Even')
else:
   print('Odd')

Loops

while condition:

   …
for x in range(start, stop):

 ­ ­ …
- Examples :
for i in range(1, 5):

   
print(i, end=' ') 
  # prints 1 2 3 4


i = 0

while i < 5:

   
print(i)

   
i = i + 1
 

Functi­ons­/Me­thods

def function(parameters)
:
   
return
- Example :
a = int(input ('Enter a: '))
b = int(input ('Enter b: '))

def multiply(a, b):
   return a * b

print(multiply(a, b)) # print
the result.

Exception Handling

try:

 ­ ­ 
# Try some code

except exception:

 ­ ­ 
# Handle an exception

finally:

 ­ ­ 
# Do some clean up
- Example :
try:

 ­ ­ 
num = 1 / 0

except
ZeroDi­vis­ion­Error
:

 ­ ­ 
print('You cannot divide by zero!')

Lists

list_name = [value, value, value]
- Example :

fruits = ['Apple', 'Orange', 'Banana']

length =
len
(
fruits
)
# get the length of the list


print
(
fruits[0]
)
# prints Apple

print
(
fruits[1]
)
# prints Orange

print
(
fruits[2]
)
# prints Banana

print
(
length
)
# prints 3

Operators

Arithmetic operators :
+
,
-
,
*
,
/
,
%
,
**
Comparison operators :
==
,
!=
,
<
,
>
,
<=
,
>=
Logical operators :
and, or, not
Assignment operators :
=
,
+=
,
-=
,
*=
,
/=
,
%=