Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Datateach - Ai Python Cheat Sheet

Uploaded by

Kunal Kharat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Datateach - Ai Python Cheat Sheet

Uploaded by

Kunal Kharat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

PYTHON CHEAT SHEET

BASICS

Print
Prints a string into the console.
print("Hello World")

Input
Prints a string into the console,
and asks the user for a string input. input("What's your name")

Comments
Adding a # symbol in font of text
lets you make comments on a line of code. #This is a comment
The computer will ignore your comments. print("This is code")

Variables
A variable give a name to a piece of data.
Like a box with a label, it tells you what's my_name = "Angela"
inside the box. my_age = 12

The += Operator
This is a convient way of saying: "take the
previous value and add to it. my_age = 12
my_age += 4
#my_age is now 16

www.datateach.ai
PYTHON CHEAT SHEET

DATA TYPES

Integers
Integers are whole numbers.
my_number = 354

Floating Point Numbers


Floats are numbers with decimal places.
When you do a calculation that results in my_float = 3.14159
a fraction e.g. 4 ÷ 3 the result will always be
a floating point number.

Strings
A string is just a string of characters.
It should be surrounded by double quotes. my_string = "Hello"

String Concatenation
You can add strings to string to create
a new string. This is called concatenation. "Hello" + "Angela"
It results in a new string. #becomes "HelloAngela"

Escaping a String
Because the double quote is special, it
denotes a string, if you want to use it in speech = "She said: \"Hi\""
a string, you need to escape it with a "\" print(speech)
#prints: She said: "Hi"

www.datateach.ai
PYTHON CHEAT SHEET

F-Strings
You can insert a variable into a string
using f-strings. days = 365
The syntax is simple, just insert the variable print(f"There are {days}
in-between a set of curly braces {}.
in a year")

Converting Data Types


You can convert a variable from 1 data
type to another. n = 354
Converting to float: new_n = float(n)
float()
print(new_n) #result 354.0
Converting to int:
int()
Converting to string:
str()

Checking Data Types


You can use the type() function
to check what is the data type of a n = 3.14159
particular variable. type(n) #result float

www.datateach.ai
PYTHON CHEAT SHEET

MATHS

Arithmetic Operators
You can do mathematical calculations with 3+2 #Add 4-1
Python as long as you know the right #Subtract 2*3
operators.
#Multiply 5/2
#Divide 5**2
#Exponent

The += Operator
This is a convenient way to modify a variable.
It takes the existing value in a variable my_number = 4
and adds to it. my_number += 2
You can also use any of the other
#result is 6
mathematical operators e.g. -= or *=

The Modulo Operator


Often you'll want to know what is the
remainder after a division. 5 % 2
e.g. 4 ÷ 2 = 2 with no remainder #result is 1
but 5 ÷ 2 = 2 with 1 remainder
The modulo does not give you the result
of the division, just the remainder.
It can be really helpful in certain situations,
e.g. figuring out if a number is odd or even.

www.datateach.ai
PYTHON CHEAT SHEET

ERRORS

Syntax Error
Syntax errors happen when your code print(12 + 4))
does not make any sense to the computer. File "<stdin>", line 1
This can happen because you've misspelt
print(12 + 4))
something or there's too many brackets or
a missing comma. ^
SyntaxError: unmatched ')'

Name Error
This happens when there is a variable
with a name that the computer my_number = 4 my_Number + 2
does not recognise. It's usually because Traceback (most recent call
you've misspelt the name of a variable last): File "<stdin>", line 1,
you created earlier. NameError: name 'my_Number' is
Note: variable names are case sensitive!
not defined

Zero Division Error


This happens when you try to divide by zero,
This is something that is mathematically 5 % 0
impossible so Python will also complain. Traceback (most recent call
last): File "<stdin>", line 1,
ZeroDivisionError: integer
division or modulo by zero

www.datateach.ai
PYTHON CHEAT SHEET

FUNCTIONS

