100% found this document useful (2 votes)
111 views16 pages

Python Basics Cheat Sheet

The document provides a cheat sheet overview of key Python concepts and features. It covers basics like printing, variables, data types, mathematical operators, functions, and conditionals. The cheat sheet aims to be a concise yet comprehensive reference for learning Python fundamentals in a complete professional Python bootcamp over 100 days of code.

Uploaded by

Jignesh Bhalsod
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
111 views16 pages

Python Basics Cheat Sheet

The document provides a cheat sheet overview of key Python concepts and features. It covers basics like printing, variables, data types, mathematical operators, functions, and conditionals. The cheat sheet aims to be a concise yet comprehensive reference for learning Python fundamentals in a complete professional Python bootcamp over 100 days of code.

Uploaded by

Jignesh Bhalsod
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Basics
  • F-Strings and Converting Data Types
  • Data Types
  • Maths and Operators
  • Errors
  • Functions
  • Advanced Function Concepts
  • Conditionals
  • Logical Operations
  • Loops
  • List Methods
  • Built-in Functions
  • Modules
  • Classes & Objects
  • Class Methods and Inheritance

PYTHON CHEAT SHEET

100 DAYS OF CODE


COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

BASICS

Print

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

Input

Prints a string into the console, input("What's your name")


and asks the user for a string input.

Comments

Adding a # symbol in font of text #This is a comment


lets you make comments on a line of code. print("This is code")
The computer will ignore your comments.

Variables

A variable give a name to a piece of data. my_name = "Angela"


Like a box with a label, it tells you what's my_age = 12
inside the box.

The += Operator

This is a convient way of saying: "take the my_age = 12


previous value and add to it. my_age += 4
#my_age is now 16

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP
DATA TYPES

Integers

Integers are whole numbers. my_number = 354

Floating Point Numbers

Floats are numbers with decimal places. my_float = 3.14159


When you do a calculation that results in
a fraction e.g. 4 ÷ 3 the result will always be
a floating point number.

Strings

A string is just a string of characters. my_string = "Hello"


It should be surrounded by double quotes.

String Concatenation

You can add strings to string to create "Hello" + "Angela"


a new string. This is called concatenation. #becomes "HelloAngela"
It results in a new string.

Escaping a String

Because the double quote is special, it speech = "She said: \"Hi\""


denotes a string, if you want to use it in print(speech)
a string, you need to escape it with a "\"
#prints: She said: "Hi"

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

F-Strings

You can insert a variable into a string days = 365


