Python Basics: A Comprehensive Guide
Python Basics: A Comprehensive Guide
Python Basics 1
🧭 Navigation
Basics & Setup
Command Line Basics (Windows):
Running Python Code on CMD
No Install Options for Notebooks
Types of Integrated Development Environments (IDE)
Execute Shell Commands from within an Environment
Python Object and Data Structure Basics
Objects & Data Structure types
Creating Object & Data Structure
Numbers
1. Basic Arithmetic:
2. Variable Assignments:
Strings
1. Creating & Printing Strings
2. String Indexing and Slicing
3. String Properties
4. String Methods
5. Print Formatting
Lists
1. Creating lists
2. Indexing and Slicing Lists
3. Basic List Methods
4. Nesting Lists
5. Introduction to List Comprehensions
Dictionaries
1. Constructing a Dictionary & accessing objects from a dictionary
2. Nesting Dictionaries
3. Basic Dictionary Methods
Tuples
1. Constructing Tuples
2. Basic Tuple Methods
3. Immutability
4. When to Use Tuples
Sets
Booleans
Files & IO
Python Basics 2
Comparison Operators
Python Statements
1. and, or
2. if, elif and else
3. for Loops
4. while Loops
5. Useful Operators
6. List Comprehensions
Methods and Functions
Methods
Functions
Python Built-in Functions:
Making New Functions (Topics):
*args and **kwargs
Lambda Expressions, Map, and Filter
Installing Packages, Modules & Libraries in python
Package Installer
Pip
Python Basics 3
cd ..
----------------------------------------------------------------------------
------
# Delete files
del <file_path>
Python Basics 4
ipconfig
#These are just a few basic commands to get you started. Windows Com
mand Prompt also supports various advanced commands and features, so
feel free to explore and learn more based on your needs.
# First Change directry where the file located using folling command
cd <directory_path>
# Then to run file as python type 'python ', then type name of the file (use
'Tab' to Autocomplete)
python <name_of_the_file>
OR
# use to quit
quit()
Python Basics 5
No Install Options for Notebooks
[Link]/try
[Link] (Paid)
Google Search
Sublime Text
Atom
VS Code
Full IDE
PyCharm
Spyder
Notebook Environments
Jupyter Notebook
Python Basics 6
Type Example Description
Objects:
str
"Hello", “What?”, “ かまど”, String: Sequence of characters
“2000” enclosed in quotes.
Data Structures:
# we can create a new Object or cast an existing obect into new data type
# 1. integer
i = int(original_value) # -create a new obect
# OR
int(original_value) # -cast an existing obect into new data type
# 1. flaoat
f = float(original_value)
# OR
float(original_value)
Python Basics 7
# 3. string
S = str(original_value)
# OR
str(original_value)
# 1. Creating a List
L = list((1,2,3)) # -constructor
# OR
L = [1,2,3] # -literal notation
# 2. Creating a Dictionary
D = dict({'a': 1, 'b': 2, 'c': 3})
# OR
D = {'a': 1, 'b': 2, 'c': 3}
# 3. Creating a Tuple
T = tuple((1, 2, 3))
# OR
T = (1, 2, 3)
# 3. Creating a Set
S = set((1, 2, 3))
# OR
S = {1, 2, 3}
Numbers
1. Basic Arithmetic:
CODE:
Python Basics 8
# Addition
2+1
# Subtraction
2-1
# Division
3/2
# Floor Division, The // operator (two forward slashes) truncates the deci
mal without rounding, and returns an integer result.
7//4
# Powers
2**3
#NOTES:
# Order of Operations followed in Python
2 + 10 * 10 + 3
# Can use parentheses to specify orders
(2+10) * (10+3)
2. Variable Assignments:
The names you use when creating these labels need to follow a few rules:
Python Basics 9
4. It's considered best practice (PEP8) that names are lowercase.
5. Avoid using the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or
'I' (uppercase letter eye) as single character variable names.
6. Avoid using words that have special meaning in Python like "list" and "str"
CODE:
a=5
a+a
>>> 10
# Reassignment
a = 10
# Use A to redefine A
a=a+a
a
>>> 20
a = 20
print(a)
>>> 20
del a
Python Basics 10
Strings
1. Creating & Printing Strings
CODE:
CODE:
# Indexing
# Assign s as a string
s = 'Hello World'
Python Basics 11
s[1]
>>> 'e'
# Slicing
# Grab everything past the first term all the way to the length of s which is
len(s)
s[1:]
>>> 'ello World'
#Everything
s[:]
>>> 'Hello World'
# Negative Indexing
# Last letter
s[-1]
>>> 'd'
# Step Size
Python Basics 12
# Grab everything, but go in steps size of 1
s[::1]
>>> 'Hello World'
3. String Properties
CODE:
s = 'Hello World'
# String Concatenation
s + ' concatenate me!'
>>> 'Hello World concatenate me!'
letter*10
>>> 'zzzzzzzzzz'
4. String Methods
The Python method syntax is [Link](parameters)
Python Basics 13
CODE:
# Lower case
[Link]()
# Split by a specific element (doesn't include the element that was split o
n)
[Link]('W')
>>> ['Hello ', 'orld concatenate me!']
# There are many more methods than the ones covered here.
5. Print Formatting
CODE:
Python Basics 14
ctively).
# [Link]() Method:
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
#OR
print("My name is {n} and I am {a} years old.".format(n=name, a=age))
Lists
1. Creating lists
Unlike strings, Lists are mutable, meaning the elements inside a list can be
changed.
CODE:
# Just like strings, the len() function will tell you how many items are in the
sequence of the list.
len(my_list)
>>> 4
Python Basics 15
CODE:
my_list = ['one','two','three',4,5]
Python Basics 16
3. Basic List Methods
CODE:
list1 = [1,2,3]
# [Link] - Use pop to "pop off" an item from the list. By default pop takes
off the last index, but you can also specify which index to pop off
[Link](0)
# [Link] - Use sort to sort the list (in this case alphabetical order, but for n
umbers it will go ascending)
[Link]()
4. Nesting Lists
Nesting means we can have data structures within data structures. For example: A
list inside a list.
CODE:
Python Basics 17
matrix = [lst_1,lst_2,lst_3]
matrix
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[0]
>>> [1, 2, 3]
matrix[0][0]
>>> 1
Some Examples:
# 1. Grab 1st element in all the list inside the matrix list
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
matrix = [lst_1,lst_2,lst_3] # creates list of all 3 lists like: [[1, 2, 3], [4, 5, 6],
[7, 8, 9]]
Python Basics 18
squared_numbers = [x**2 for x in range(5)]
squared_numbers
>>> [0, 1, 4, 9, 16]
Dictionaries
1. Constructing a Dictionary & accessing objects from a dictionary
A Python dictionary consists of a key and then an associated value. That value
can be almost any Python object.
CODE:
my_dict['key2']
>>> 'value2'
# dictionaries are very flexible in the data types they can hold. For exampl
e:
my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}
my_dict['key3']
>>> ['item0', 'item1', 'item2']
my_dict['key3'][0]
>>> 'item0'
my_dict['key3'][0].upper()
>>> 'ITEM0'
Python Basics 19
my_dict['key1']
>>> 123
my_dict['key1']
>>> 0
my_dict2 = {}
my_dict2['animal'] = 'Dog'
my_dict2['answer'] = 42
my_dict2
>>> {'animal': 'Dog', 'answer': 42}
2. Nesting Dictionaries
CODE:
Python Basics 20
# Each of these methods return a dictionary view object
d = {'key1':1,'key2':2,'key3':3}
[Link]()
>>> dict_keys(['key1', 'key2', 'key3'])
[Link]()
>>> dict_values([1, 2, 3])
[Link]()
>>> dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
Tuples
In Python tuples are very similar to lists, however, unlike lists they
are immutable meaning they can not be changed. You would use tuples to present
things that shouldn't be changed, such as days of the week, or dates on a
calendar.
1. Constructing Tuples
CODE:
t = (1,2,3)
len(t)
>>> 3
Python Basics 21
# Can also mix object types
t = ('one',2)
t
>>> ('one', 2)
3. Immutability
CODE:
Python Basics 22
[Link]('nope')
>>> AttributeError
Sets
Sets are an unordered collection of unique elements. We can construct them by
using the set() function.
A set has only unique entries. So it will not affect the set if we add an item which
that set already has.
CODE:
x = set()
x
>>> {1}
[Link](2)
x
>>> {1,2}
# We can cast a list with multiple repeat elements to a set to get the uniqu
e elements. For example:
Python Basics 23
list1 = [1,1,2,2,3,4,5,6,1,1]
Booleans
Python comes with Booleans (with predefined True and False displays that are
basically just the integers 1 and 0). It also has a placeholder object called None.
CODE:
a
>>> True
# Output is boolean
1>2
>>> False
b = None
print(b)
>>> None
Files & IO
Python Basics 24
Python uses file objects to interact with external files on your computer. These file
objects can be any sort of file you have on your computer, whether it be an audio
file, a text file, emails, Excel documents, etc.
%%writefile <file_name>.txt
Hello, this is a quick test file. # write content of the text file
myfile = open('<file_name>.txt')
# to grab files from any location on your computer, simply pass in the entir
e file path.
# For Windows you need to use double \ so python doesn't treat the seco
nd \ as an escape character, a file path is in the form
myfile = open("C:\\Users\\YourUserName\\Home\\Folder\\[Link]")
pwd
>>> 'C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Boot
camp\\00-Python Object and Data Structure Basics'
4. Read File
my_file.read()
>>> 'Hello, this is a quick test file.'
5. Seek Method
Python Basics 25
# But if we try to read it again, it will rearurn an empty string.
my_file.read()
>>> ''
# This happens because you can imagine the reading "cursor" is at the en
d of the file after having read it. So there is nothing left to read. We can res
et the "cursor" like this:
# You can read a file line by line using the readlines method. Use caution
with large files, since everything will be held in memory. We will learn how
to iterate over large files later in the course.
7. Close file
# When you have finished using a file, it is always good practice to close i
t.
my_file.close()
8. Writing to a File
Python Basics 26
# By default, the open() function will only allow us to read the file. We nee
d to pass another argument to write over the file.
my_file = open('[Link]','w+')
OR
my_file = open('[Link]', mode = 'w+')
# Use caution!
# Opening a file with 'w' or 'w+' truncates the original, meaning that anyth
ing that was in the original file is deleted!
my_file = open('[Link]','a+')
my_file.write('\nThis is text being appended to [Link]')
my_file.write('\nAnd another line here.')
Python Basics 27
my_file.seek(0)
print(my_file.read())
>>> This is a new line
This is text being appended to [Link]
And another line here.
%%writefile -a [Link]
This is text being appended to [Link] # this is the text that will be append
ed to the file
And another line here.
# Add a blank space if you want the first line to begin on its own line, as J
upyter won't recognize escape sequences like \n
Comparison Operators
In the table below, a=3 and b=4.
>= If the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, then
Python Basics 28
Operator Description Example
condition becomes true.
CODE:
# [Link]
2 == 2
>>> True
1 == 0
>>> False
# [Link] Equal
2 != 1
>>> True
2 != 2
>>> False
# [Link] Than
4>2
>>> True
1>2
>>> False
# [Link] Than
Python Basics 29
2<4
>>> True
2<1
>>> False
2 >= 2
>>> True
2 >= 1
>>> True
2 <= 2
>>> True
2 <= 4
>>> True
CODE:
# Example 1
1<2<3
>>> True
Python Basics 30
# The above statement checks if 1 was less than 2 and if 2 was less than
3. We could have written this using an and statement in Python:
# similarly
# Example 2
1<3>2
>>> True
# Example 3
1==2 or 2<3
>>> True
1==1 or 100==1
>>> True
Python Statements
1. and, or
CODE:
AND:
# The and is used to make sure two checks have to be true in order for the
total check to be true.
Python Basics 31
1=1 and 2=2
>>> True
OR:
if case1:
perform action1
elif case2:
perform action2
else:
perform action3
Examples:
Python Basics 32
# if statement
if True:
print('It was true!')
>>> It was true!
x = False
if x:
print('x was True!')
else:
print('I will be printed in any case where x is not true')
>>> I will be printed in any case where x is not true
loc = 'Bank'
# you can put in as many elif statements as you want before you close off
with an else.
loc = 'E'
if loc == 'A':
print('Action A')
Python Basics 33
elif loc == 'B':
print('Action B')
elif loc == 'C':
print('Action C')
elif loc == 'D':
print('Action D')
elif loc == 'E':
print('Action E')
else:
print('Action 0')
3. for Loops
A for loop acts as an iterator in Python; it goes through items that are in
a sequence or any other iterable item. We can iterate over any objects such as
strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or
values.
general format for a for loop in Python:
The variable name used for the item is completely up to the coder, so use your
best judgment for choosing a name that makes sense and you will be able to
understand when revisiting your code. This item name can then be referenced
inside your loop, for example if you wanted to use if statements to perform
checks.
Examples:
list1 = [1,2,3,4,5,6,7,8,9,10]
Python Basics 34
>>> 1
2
3
4
5
6
7
8
9
10
Python Basics 35
4
Odd number
6
Odd number
8
Odd number
10
print(list_sum)
>>> 55
i
s
Python Basics 36
t
r
i
n
g
tup = (1,2,3,4,5)
for t in tup:
print(t)
>>> 1
2
3
4
5
list2 = [(2,4),(6,8),(10,12)]
Python Basics 37
6
10
d = {'k1':1,'k2':2,'k3':3}
# to obtain a true list of keys, values, or key/value tuples, you can cast the
view as a list:
Python Basics 38
list([Link]())
>>> ['k1', 'k2', 'k3']
# Remember that dictionaries are unordered, and that keys and values co
me back in arbitrary order. You can obtain a sorted list using sorted():
sorted([Link]())
>>> [1, 2, 3]
4. while Loops
The while statement in Python is one of most general ways to perform iteration.
A while statement will repeatedly execute a single statement or group of
statements as long as the condition is true. The reason it is called a 'loop' is
because the code statements are looped through over and over again until the
condition is no longer met.
The general format of a while loop is:
while test:
code statements
else:
final code statements
Examples:
Example 1:
x=0
Python Basics 39
x is currently: 2
x is still less than 10, adding 1 to x
x is currently: 3
x is still less than 10, adding 1 to x
x is currently: 4
x is still less than 10, adding 1 to x
x is currently: 5
x is still less than 10, adding 1 to x
x is currently: 6
x is still less than 10, adding 1 to x
x is currently: 7
x is still less than 10, adding 1 to x
x is currently: 8
x is still less than 10, adding 1 to x
x is currently: 9
x is still less than 10, adding 1 to x
x=0
else:
print('All Done!')
>>> x is currently: 0
x is still less than 10, adding 1 to x
x is currently: 1
x is still less than 10, adding 1 to x
x is currently: 2
x is still less than 10, adding 1 to x
x is currently: 3
x is still less than 10, adding 1 to x
Python Basics 40
x is currently: 4
x is still less than 10, adding 1 to x
x is currently: 5
x is still less than 10, adding 1 to x
x is currently: 6
x is still less than 10, adding 1 to x
x is currently: 7
x is still less than 10, adding 1 to x
x is currently: 8
x is still less than 10, adding 1 to x
x is currently: 9
x is still less than 10, adding 1 to x
All Done!
We can use break , continue , and pass statements in our loops to add additional
functionality for various cases. The three statements are defined by:
while test:
code statement
if test:
break
if test:
continue
else:
breakand continue statements can appear anywhere inside the loop’s body, but
we will usually put them further nested in conjunction with an if statement to
Python Basics 41
perform an action based on some condition.
Example with continue
# in given code when x==3 it will print 'statement IF' , else it will print 'stat
ement ELSE'
x=0
Python Basics 42
step 1
step 2
statement ELSE
step 1
step 2
statement ELSE
step 1
step 2
statement ELSE
step 1
step 2
statement ELSE
x=0
# Note how the other else statement wasn't reached and continuing was n
ever printed!
Python Basics 43
🟥 Caution:
# It is possible to create an infinitely running loop with while statements. F
or example:
# A quick note: If you *did* run the above cell, click on the Kernel menu ab
ove to restart the kernel!
5. Useful Operators
There are a few built-in functions and "operators" in Python that don't fit well into
any category.
1. range
The range function allows you to quickly generate a list of integers, There are
3 parameters you can pass, a start, a stop, and a step size.
The general format of a range operator is: range(start, stop, step)
range(0,11)
>>> range(0, 11)
# Note that this is a generator function, so to actually get a list out of it, we
need to cast it to a list with list().
# Generator is a special type of function that will generate information and
not need to save it to memory.
# step size just means how big of a jump/leap/step you take from the start
Python Basics 44
ing number to get to the next number
list(range(0,11,2))
>>> [0, 2, 4, 6, 8, 10]
list(range(0,101,10))
>>> [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2. enumerate
enumerate is a very useful function to use with for loops.
index_count = 0
Python Basics 45
# Notice the format enumerate actually returns, let's take a look by transfo
rming it to a list()
list(enumerate('abcde'))
>>> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
# It was a list of tuples, meaning we could use tuple unpacking during our
for loop.
3. zip
zip() function is used to quickly create a list of tuples by "zipping" up together
two lists.
mylist1 = [1,2,3,4,5]
mylist2 = ['a','b','c','d','e']
zip(mylist1,mylist2)
>>> <zip at 0x1d205086f08>
list(zip(mylist1,mylist2))
>>> [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
Python Basics 46
For this tuple, first item was 4 and second item was d
For this tuple, first item was 5 and second item was e
4. in operator
We've already seen the in keyword during the for loop, but we can also use it
to quickly check if an object is in a list
'x' in ['x','y','z']
>>> True
'x' in [1,2,3]
>>> False
5. not in
We can combine in with a not operator, to check if some object or variable is
not present in a list.
mylist = [10,20,30,40,100]
min(mylist)
>>> 10
max(mylist)
>>> 100
Python Basics 47
7. random
Python comes with a built in random library. There are a lot of functions
included in this random library, some are given below.
mylist = [10,20,30,40,100]
# [Link]
from random import shuffle
mylist
>>> [40, 10, 100, 30, 20]
# [Link]
from random import randint
# Return random integer in range [a, b], including both end points.
randint(0,100)
>>> 27
randint(0,100)
>>> 67
8. input
Python Basics 48
| |
|----------------------------|
6. List Comprehensions
In addition to sequence operations and list methods, Python includes a more
advanced operation called a list comprehension.
List comprehensions allow us to build out lists using a different notation. You can
think of it as essentially a one line for loop built inside of brackets.
Examples:
Example 1
lst
>>> ['w', 'o', 'r', 'd']
Example 2
lst
>>> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Example 3:
Let's see how to add in if statements:
Python Basics 49
lst
>>> [0, 2, 4, 6, 8, 10]
Example 4:
More complicated arithmetic:
fahrenheit
>>> [32.0, 50.0, 68.18, 94.1]
Example 5:
Nested list comprehensions
lst
>>> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]
There are built in python functions and methods, as well as we can create them
according to our needs
my_list = [1, 2, 3, 4, 5]
Python Basics 50
# here .append is a built-in method, a metod is used after a dot after a variabl
e, we can use TAB to get list of all the methods available.
my_list.append(4)
Methods
Methods are essentially functions built into objects. Later we will learn about how
to create our own objects and methods using Object Oriented Programming (OOP)
and classes.
Methods perform specific actions on an object and can also take arguments, just
like a function.
Methods are in the form:
[Link](arg1,arg2,etc...)
Example:
With iPython and the Jupyter Notebook we can quickly see all the possible
methods using the tab key. The methods for a list are:
append
count
extend
insert
pop
remove
reverse
sort
Python Basics 51
# append - It allows us to add elements to the end of a list
[Link](6)
lst
>>> [1, 2, 3, 4, 5, 6]
# You can always use Shift+Tab in the Jupyter Notebook to get more help
about the method. In general Python you can use the help() function:
help([Link])
>>> Help on built-in function count:
count(...) method of [Link] instance
[Link](value) -> integer -- return number of occurrences of value
# ...........................
# ...........................
# ...........................
# ...........................
Functions
A function is a useful device that groups together a set of statements so they can
be run more than once. They can also let us specify parameters that can serve as
inputs to the functions.
Functions allow us to not have to repeatedly write the same code again and again.
Why even use functions?
Put simply, you should use functions when you plan on using a block of code
multiple times. The function will allow you to call the same block of code
Python Basics 52
without having to write it multiple times. This in turn will allow you to create
more complex Python scripts.
Python Basics 53
to_excel(): Write DataFrame to an Excel file.
to_feather(): Write a DataFrame to the feather format.
to_gbq(): Write a DataFrame to a Google BigQuery table.
to_hdf(): Write the contained data to an HDF5 file.
to_html(): Render a DataFrame as an HTML table.
to_json(): Convert the object to a JSON string.
to_latex(): Render object to a LaTeX tabular environment table.
to_markdown(): Print object to markdown.
to_numpy(): Convert the DataFrame to a NumPy array.
to_parquet(): Write a DataFrame to the binary parquet format.
to_period(): Convert DataFrame from datetime-like to period.
to_pickle(): Pickle (serialize) object to file.
to_records(): Convert DataFrame to a NumPy record array.
to_sql(): Write records stored in a DataFrame to a SQL database.
to_stata(): Export DataFrame object to Stata dta format.
to_string(): Render a DataFrame to a console-friendly tabular output.
to_timestamp(): Cast to datetimeindex of timestamps, at beginning of peri
od.
to_xarray(): Return an xarray object from the pandas object.
Built-in Functions
The Python interpreter has a number of functions and
types built into it that are always available. They are listed
here in alphabetical order.,,,, Built-in Functions,,, A, abs(),
[Link]
Syntax of a function:
def name_of_function(arg1,arg2):
'''
This is where the function's Document String (docstring) goes.
Python Basics 54
When you call help() on your function it will be printed out.
'''
# Do stuff here
# Return desired result
We begin with def then a space followed by the name of the function. Try to
keep names relevant, for example len() is a good name for a length() function.
Also be careful with names, you wouldn't want to call a function the same
name as a built-in function in Python (such as len).
Next come a pair of parentheses with a number of arguments separated by a
comma. These arguments are the inputs for your function. You'll be able to
use these inputs in your function and reference them. After this you put a
colon.
Now here is the important step, you must indent to begin the code inside your
function correctly. Python makes use of whitespace to organize code. Lots of
other programing languages do not do this, so keep that in mind.
Next you'll see the docstring, this is where you write a basic description of the
function. Using Jupyter and Jupyter Notebooks, you'll be able to read these
docstrings by pressing Shift+Tab after a function name. Docstrings are not
necessary for simple functions, but it's good practice to put them in so you or
other people can easily understand the code you write.
After all this you begin writing the code you wish to execute.
def say_hello():
print('hello')
say_hello()
>>> hello
# If you forget the parenthesis (), it will simply display the fact that say_hell
o is a function.
Python Basics 55
say_hello
>>> <function __main__.say_hello>
def greeting(name):
print(f'Hello {name}')
greeting('Jose')
>>> Hello Jose
Using return
So far we've only seen print() used, but if we actually want to save the
resulting variable we need to use the return keyword.
return allows a function to return a result that can then be stored as a variable,
or used in whatever manner a user wants.
Example: Addition function:
def add_num(num1,num2):
return num1+num2
add_num(4,5)
>>> 9
print(result)
>>> 9
Python Basics 56
add_num('one','two')
>>> 'onetwo'
The return keyword allows you to actually save the result of the output of a
function as a variable. The print() function simply displays the output to you,
but doesn't save it for future use.
# print function
def print_result(a,b):
print(a+b)
print_result(10,5)
>>> 15
# return function
def return_result(a,b):
return a+b
# You won't see any output if you run this in a .py script
return_result(10,5)
>>> 15
my_result = print_result(10,5)
>>> 15
type(my_result)
>>> NoneType
Python Basics 57
The print_result() doesn't let you actually save the result to a variable, It only
prints it out.
Save this result for later use with return .
my_result = return_result(10,5)
my_result
>>> 15
my_result + my_result
>>> 30
2%2
>>> 0
3%2
>>> 1
2 % 2 == 0
>>> True
3 % 2 == 0
>>> False
# Let's use this to construct a function. Notice how we simply return the b
Python Basics 58
oolean check.
def even_check(number):
return number % 2 == 0
even_check(20)
>>> True
even_check(21)
>>> False
# WRONG APPROACH 1
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# Otherwise we don't do anything
else:
pass
check_even_list([1,2,3])
>>> True
check_even_list([1,1,1])
>>> _ _ _ _
Python Basics 59
# WRONG APPROACH 2
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# This is WRONG! This returns False at the very first odd number!
# It doesn't end up checking the other numbers in the list!
else:
return False
# CORRECT APPROACH
# We need to initiate a return False AFTER running through the entire loop
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# Don't do anything if its not even
else:
pass
# Notice the indentation! This ensures we run through the entire for loo
p
return False
check_even_list([1,2,3])
Python Basics 60
>>> True
check_even_list([1,3,5])
>>> False
def check_even_list(num_list):
even_numbers = []
check_even_list([1,2,3,4,5,6])
>>> [2, 4, 6]
check_even_list([1,3,5])
>>> []
Tuple unpacking
Recall we can loop through a list of tuples and "unpack" the values within
them
Python Basics 61
stock_prices = [('AAPL',200),('GOOG',300),('MSFT',400)]
Similarly, functions often return tuples, to easily return multiple results for later
use.
The employee of the month function will return both the name and number of
hours worked for the top performer (judged by number of hours worked).
work_hours = [('Abby',100),('Billy',400),('Cassie',800)]
def employee_check(work_hours):
Python Basics 62
if hours > current_max:
current_max = hours
employee_of_month = employee
else:
pass
employee_check(work_hours)
>>> ('Cassie', 800)
return mylist
guess = ''
Python Basics 63
# Recall input() returns a string
guess = input("Pick a number: 0, 1, or 2: ")
return int(guess)
# Function 3 - check the user's guess (Notice we only print here, since we
have no need to save a user's guess or the shuffled list.)
def check_guess(mylist,guess):
if mylist[guess] == 'O':
print('Correct Guess!')
else:
print('Wrong! Better luck next time')
print(mylist)
# Initial List
mylist = [' ','O',' ']
# Function 1 - Shuffle It
mixedup_list = shuffle_list(mylist)
>>>
Python Basics 64
*args and **kwargs terms show up as parameters in function definitions.
*args:
Explanation:
def myfunc(a,b):
return sum((a,b))*.05
myfunc(40,60)
>>> 5.0
def myfunc(a=0,b=0,c=0,d=0,e=0):
return sum((a,b,c,d,e))*.05
myfunc(40,60,20)
>>> 6.0
def myfunc(*args):
return sum(args)*.05
myfunc(40,60,20)
>>> 0.6
# passing the keyword "args" into the sum() function did the same thing a
s a tuple of arguments.
# It is worth noting that the word "args" is itself arbitrary - any word will d
o so long as it's preceded by an asterisk. To demonstrate this:
Python Basics 65
def myfunc(*spam):
return sum(spam)*.05
myfunc(40,60,20)
>>> 0.6
**kwargs:
Similarly, Python offers a way to handle arbitrary numbers
of keyworded arguments. Instead of creating a tuple of values, **kwargs builds
a dictionary of key/value pairs. For example:
def myfunc(**kwargs):
if 'fruit' in kwargs:
print(f"My favorite fruit is {kwargs['fruit']}") # review String Formatti
ng and f-strings if this syntax is unfamiliar
else:
print("I don't like fruit")
myfunc(fruit='pineapple')
>>> My favorite fruit is pineapple
myfunc()
>>> I don't like fruit
Python Basics 66
t']}")
print(f"May I have some {kwargs['juice']} juice?")
else:
pass
myfunc('eggs','spam',fruit='cherries',juice='orange')
>>> I like eggs and spam and my favorite fruit is cherries
May I have some orange juice?
myfunc(fruit='cherries',juice='orange','eggs','spam')
>>> File "<ipython-input-8-fc6ff65addcc>", line 1
myfunc(fruit='cherries',juice='orange','eggs','spam')
^
SyntaxError: positional argument follows keyword argument
As with "args", you can use any name you'd like for keyworded arguments -
"kwargs" is just a popular convention.
The map function allows you to "map" a function to an iterable object. That is
to say you can quickly call the same function to every item in an iterable, such
as a list.
def square(num):
return num**2
my_nums = [1,2,3,4,5]
map(square,my_nums)
Python Basics 67
# or just cast to a list
list(map(square,my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'even'
else:
return mystring[0]
mynames = ['John','Cindy','Sarah','Kelly','Mike']
list(map(splicer,mynames))
>>> ['even', 'C', 'S', 'K', 'even']
Assigning Values
df['binary_column'] = df['Category'].map({'A':1,'B':0})
df
>>> | Category | binary_column |
|----------|---------------|
| A | 1.0 |
| B | 0.0 |
| A | 1.0 |
| C | NaN |
Python Basics 68
| B | 0.0 |
| A | 1.0 |
Note: The .apply which is very similar to map function, but it is typically used
with Pandas DataFrames:
filter function:
The filter function returns an iterator yielding those items of iterable for which
function(item) is true. Meaning you need to filter by a function that returns
either True or False. Then passing that into filter (along with your iterable) and
you will get back only the results that would return True when passed to the
function.
def check_even(num):
return num % 2 == 0
nums = [0,1,2,3,4,5,6,7,8,9,10]
filter(check_even,nums)
list(filter(check_even,nums))
>>> [0, 2, 4, 6, 8, 10]
lambda expression:
lambda expressions allow us to create "anonymous" functions.
This basically means we can quickly make ad-hoc functions without needing
to properly define a function using def.
lambda's body is a single expression, not a block of statements. lambda is
designed for coding simple functions, and def handles the larger tasks.
Python Basics 69
square(2)
>>> 4
square(2)
>>> 4
square(2)
>>> 4
square(2)
>>> 4
So why would use this? Many function calls need a function passed in, such
as map and filter. Often you only need to use the function you are passing in
once, so instead of formally defining it, you just use the lambda expression.
Python Basics 70
my_nums = [1,2,3,4,5]
nums = [0,1,2,3,4,5,6,7,8,9,10]
list(filter(lambda n: n % 2 == 0,nums))
>>> [0, 2, 4, 6, 8, 10]
Here are a few more examples, keep in mind the more comples a function is,
the harder it is to translate into a lambda expression, meaning sometimes its
just easier (and often the only way) to create the def keyword function.
# You can even pass in multiple arguments into a lambda expression. Agai
n, keep in mind that not every function can be translated into a lambda ex
pression.
# Addition
lambda x,y : x + y
x = 25
Python Basics 71
def printer():
x = 50
return x
# print(x)
# print(printer())
# What do you imagine the output of printer() is? 25 or 50? What is the out
put of print x? 25 or 50?
print(x)
>>> 25
print(printer())
>>> 50
Interesting! But how does Python know which x you're referring to in your
code? This is where the idea of scope comes in. Python has a set of rules it
follows to decide what variables (such as x in this case) you are referencing in
your code. Lets break down the rules:
local
enclosing functions
global
built-in
Python Basics 72
LEGB Rule:
L: Local — Names assigned in any way within a function (def or lambda), and
not declared global in that function.
E: Enclosing function locals — Names in the local scope of any and all
enclosing functions (def or lambda), from inner to outer.
G: Global (module) — Names assigned at the top-level of a module file, or
declared global in a def within the file.
B: Built-in (Python) — Names preassigned in the built-in names module : open,
range, SyntaxError,...
# x is local here:
f = lambda x:x**2
f(2)
>>> 4
def greet():
# Enclosing function
name = 'Sammy'
def hello():
print('Hello '+name)
Python Basics 73
hello()
greet()
>>> Hello Sammy
# Note how Sammy was used, because the hello() function was enclo
sed inside of the greet function!
G: Global
Luckily in Jupyter a quick way to test for global variables is to see if
another cell recognizes the variable!
print(name)
>>> This is a global name
B: Built-in
These are the built-in function names in Python (don't overwrite these!)
len
>>> <function len>
Local Variables:
If we want to use the global variable (global x = 50 in given example), we
simply pass the variable in function as an argument.
for example def func( x ) , here x is global.
But, we can also reassign variable inside the function at the same time(the
reassignment will be limited to only for the function), and use the variable as
shown in example below.
Example:
x = 50 # Global x
Python Basics 74
def func(x):
print('x is', x)
# LOCAL REASSIGNMENT
x = 2 # Local x
print('Changed local x to', x)
func(x)
print('x is still', x)
>>> x is 50
Changed local x to 2
x is still 50
x = 50 # Global x
func()
print('x is now', x)
>>> x is 50
Changed local x to 2
Python Basics 75
x is now 2
print(x)
>>> 2
# Notice that the reassignment is now on global level, and value of x is no
w change to 2 (from 50 on global level)
x = 50
print(x)
>>> 50
func(x)
>>> x is 50
Changed local x to 2
x is now 2
print(x)
>>> 2
Python Basics 76
In Python, "packages," "modules," and "libraries" are related concepts, but they
refer to different things in the context of organizing and structuring code:
Module:
Modules allow you to import functions and variables from one file into
another, providing reusability and better structure.
Examples:
# math_ops.py
def add(a, b):
return a + b
Package:
Python Basics 77
my_package/
├── __init__.py
├── math_ops.py
└── string_ops.py
You can import and use the modules within the package like this:
# OR
Library:
A library is a collection of modules and/or packages that provide specific
functionalities.
Libraries are larger units of code designed to be reusable across different
projects.
They often contain a set of related functionalities, making it easier for
developers to perform common tasks without reinventing the wheel.
Example:
The requests library for making HTTP requests is a collection of modules that
simplify the process of interacting with web servers.
import requests
response = [Link]("[Link]
print([Link])
Python Basics 78
Package Installer
A package installer in Python is a tool or software that facilitates the installation,
management, and removal of Python packages. Python packages are collections
of code, modules, and resources that provide specific functionalities and can be
easily distributed and reused.
There are a plenty of package installers available, the most common one is pip.
Pip
Explanation:
pip is the package installer for Python, used to manage Python packages and
libraries. It simplifies the process of downloading and installing packages from
the Python Package Index (PyPI) and other repositories.
Here are some commonly used pip commands to use in cmd:
# Installing a Package:
pip install package_name
# Uninstalling a Package:
pip uninstall package_name
# Updating a Package:
pip install --upgrade package_name
Alternatives to pip:
Python Basics 79
conda
easy_install
virtualenv
poetry
Python Basics 80