Creating Functions
This is the basic syntax for a function in def my_function():
Python. It allows you to give a set of print("Hello")
instructions a name, so you can trigger it
multiple times without having to re-write or name = input("Your name:")
copy-paste it. The contents of the function print("Hello")
must be indented to signal that it's inside.

Calling Functions
You activate the function by calling it. my_function()
This is simply done by writing the name of my_function() #The
the function followed by a set of round
brackets. This allows you to determine function my_function
when to trigger the function and how #will run twice.
many times.

Functions with Inputs


In addition to simple functions, you can
give the function an input, this way, each time def add(n1, n2):
the function can do something different print(n1 + n2)
depending on the input. It makes your
function more useful and re-usable.
add(2, 3)

www.datateach.ai
PYTHON CHEAT SHEET

Functions with Outputs


In addition to inputs, a function can also have
an output. The output value is proceeded by def add(n1, n2):
the keyword "return". return n1 + n2
This allows you to store the result from a
function.
result = add(2, 3)

Variable Scope
Variables created inside a function are n = 2
destroyed once the function has executed. def my_function():
The location (line of code) that you use
a variable will determine its value. n = 3
Here n is 2 but inside my_function() n is 3. print(n)
So printing n inside and outside the function
will determine its value.
print(n) #Prints 2
my_function() #Prints 3

Keyword Arguments
When calling a function, you can provide def divide(n1, n2):
a keyword argument or simply just the result = n1 / n2
value.
Using a keyword argument means that #Option 1:
you don't have to follow any order divide(10, 5)
when providing the inputs. #Option 2:
divide(n2=5, n1=10)

www.datateach.ai
PYTHON CHEAT SHEET

CONDITIONALS

If
This is the basic syntax to test if a condition n = 5
is true. If so, the indented code will be if n > 2:
executed, if not it will be skipped.
print("Larger than 2")

Else
This is a way to specify some code that will be age = 18
executed if a condition is false. if age > 16:
print("Can drive")
else:
print("Don't drive")

Elif
In addition to the initial If statement
condition, you can add extra conditions to weather = "sunny"
test if the first condition is false. if weather == "rain":
Once an elif condition is true, the rest of
print("bring umbrella")
the elif conditions are no longer checked
and are skipped. elif weather == "sunny":
print("bring sunglasses")
elif weather == "snow":
print("bring gloves")

www.datateach.ai
PYTHON CHEAT SHEET

and
This expects both conditions either side s = 58
of the and to be true. if s < 60 and s > 50:
print("Your grade is C")

or
This expects either of the conditions either age = 12
side of the or to be true. Basically, both if age < 16 or age > 200:
conditions cannot be false.
print("Can't drive")

not
This will flip the original result of the
condition. e.g. if it was true then it's now if not 3 > 1:
false. print("something")
#Will not be printed.

comparison operators
These mathematical comparison operators
allow you to refine your conditional checks. > Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
== Is equal to
!= Is not equal to

www.datateach.ai
PYTHON CHEAT SHEET

LOOPS

While Loop
This is a loop that will keep repeating itself n = 1
until the while condition becomes false. while n < 100:
n += 1

For Loop
For loops give you more control than all_fruits = ["apple",
while loops. You can loop through anything "banana", "orange"]
that is iterable. e.g. a range, a list, a dictionary
or tuple. for fruit in all_fruits:
print(fruit)

_ in a For Loop
If the value your for loop is iterating through,
e.g. the number in the range, or the item in for _ in range(100):
the list is not needed, you can replace it with #Do something 100 times.
an underscore.

break
This keyword allows you to break free of the
loop. You can use it in a for or while loop. scores = [34, 67, 99, 105]
for s in scores:
if s > 100:
print("Invalid")
break
print(s)
www.datateach.ai
PYTHON CHEAT SHEET

continue n = 0
This keyword allows you to skip this iteration
while n < 100:
of the loop and go to the next. The loop will
still continue, but it will start from the top. n += 1
if n % 2 == 0:
continue
print(n)
#Prints all the odd numbers

