Hello World: Cheatsheets / Learn Python 3
Hello World: Cheatsheets / Learn Python 3
Hello World
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 1 of 6
12/28/20, 12:55 AM
Comments
A comment is a piece of text within a program that is
not executed. It can be used to provide additional # Comment on a single line
information to aid in understanding the code.
The # character is used to start a comment and it user = "JDoe" # Comment after code
continues until the end of the line.
Arithmetic Operations
Python supports di!erent types of arithmetic
operations that can be performed on literal numbers, # Arithmetic operations
variables, or some combination. The primary
arithmetic operators are: result = 10 + 30
result = 40 - 10
●
+ for addition
result = 50 * 5
●
- for subtraction result = 16 / 4
result = 25 % 2
●
* for multiplication
result = 5 ** 3
●
/ for division
●
% for modulus (returns the remainder)
●
** for exponentiation
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 2 of 6
12/28/20, 12:55 AM
Plus-Equals Operator +=
The plus-equals operator += provides a convenient
way to add a value to an existing variable and assign # Plus-Equal Operator
the new value back to the same variable. In the case
where the variable and the value are strings, this counter = 0
operator performs string concatenation instead of counter += 10
addition.
The operation is performed in-place, meaning that any # This is equivalent to
other variable which points to the variable being
updated will also be updated.
counter = 0
counter = counter + 10
Variables
A variable is used to store data that will be used by the
program. This data can be a number, a string, a # These are all valid variable names
Boolean, a list or some other data type. Every variable and assignment
has a name which can consist of letters, numbers, and
the underscore character _ . user_name = "@sonnynomnom"
The equal sign = is used to assign a value to a user_id = 100
variable. After the initial assignment is made, the value verified = False
of a variable can be updated to new values as needed.
points = 100
points = 120
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 3 of 6
12/28/20, 12:55 AM
Modulo Operator %
A modulo calculation returns the remainder of a
division between the "rst and second number. For # Modulo operations
example:
zero = 8 % 4
●
The result of the expression 4 % 2 would
result in the value 0, because 4 is evenly divisible
nonzero = 12 % 5
by 2 leaving no remainder.
●
The result of the expression 7 % 3 would
return 1, because 7 is not evenly divisible by 3,
leaving a remainder of 1.
Integers
An integer is a number that can be written without a
fractional part (no decimal). An integer can be a # Example integer numbers
positive number, a negative number or the number 0
so long as there is no decimal portion. chairs = 4
The number 0 represents an integer value but the tables = 1
same number written as 0.0 would represent a broken_chairs = -2
#oating point number. sofas = 0
# Non-integer numbers
lights = 2.5
left_overs = 0.0
String Concatenation
Python supports the joining (concatenation) of strings
together using the + operator. The + operator is # String concatenation
also used for mathematical addition operations. If the
parameters passed to the + operator are strings, first = "Hello "
then concatenation will be performed. If the second = "World"
parameter passed to + have di!erent types, then
Python will report an error condition. Multiple result = first + second
variables or literal strings can be joined together using
the + operator. long_result = first + second + "!"
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 4 of 6
12/28/20, 12:55 AM
Errors
The Python interpreter will report errors present in
your code. For most error cases, the interpreter will if False ISNOTEQUAL True:
display the line of code where the error was detected ^
and place a caret character ^ under the portion of SyntaxError: invalid syntax
the code where the error was detected.
ZeroDivisionError
A ZeroDivisionError is reported by the Python
interpreter when it detects a division operation is numerator = 100
being performed and the denominator (bottom denominator = 0
number) is 0. In mathematics, dividing a number by bad_results = numerator / denominator
zero has no de"ned value, so Python treats this as an
error condition and will report a ZeroDivisionError and
ZeroDivisionError: division by zero
display the line of code where the division occurred.
This can also happen if a variable is used as the
denominator and its value has been set to or changed
to 0.
Strings
A string is a sequence of characters (letters, numbers,
whitespace or punctuation) enclosed by quotation user = "User Full Name"
marks. It can be enclosed using either the double game = 'Monopoly'
quotation mark " or the single quotation mark ' .
If a string has to be broken into multiple lines, the longer = "This string is broken up \
backslash character \ can be used to indicate that over multiple lines"
the string continues on the next line.
SyntaxError
A SyntaxError is reported by the Python interpreter
when some portion of the code is incorrect. This can age = 7 + 5 = 4
include misspelled keywords, missing or too many
brackets or parenthesis, incorrect operators, missing File "<stdin>", line 1
or too many quotation marks, or other conditions.
SyntaxError: can't assign to operator
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 5 of 6
12/28/20, 12:55 AM
NameError
A NameError is reported by the Python interpreter
when it detects a variable that is unknown. This can misspelled_variable_name
occur when a variable is used before it has been
assigned a value or if a variable name is spelled NameError: name
di!erently than the point at which it was de"ned. The
'misspelled_variable_name' is not
Python interpreter will display the line of code where
defined
the NameError was detected and indicate which name
it found that was not de"ned.
print() Function
The print() function is used to output text,
numbers, or other printable information to the print("Hello World!")
console.
It takes one or more arguments and will output each print(100)
of the arguments to the console separated by a space.
If no arguments are provided, the print() pi = 3.14159
function will output a blank line. print(pi)
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 6 of 6
12/28/20, 12:55 AM
Functions
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 1 of 6
12/28/20, 12:55 AM
Function Parameters
Sometimes functions require input to provide data for
their code. This input is de!ned using parameters. def write_a_book(character, setting,
Parameters are variables that are de!ned in the special_skill):
function de!nition. They are assigned the values which print(character + " is in " +
were passed as arguments when the function was setting + " practicing her "
called, elsewhere in the code.
+
For example, the function de!nition de!nes
special_skill)
parameters for a character, a setting, and a skill, which
are used as inputs to write the !rst sentence of a
book.
Multiple Parameters
Python functions can have multiple parameters. Just
as you wouldn’t go to school without both a backpack def ready_for_school(backpack,
and a pencil case, functions may also need more than pencil_case):
one input to carry out their operations. if (backpack == 'full' and
To de!ne a function with multiple parameters, pencil_case == 'full'):
parameter names are placed one after another,
print ("I'm ready for school!")
separated by commas, within the parentheses of the
function de!nition.
Functions
Some tasks need to be performed multiple times
within a program. Rather than rewrite the same code # Define a function my_function()
in multiple places, a function may be de!ned using the with parameter x
def keyword. Function de!nitions may include
parameters, providing data input to the function. def my_function(x):
Functions may return a value using the return return x + 1
keyword followed by the value to return.
# Invoke the function
print(my_function(2)) # Output:
3
print(my_function(3 + 5)) # Output:
9
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 2 of 6
12/28/20, 12:55 AM
Function Indentation
Python uses indentation to identify blocks of code.
Code within the same block should be indented at the # Indentation is used to identify
same level. A Python function is one type of code code blocks
block. All code under a function declaration should be
indented to identify it as part of the function. There def testfunction(number):
can be additional indentation within a function to
# This code is part of testfunction
handle other statements such as for and if so print("Inside the testfunction")
long as the lines are not indented less than the !rst
sum = 0
line of the function code.
for x in range(number):
# More indentation because 'for'
has a code block
# but still part of he function
sum += x
return sum
print("This is not part of
testfunction")
Calling Functions
Python uses simple syntax to use, invoke, or call a
preexisting function. A function can be called by doHomework()
writing the name of it, followed by parentheses.
For example, the code provided would call the
doHomework() method.
Function Arguments
Parameters in python are variables — placeholders for
the actual values the function needs. When the def sales(grocery_store,
function is called, these values are passed in as item_on_sale, cost):
arguments. print(grocery_store + " is selling
For example, the arguments passed into the function " + item_on_sale + " for " + cost)
.sales() are the “The Farmer’s Market”,
“toothpaste”, and “$1” which correspond to the
sales("The Farmer’s Market",
parameters grocery_store , "toothpaste", "$1")
item_on_sale , and cost .
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 3 of 6
12/28/20, 12:55 AM
three_squared, four_squared,
five_squared = square_point(3, 4, 5)
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 4 of 6
12/28/20, 12:55 AM
year_to_check = 2018
returned_value
= check_leap_year(year_to_check)
print(returned_value) # 2018 is not
a leap year.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 5 of 6
12/28/20, 12:55 AM
Global Variables
A variable that is de!ned outside of a function is called
a global variable. It can be accessed inside the body of a = "Hello"
a function.
In the example, the variable a is a global variable def prints_a():
because it is de!ned outside of the function print(a)
prints_a . It is therefore accessible to
prints_a , which will print the value of a . # will print "Hello"
prints_a()
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 6 of 6
12/28/20, 12:55 AM
Control Flow
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 1 of 6
12/28/20, 12:55 AM
elif Statement
The Python elif statement allows for continued
# elif Statement
checks to be performed after an initial if
statement. An elif statement di!ers from the
pet_type = "fish"
else statement because another expression is
provided to be checked, just as with the initial if
if pet_type == "dog":
statement.
print("You have a dog.")
If the expression is True , the indented code
elif pet_type == "cat":
following the elif is executed. If the expression print("You have a cat.")
evaluates to False , the code can continue to an elif pet_type == "fish":
optional else statement. Multiple elif # this is performed
statements can be used following an initial if to print("You have a fish")
perform a series of checks. Once an elif else:
expression evaluates to True , no further elif print("Not sure!")
statements are executed.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 2 of 6
12/28/20, 12:55 AM
or Operator
The Python or operator combines two Boolean
True or True # Evaluates to True
expressions and evaluates to True if at least one of
True or False # Evaluates to True
the expressions returns True . Otherwise, if both
False or False # Evaluates to
expressions are False , then the entire expression
False
evaluates to False .
1 < 2 or 3 < 1 # Evaluates to True
3 < 1 or 1 > 6 # Evaluates to
False
1 == 1 or 1 < 2 # Evaluates to True
Equal Operator ==
The equal operator, == , is used to compare two
values, variables or expressions to determine if they # Equal operator
are the same.
If the values being compared are the same, the if 'Yes' == 'Yes':
operator returns True , otherwise it returns # evaluates to True
False . print('They are equal')
The operator takes the data type into account when
making the comparison, so a string value of "2" is if (2 > 1) == (5 < 10):
not considered the same as a numeric value of 2 . # evaluates to True
print('Both expressions give the
same result')
c = '2'
d = 2
if c == d:
print('They are equal')
else:
print('They are not equal')
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 3 of 6
12/28/20, 12:55 AM
Comparison Operators
In Python, relational operators compare two values or
expressions. The most common ones are: a = 2
b = 3
●
< less than a < b # evaluates to True
●
> greater than a > b # evaluates to False
a >= b # evaluates to False
●
<= less than or equal to a <= b # evaluates to True
●
>= greater than or equal too a <= a # evaluates to True
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 4 of 6
12/28/20, 12:55 AM
if Statement
The Python if statement is used to determine the
execution of code based on the evaluation of a # if Statement
Boolean expression.
test_value = 100
●
If the if statement expression evaluates to
True , then the indented code following the if test_value > 1:
statement is executed. # Expression evaluates to True
print("This code is executed!")
●
If the expression evaluates to False then the
indented code following the if statement is
if test_value > 1000:
skipped and the program executes the next line
# Expression evaluates to False
of code which is indented at the same level as
print("This code is NOT executed!")
the if statement.
else Statement
The Python else statement provides alternate
# else Statement
code to execute if the expression in an if
statement evaluates to False .
test_value = 50
The indented code for the if statement is executed
if the expression evaluates to True . The indented
if test_value < 1:
code immediately following the else is executed print("Value is < 1")
only if the expression evaluates to False . To mark else:
the end of the else block, the code must be print("Value is >= 1")
unindented to the same level as the starting if line.
test_string = "VALID"
if test_string == "NOT_VALID":
print("String equals NOT_VALID")
else:
print("String equals something
else!")
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 5 of 6
12/28/20, 12:55 AM
and Operator
The Python and operator performs a Boolean
comparison between two Boolean values, variables, or True and True # Evaluates to True
expressions. If both sides of the operator evaluate to True and False # Evaluates to
True then the and operator returns True . If False
either side (or both sides) evaluates to False , then
False and False # Evaluates to
False
the and operator returns False . A non-Boolean
value (or variable that stores a value) will always
1 == 1 and 1 < 2 # Evaluates to True
1 < 2 and 3 < 1 # Evaluates to
evaluate to True when used with the and
operator.
False
"Yes" and 100 # Evaluates to True
Boolean Values
Booleans are a data type in Python, much like integers,
"oats, and strings. However, booleans only have two is_true = True
values: is_false = False
●
True print(type(is_true))
●
False # will output: <class 'bool'>
not Operator
The Python Boolean not operator is used in a
Boolean expression in order to evaluate the expression not True # Evaluates to False
to its inverse value. If the original expression was not False # Evaluates to True
True , including the not operator would make 1 > 2 # Evaluates to False
the expression False , and vice versa.
not 1 > 2 # Evaluates to True
1 == 1 # Evaluates to True
not 1 == 1 # Evaluates to False
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 6 of 6
12/28/20, 12:55 AM
Lists
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 1 of 5
12/28/20, 12:55 AM
Lists
In Python, lists are ordered collections of items that
allow for easy use of a set of data. primes = [2, 3, 5, 7, 11]
List values are placed in between square brackets [ print(primes)
] , separated by commas. It is good practice to put a
space between the comma and the next value. The empty_list = []
values in a list do not need to be unique (the same
value can be repeated).
Empty lists do not contain any values within the square
brackets.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 2 of 5
12/28/20, 12:55 AM
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 3 of 5
12/28/20, 12:55 AM
Zero-Indexing
In Python, list index begins at zero and ends at the
length of the list minus one. For example, in this list, names = ['Roger', 'Rafael', 'Andy',
'Andy' is found at index 2 . 'Novak']
List Indices
Python list elements are ordered by index, a number
referring to their placement in the list. List indices berries = ["blueberry", "cranberry",
start at 0 and increment by one. "raspberry"]
To access a list element by index, square bracket
notation is used: list[index] . berries[0] # "blueberry"
berries[2] # "raspberry"
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 4 of 5
12/28/20, 12:55 AM
List Slicing
A slice, or sub-list of Python list elements can be
selected from a list using a colon-separated starting tools = ['pen', 'hammer', 'lever']
and ending point. tools_slice = tools[1:3] # ['hammer',
The syntax pattern is 'lever']
myList[START_NUMBER:END_NUMBER] . tools_slice[0] = 'nail'
The slice will include the START_NUMBER index,
and everything until but excluding the # Original list is unaltered:
END_NUMBER item. print(tools) # ['pen', 'hammer',
When slicing a list, a new list is returned, so if the slice 'lever']
is saved and then altered, the original list remains the
same.
sorted() Function
The Python sorted() function accepts a list as
an argument, and will return a new, sorted list unsortedList = [4, 2, 1, 3]
containing the same elements as the original. sortedList = sorted(unsortedList)
Numerical lists will be sorted in ascending order, and print(sortedList)
lists of Strings will be sorted into alphabetical order. It # Output: [1, 2, 3, 4]
does not modify the original, unsorted list.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 5 of 5
12/28/20, 12:55 AM
Loops
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 1 of 5
12/28/20, 12:55 AM
break Keyword
In a loop, the break keyword escapes the loop,
numbers = [0, 254, 2, -1, 3]
regardless of the iteration number. Once break
executes, the program will continue to execute after
the loop. for num in numbers:
In this example, the output would be: if (num < 0):
print("Negative number
●
0 detected!")
break
●
254
print(num)
●
2
# 0
●
Negative number detected!
# 254
# 2
# Negative number detected!
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 2 of 5
12/28/20, 12:55 AM
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 3 of 5
12/28/20, 12:55 AM
In!nite Loop
An in!nite loop is a loop that never terminates. In!nite
loops result when the conditions of the loop prevent it
from terminating. This could be due to a typo in the
conditional statement within the loop or incorrect
logic. To interrupt a Python program that is running
forever, press the Ctrl and C keys together on
your keyboard.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 4 of 5
12/28/20, 12:55 AM
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 5 of 5
12/28/20, 12:56 AM
Strings
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 1 of 7
12/28/20, 12:56 AM
Strings
In computer science, sequences of characters are
referred to as strings. Strings can be any length and
can include any character such as letters, numbers,
symbols, and whitespace (spaces, tabs, new lines).
Escaping Characters
Backslashes ( \ ) are used to escape characters in a
Python string. txt = "She said \"Never let go\"."
For instance, to print a string with quotation marks, the print(txt) # She said "Never let go".
given code snippet can be used.
The in Syntax
The in syntax is used to determine if a letter or a
game = "Popular Nintendo Game: Mario
substring exists in a string. It returns True if a
Kart"
match is found, otherwise False is returned.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 2 of 7
12/28/20, 12:56 AM
Iterate String
To iterate through a string in Python, “for…in” notation
is used. str = "hello"
for c in str:
print(c)
# h
# e
# l
# l
# o
String Concatenation
To combine the content of two strings into a single
string, Python provides the + operator. This process x = 'One fish, '
of joining strings is called concatenation. y = 'two fish.'
z = x + y
print(z)
# Output: One fish, two fish.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 3 of 7
12/28/20, 12:56 AM
Immutable strings
Strings are immutable in Python. This means that once
a string has been de!ned, it can’t be changed.
There are no mutating methods for strings. This is
unlike data types like lists, which can be modi!ed once
they are created.
IndexError
When indexing into a string in Python, if you try to
access an index that doesn’t exist, an fruit = "Berry"
IndexError is generated. For example, the indx = fruit[6]
following code would create an IndexError :
print(greeting.lower())
# Prints: welcome to chili's
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 4 of 7
12/28/20, 12:56 AM
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 5 of 7
12/28/20, 12:56 AM
String replace
The .replace() method is used to replace the
occurence of the !rst argument with the second fruit = "Strawberry"
argument within the string. print(fruit.replace('r', 'R'))
The !rst argument is the old substring to be replaced,
and the second argument is the new substring that will # StRawbeRRy
replace every occurence of the !rst one within the
string.
print(dinosaur.upper())
# Prints: T-REX
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 6 of 7
12/28/20, 12:56 AM
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 7 of 7
12/28/20, 12:56 AM
Modules
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 1 of 4
12/28/20, 12:56 AM
time_13_48min_5sec
= datetime.time(hour=13, minute=48,
second=5)
time_13_48min_5sec
= datetime.time(13, 48, 5)
print(time_13_48min_5sec) #13:48:05
timestamp=
datetime.datetime(year=2019, month=2,
day=16, hour=13, minute=48, second=5)
timestamp = datetime.datetime(2019,
2, 16, 13, 48, 5)
print (timestamp) #2019-01-02
13:48:05
# Aliasing calendar as c
import calendar as c
print(c.month_name[1])
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 2 of 4
12/28/20, 12:56 AM
# Third way
from module import *
function()
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 3 of 4
12/28/20, 12:56 AM
Module importing
In Python, you can import and use the content of
another !le using import filename , provided # file1 content
that it is in the same folder as the current !le you are # def f1_function():
writing. # return "Hello World"
# file2
import file1
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 4 of 4
12/28/20, 12:56 AM
Dictionaries
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 1 of 4
12/28/20, 12:56 AM
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 2 of 4
12/28/20, 12:56 AM
Python dictionaries
A python dictionary is an unordered collection of
items. It contains data as a set of key: value pairs. my_dictionary = {1: "L.A. Lakers", 2:
"Houston Rockets"}
ex_dict.items()
# [("a","anteater"),
("b","bumblebee"),("c","cheetah")]
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 3 of 4
12/28/20, 12:56 AM
# with default
{"name": "Victor"}.get("nickname",
"nickname is not a key")
# returns "nickname is not a key"
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 4 of 4
12/28/20, 12:57 AM
Files
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 1 of 7
12/28/20, 12:57 AM
with open('somefile.txt') as
file_object:
print(file_object)
<_io.TextIOWrapper
name='somefile.txt' mode='r'
encoding='UTF-8'>
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 2 of 7
12/28/20, 12:57 AM
with open('story.txt') as
story_object:
print(story_object.readline(
))
import json
with open('file.json') as json_file:
python_dict = json.load(json_file)
print(python_dict.get('userId'))
# Prints 10
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 3 of 7
12/28/20, 12:57 AM
with open('diary.txt','w') as
diary:
diary.write('Special events
for today')
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 4 of 7
12/28/20, 12:57 AM
with open('lines.txt') as
file_object:
file_data
= file_object.readlines()
print(file_data)
outputs:
1. Learn Python.
2. Work hard.
3. Graduate.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 5 of 7
12/28/20, 12:57 AM
Class csv.DictWriter
In Python, the csv module implements classes to
read and write tabular data in CSV format. It has a # An example of csv.DictWriter
class DictWriter which operates like a regular import csv
writer but maps a dictionary onto output rows. The
keys of the dictionary are column names while values with open('companies.csv', 'w') as
are actual data. csvfile:
The csv.DictWriter constructor takes two fieldnames = ['name', 'type']
arguments. The !rst is the open !le handler that the writer = csv.DictWriter(csvfile,
CSV is being written to. The second named parameter, fieldnames=fieldnames)
fieldnames , is a list of !eld names that the CSV writer.writeheader()
is going to handle. writer.writerow({'name':
'Codecademy', 'type': 'Learning'})
writer.writerow({'name': 'Google',
'type': 'Search'})
"""
After running the above code,
companies.csv will contain the
following information:
name,type
Codecademy,Learning
Google,Search
"""
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 6 of 7
12/28/20, 12:57 AM
with open('mystery.txt') as
text_file:
text_data = text_file.read()
print(text_data)
Mystery solved.
Congratulations!
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 7 of 7
12/28/20, 12:57 AM
Classes
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 1 of 9
12/28/20, 12:57 AM
def __repr__(self):
return self.name
john = Employee('John')
print(john) # John
# Class Instantiation
ferrari = Car()
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 2 of 9
12/28/20, 12:57 AM
print(x.class_variable) #I am a Class
Variable!
print(y.class_variable) #I am a Class
Variable!
dog = Animal('Woof')
print(dog.voice) # Output: Woof
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 3 of 9
12/28/20, 12:57 AM
a = 1.1
print(type(a)) # <class 'float'>
a = 'b'
print(type(a)) # <class 'str'>
a = None
print(type(a)) # <class 'NoneType'>
Python class
In Python, a class is a template for a data type. A class
can be de!ned using the class keyword. # Defining a class
class Animal:
def __init__(self, name,
number_of_legs):
self.name = name
self.number_of_legs
= number_of_legs
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 4 of 9
12/28/20, 12:57 AM
print(dir())
# ['Employee', '__builtins__',
'__doc__', '__file__', '__name__',
'__package__', 'new_employee']
print(dir(Employee))
# ['__doc__', '__init__',
'__module__', 'print_name']
__main__ in Python
In Python, __main__ is an identi!er used to
reference the current !le context. When a module is
read from standard input, a script, or from an
interactive prompt, its __name__ is set equal to
__main__ .
Suppose we create an instance of a class called
CoolClass . Printing the type() of the
instance will result in:
<class '__main__.CoolClass'>
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 5 of 9
12/28/20, 12:57 AM
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's version of
print_test()
super().print_test()
child_instance = ChildClass()
child_instance.print_test()
# Output:
# Child Method
# Parent Method
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 6 of 9
12/28/20, 12:57 AM
Polymorphism in Python
When two Python classes o"er the same set of
methods with di"erent implementations, the classes class ParentClass:
are polymorphic and are said to have the same def print_self(self):
interface. An interface in this sense might involve a print('A')
common inherited class and a set of overridden
methods. This allows using the two objects in the same
class ChildClass(ParentClass):
way regardless of their individual types.
def print_self(self):
When a child class overrides a method of a parent
print('B')
class, then the type of the object determines the
version of the method to be called. If the object is an
instance of the child class, then the child class version obj_A = ParentClass()
of the overridden method will be called. On the other obj_B = ChildClass()
hand, if the object is an instance of the parent class,
then the parent class version of the method is called. obj_A.print_self() # A
obj_B.print_self() # B
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 7 of 9
12/28/20, 12:57 AM
print(issubclass(Member, Family)) #
True
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 8 of 9
12/28/20, 12:57 AM
Python Inheritance
Subclassing in Python, also known as “inheritance”,
allows classes to share the same attributes and class Animal:
methods from a parent or superclass. Inheritance in def __init__(self, name, legs):
Python can be accomplished by putting the superclass self.name = name
name between parentheses after the subclass or child
self.legs = legs
class name.
In the example code block, the Dog class subclasses
class Dog(Animal):
the Animal class, inheriting all of its attributes. def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # YOKI
print(Yoki.legs) # 4
Yoki.sound() # Woof!
+ Operator
In Python, the + operation can be de!ned for a
user-de!ned class by giving that class an class A:
.__add()__ method. def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other.a
obj1 = A(5)
obj2 = A(10)
print(obj1 + obj2) # 15
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 9 of 9
12/28/20, 12:57 AM
Function Arguments
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 1 of 4
12/28/20, 12:57 AM
greet("Ankit")
greet("Ankit", "How do you do?")
"""
this code will print the following
for both the calls -
`Hello Ankit, How do you do?`
"""
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 2 of 4
12/28/20, 12:57 AM
print(my_function())
#Output
None
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 3 of 4
12/28/20, 12:57 AM
func_with_args('First', 'Second')
# Prints:
# First Second
func_with_args(arg2='Second',
arg1='First')
# Prints
# First Second
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 4 of 4