using f-strings. print(f"There are {days}
The syntax is simple, just insert the variable in a year")
in-between a set of curly braces {}.

Converting Data Types

You can convert a variable from 1 data n = 354


type to another. new_n = float(n)
Converting to float:
float() print(new_n) #result 354.0
Converting to int:
int()
Converting to string:
str()

Checking Data Types

You can use the type() function


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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP
MATHS

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

The += Operator

This is a convenient way to modify a variable. my_number = 4


It takes the existing value in a variable my_number += 2
and adds to it.
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 5 % 2


remainder after a division. #result is 1
e.g. 4 ÷ 2 = 2 with no remainder
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.

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

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


my_number = 4
with a name that the computer 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'
Note: variable names are case sensitive!
is not defined

Zero Division Error

This happens when you try to divide by zero,


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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

FUNCTIONS

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

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

Functions with Inputs

In addition to simple functions, you can def add(n1, n2):


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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

Functions with Outputs

In addition to inputs, a function can also have def add(n1, n2):


an output. The output value is proceeded by return n1 + n2
the keyword "return".
This allows you to store the result from a
function.
result = add(2, 3)

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

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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

CONDITIONALS

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

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

Elif

In addition to the initial If statement weather = "sunny"


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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

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

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

not

This will flip the original result of the


if not 3 > 1:
condition. e.g. if it was true then it's now print("something")
false. #Will not be printed.

comparison operators

These mathematical comparison operators


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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

LOOPS

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

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

_ in a For Loop

If the value your for loop is iterating through,


for _ in range(100):
e.g. the number in the range, or the item in #Do something 100 times.
the list is not needed, you can replace it with
an underscore.

break

This keyword allows you to break free of the


scores = [34, 67, 99, 105]
loop. You can use it in a for or while loop. for s in scores:
if s > 100:
print("Invalid")
break
print(s)
[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

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

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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

LIST METHODS

Adding Lists Together


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

Adding an Item to a List


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

List Index

To get hold of a particular item from a letters = ["a", "b", "c"]


list you can use its index number. letters[0]
This number can also be negative, if you #Result:"a"
want to start counting from the end of the
list.
letters[-1]
#Result: "c"
List Slicing

Using the list index and the colon symbol #list[start:end]


you can slice up a list to get only the letters = ["a","b","c","d"]
portion you want. letters[1:3]
Start is included, but end is not.
#Result: ["b", "c"]

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

BUILT IN FUNCTIONS

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

Randomisation
import random
The random functions come from the
# randint(start, end)
random module which needs to be
imported. n = [Link](2, 5)
In this case, the start and end are both #n can be 2, 3, 4 or 5.
included
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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

MODULES

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

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

Importing from modules


from random import randint
You can import a specific thing from a n = randint(1, 5)
module. e.g. a function/class/constant
You 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


from random import *
everything from a module. Beware, this list = [1, 2, 3]
usually reduces code readability. choice(list)
# More readable/understood
#[Link](list)

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

CLASSES & OBJECTS

Creating a Python Class


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

Creating an Object from a Class


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

my_toyota = Car()

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

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

[Link]
PYTHON CHEAT SHEET
100 DAYS OF CODE
COMPLETE PROFESSIONAL
PYTHON BOOTCAMP

The __init__ method


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

Class Properties

You can create a variable in the init() of


class Car:
a class so that all objects created from the def __init__(self, name):
class has access to that variable. [Link] = "Jimmy"

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

Common questions

Powered by AI

In Python loops, 'break' and 'continue' control the flow by altering the normal sequential execution of loops. The 'break' keyword is used to exit a loop prematurely when a certain condition is met, skipping any remaining code within the loop body. For example, it can stop a loop searching through a list as soon as a special condition is true . On the other hand, 'continue' skips the current iteration and goes back to the loop's beginning for the next iteration, which can be useful in skipping over unwanted data while still continuing the loop . This selective skipping helps refine the logic inside loops without terminating them entirely.

Negative indexing in lists provides Python programmers with the ability to access elements from the end backwards, without needing to determine the list's length. This is beneficial when working with lists of unknown or variable length, as it allows access to elements relative to the end of the list, such as the last element with index -1 . Negative indexing simplifies situations where recent or trailing elements need to be accessed directly, streamlining list operations and contributing to concise and efficient code.

Using keyword arguments in Python functions offers increased clarity and flexibility over traditional positional arguments. They enable functions to be called with arguments in any order by associating each value with a parameter by name, reducing errors from incorrect ordering of inputs. For instance, invoking `divide(n2=5, n1=10)` avoids the necessity of matching parameter positions . This approach enhances code readability and maintainability, making it easier to understand and modify function calls when multiple parameters are involved.

Python's arithmetic operators, such as +, -, *, /, and **, are used to perform basic mathematical operations like addition, subtraction, multiplication, division, and exponentiation, respectively . In contrast, the modulo operator (%) specifically provides the remainder from division, which is useful for tasks like checking if a number is odd or even . While arithmetic operators handle continuous mathematical calculations between numbers, the modulo operator is beneficial for discrete checks and determining divisibility.

Python handles variable scope by limiting the accessibility of variables declared inside functions to the function itself. These variables are local to the function and are destroyed once the function execution completes. This means that variables cannot be accessed outside the function in which they were created. For instance, a variable `n` defined inside a function cannot affect the value of a global variable with the same name outside the function. This isolation allows functions to operate independently without side-effects on other parts of the code . Scope management ensures that alterations to variables inside a function are specific to that function's execution context.

Common Python errors include NameError, ZeroDivisionError, and SyntaxError. NameError occurs when a variable name isn't recognized, usually due to typographical errors or case sensitivity issues, and can be avoided by consistency in naming conventions . ZeroDivisionError happens when division by zero is attempted, resolvable by ensuring divisors are checked against zero before division operations . SyntaxError arises from code not conforming to Python's syntax, such as unmatched parentheses or incorrect indentation, and can be avoided by thorough code review and using an IDE that highlights syntax errors . Each error type provides specific feedback to correct its occurrence.

List slicing in Python allows access to a subset of list elements by specifying a start and end index, formatted as list[start:end], where 'start' is included and 'end' is not. Negative indices can be used to reference elements from the end of the list, making it possible to slice from the end without knowing the list length explicitly. For example, lst[-4:-1] would slice the last four elements except the last one . This flexibility enables dynamic slicing of lists for different requirements, thus advancing data handling capabilities.

F-strings improve code readability by allowing the direct inclusion of variables within curly braces inside a string literal, making the code concise and clear. For example, using f-strings like `print(f"There are {days} in a year")` embeds the variable value naturally within the string, while traditional string concatenation requires multiple operations and potentially more complex syntax to achieve the same result, such as `"There are " + str(days) + " in a year"` . F-strings simplify code writing and reduce syntax errors related to quote management in concatenation.

Python's 'range' function can generate sequences of numbers with specified start, end, and step values. It constructs a sequence starting from the 'start' index, up to but not including the 'end' index, incremented by 'step'. This customization allows for generating arithmetic progressions of numbers efficiently, as illustrated by `range(6, 0, -2)` producing 6, 4, 2 . 'Range' is versatile in creating lists of numbers used in loops, enabling precise control over iteration without manually managing index values.

The 'abs' function in Python returns the absolute value of a number, effectively removing any negative sign. This is particularly useful in situations where only the magnitude of a number is desired, irrespective of its sign, such as calculating distances or error magnitudes where negative values should not influence results . The ability to convert negative to positive values expands its use case in data analysis to ensure all results are non-negative.

B A S I C S
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A
D A T A  T Y P E S
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O
www.appbrewery.com
 
Converting Data Types
You can convert a variable from 1 data 
type to another.
Converting to float: 
flo
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app
PYTHON CHEAT SHEET
1 0 0  D A Y S  O F  C O D E
C O M P L E T E  P R O F E S S I O N A L
P Y T H O N  B O O T C A M P
www.app

You might also like