Infinite Loops
Sometimes, the condition you are checking while 5 > 1:
to see if the loop should continue never print("I'm a survivor")
becomes false. In this case, the loop will
continue for eternity (or until your computer
stops it). This is more common with while
loops.

www.datateach.ai
PYTHON CHEAT SHEET

LIST METHODS

Adding Lists Together


You can extend a list with another list by list1 = [1, 2, 3] list2
using the extend keyword, or the + symbol. = [9, 8, 7] new_list =
list1 + list2 list1 +=
list2

Adding an Item to a List


If you just want to add a single item to a all_fruits = ["apple",
list, you need to use the .append() method. "banana", "orange"]
all_fruits.append("pear")

List Index
To get hold of a particular item from a
list you can use its index number. letters = ["a", "b", "c"]
This number can also be negative, if you letters[0]
want to start counting from the end of the
#Result:"a"
list.
letters[-1]
#Result: "c"
List Slicing
Using the list index and the colon symbol
you can slice up a list to get only the #list[start:end]
portion you want. letters = ["a","b","c","d"]
Start is included, but end is not.
letters[1:3]
#Result: ["b", "c"]

www.datateach.ai
PYTHON CHEAT SHEET

BUILT IN FUNCTIONS

Range
Often you will want to generate a range # range(start, end, step)
of numbers. You can specify the start, end for i in range(6, 0, -2):
and step.
Start is included, but end is excluded: print(i)
start <= range < end
# result: 6, 4, 2
# 0 is not included.

Randomisation
The random functions come from the import random
random module which needs to be # randint(start, end)
imported.
In this case, the start and end are both n = random.randint(2, 5)
included #n can be 2, 3, 4 or 5.
start <= randint <= end

Round
This does a mathematical round.
So 3.1 becomes 3, 4.5 becomes 5 round(4.6)
and 5.8 becomes 6. # result 5

abs
This returns the absolute value.
Basically removing any -ve signs. abs(-4.6)
# result 4.6

www.datateach.ai
PYTHON CHEAT SHEET

MODULES

Importing
Some modules are pre-installed with python import random
e.g. random/datetime n = random.randint(3, 10)
Other modules need to be installed from
pypi.org

Aliasing
You can use the as keyword to give import random as r
your module a different name. n = r.randint(1, 5)

Importing from modules


You can import a specific thing from a from random import randint
module. e.g. a function/class/constant You n = randint(1, 5)
do this with the from keyword. It can save
you from having to type the same thing
many times.

Importing Everything
You can use the wildcard (*) to import
everything from a module. Beware, this from random import *
usually reduces code readability. list = [1, 2, 3]
choice(list)
# More readable/understood
#random.choice(list)

www.datateach.ai
PYTHON CHEAT SHEET

CLASSES & OBJECTS

Creating a Python Class


You create a class using the class keyword. class MyClass:
Note, class names in Python are PascalCased. #define class
So to create an empty class

Creating an Object from a Class


You can create a new instance of an object class Car:
by using the class name + () pass

my_toyota = Car()

Class Methods
You can create a function that belongs class Car:
to a class, this is known as a method. def drive(self):
print("move")
my_honda = Car()
my_honda.drive()

Class Variables
You can create a varaiable in a class. class Car:
The value of the variable will be available colour = "black"
to all objects created from the class.
car1 = Car()
print(car1.colour) #black

www.datateach.ai
PYTHON CHEAT SHEET

The __init__ method


The init method is called every time a new class Car:
object is created from the class. def __init__(self):
print("Building car")
my_toyota = Car()
#You will see "building car"
#printed.

Class Properties
You can create a variable in the init() of
a class so that all objects created from the class Car:
class has access to that variable. def __init__(self, name):
self.name = "Jimmy"

Class Inheritance
When you create a new class, you can class Animal:
inherit the methods and properties def breathe(self):
of another class.
print("breathing")
class Fish(Animal):
def breathe(self):
super().breathe()
print("underwater")
nemo = Fish()
nemo.breathe()
#Result:
#breathing
#underwater
www.datateach.ai

You might also like