0% found this document useful (0 votes)
36 views80 pages

Python Basics: A Comprehensive Guide

Python tutorial
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
0% found this document useful (0 votes)
36 views80 pages

Python Basics: A Comprehensive Guide

Python tutorial
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

Python Basics

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

Basics & Setup


Command Line Basics (Windows):
CODE:

# show the current directory


cd

# List files and folders in the current directory


dir

# Change the current directory (hit 'Tab' to Autocomplete)


cd <directory_path>

# Move back from the current directory

Python Basics 3
cd ..

# Clear the console screen


cls

----------------------------------------------------------------------------
------

# Copy files or directories


copy <source> <destination>

# Delete files
del <file_path>

# Create a new directory


mkdir <directory_name>

# Remove a directory (empty directories only)


rmdir <directory_name>

# Rename a file or directory


ren <old_name> <new_name>

# Display the contents of a text file


type <file_name>

# Display messages on the screen or redirect output


echo <message>

# Move files or directories from one location to another


move <source> <destination>

# Display help information about commands


help

# Display network configuration information

Python Basics 4
ipconfig

# Check the connectivity to a network host


ping <host_name_or_ip>

# Display a list of currently running processes


tasklist

# Terminate a running process


taskkill /F /IM <process_name>

#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.

Running Python Code on CMD


CODE:

# 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

# run folling command to directly type code on the command line


python

# use to quit
quit()

Python Basics 5
No Install Options for Notebooks
[Link]/try

Google Collab Notebook

[Link] (Paid)

Google Search

“Python Interpreters Online”

Types of Integrated Development Environments (IDE)


Text Editors

Sublime Text

Atom

VS Code

Full IDE

PyCharm

Spyder

Notebook Environments

Jupyter Notebook

Google Collab Notebook

Execute Shell Commands from within an Environment


In a command-line interface or terminal, the ‘ ! ’ symbol is used to execute shell
commands from within the environment where the Python interpreter is running.
For example !pip install <name_of_library>

Python Object and Data Structure Basics


Objects & Data Structure types

Python Basics 6
Type Example Description

Objects:

Integer: Whole numbers without


int 3, 300, 200,-5
decimal points.

Floating point: Numbers with decimal


float 3.14, 15.0, -5.1, 2e2
points.

str
"Hello", “What?”, “ かまど”, String: Sequence of characters
“2000” enclosed in quotes.

Data Structures:

List: Ordered, mutable collection of


list [10, “Hello” , 20.3]
elements.

{"key1": "value1", "key2": Dictionary: Unordered collection of


dict
"value2"} key-value pairs.

Tuple: Ordered, immutable collection


tuple (10, “Hello” , 20.3)
of elements.

Set: Unordered collection of unique


set {1, 2, 3}
elements.

Boolean: Represents True or False


bool True or False
values.

Creating Object & Data Structure

# 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)

# we create any Data Structure using constructor or literal notation as shown


below.

# 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

# Modulo or Mod, The % operator returns the remainder after division.


7%4

# Powers
2**3

# Can also do roots this way


4**0.5

#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:

1. Names can not start with a number.

2. There can be no spaces in the name, use _ instead.

3. Can't use any of these symbols :'",<>/?|\()!@#$%^&*~-+

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

# Deleting a variable assignment using del keyword.

a = 20

print(a)
>>> 20

del a

# here the 'a' is no longer assigned to some value.


print(a)
>>> NameError: name 'a' is not defined

Python Basics 10
Strings
1. Creating & Printing Strings
CODE:

# Strings can be created by single quote or double quote


"String built with double quotes"
"I'm using double quotes"

#Represents a newline character


"\n"

#Represents a tab character


"\t"

# to check the length of a string


len('Hello World')

2. String Indexing and Slicing


In Python, we use brackets [] after an object to call its index. The number inside
the bracket is the position of what we wish to grab.

CODE:

# Indexing

# Assign s as a string
s = 'Hello World'

# Show first element (in this case a letter)


s[0]
>>> 'H'

Python Basics 11
s[1]
>>> 'e'

We can use slicing to grab a subsection from a object.


slicing syntax object[start:stop:step]

# Slicing

# We can use a : to perform slicing which grabs everything up to a design


ated point.

# Grab everything past the first term all the way to the length of s which is
len(s)
s[1:]
>>> 'ello World'

# Grab everything UP TO the 3rd index, 3rd index is not included.


s[:3]
>>> 'Hel'

#Everything
s[:]
>>> 'Hello World'

# Negative Indexing
# Last letter
s[-1]
>>> 'd'

# Grab everything but the last letter


s[:-1]
>>> 'Hello Worl'

# Step Size

Python Basics 12
# Grab everything, but go in steps size of 1
s[::1]
>>> 'Hello World'

# Grab everything, but go in step sizes of 2


s[::2]
>>> 'HloWrd'

# We can use this to print a string backwards


s[::-1]
>>> 'dlroW olleH'

3. String Properties
CODE:

s = 'Hello World'

# Let's try to change the first letter to 'x'


s[0] = 'x'
>>> TypeError

# String Concatenation
s + ' concatenate me!'
>>> 'Hello World concatenate me!'

# multiplication symbol to create repetition!


letter = 'z'

letter*10
>>> 'zzzzzzzzzz'

4. String Methods
The Python method syntax is [Link](parameters)

Python Basics 13
CODE:

s = 'Hello World concatenate me!'

# Upper Case a string


[Link]()

# Lower case
[Link]()

# Split a string by blank space (this is the default)


[Link]()
>>> ['Hello', 'World', 'concatenate', 'me!']

# 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:

# [Link] Formatting with % Operator:


name = "John"
age = 25
print("My name is %s and I am %d years old." % (name, age))

# %s is a placeholder for a string (used for the variable name).


# %d or %i is a placeholder for an integer (used for the variable age).

# %f: Floating-point decimal.


# %.nf: Floating-point decimal with n digits after the decimal point.
# %x or %X: Hexadecimal representation (lowercase or uppercase, respe

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))

# [Link] F-String Literals:


name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")

Lists
1. Creating lists
Unlike strings, Lists are mutable, meaning the elements inside a list can be
changed.

CODE:

# Assign a list to an variable named my_list


my_list = [1,2,3]

my_list = ['A string',23,100.232,'o']

# Just like strings, the len() function will tell you how many items are in the
sequence of the list.
len(my_list)
>>> 4

2. Indexing and Slicing Lists


Indexing and slicing work just like in strings.

Python Basics 15
CODE:

my_list = ['one','two','three',4,5]

# Grab index 1 and everything past it


my_list[1:]
>>> ['two', 'three', 4, 5]

# use + to concatenate lists


my_list + ['new item']
>>> ['one', 'two', 'three', 4, 5, 'new item']
# NOTE: This doesn't actually change the original list!

# reassign the list to make the change permanent.


my_list = my_list + ['add new item permanently']
my_list
>>> ['one', 'two', 'three', 4, 5, 'add new item permanently']

# use the * for a duplication method similar to strings


my_list * 2
>>> ['one',
'two',
'three',
4,
5,
'add new item permanently',
'one',
'two',
'three',
4,
5,
'add new item permanently']

# Again doubling not permanent, usless reassigned.

Python Basics 16
3. Basic List Methods
CODE:

list1 = [1,2,3]

# [Link] - Use the append method to permanently add an item to the e


nd of a list:
[Link]('append me!')

# [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 reverse to reverse order (this is permanent!)


[Link]()

# [Link] - Use sort to sort the list (in this case alphabetical order, but for n
umbers it will go ascending)
[Link]()

# [Link] - Use .count to count the number of times a value appears


[Link](1)

4. Nesting Lists
Nesting means we can have data structures within data structures. For example: A
list inside a list.

CODE:

# Let's make three lists


lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]

# Make a list of lists to form a matrix

Python Basics 17
matrix = [lst_1,lst_2,lst_3]

matrix
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# indexing for Nested lists

matrix[0]
>>> [1, 2, 3]

matrix[0][0]
>>> 1

5. Introduction to List Comprehensions


List comprehensions in Python provide a concise and expressive way to create
lists. They allow you to generate lists by applying an expression to each item in an
iterable (such as a list, tuple, or range) and optionally including conditions.

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]]

first_col = [row[2] for row in matrix]


first_col
>>>[3, 6, 9]

# [Link] a list of squared numbers from 0 to 4.

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:

# Make a dictionary with {} and : to signify a key and a value


my_dict = {'key1':'value1','key2':'value2'}

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'

# methods on values in a dictionaty

my_dict['key3'][0].upper()
>>> 'ITEM0'

# We can affect the values of a key as well. For instance:

Python Basics 19
my_dict['key1']
>>> 123

# Subtract 123 from the value


my_dict['key1'] = my_dict['key1'] - 123

my_dict['key1']
>>> 0

# We can also create keys by assignment.


# For instance if we started off with an empty dictionary, we could continu
ally add to it:

my_dict2 = {}

my_dict2['animal'] = 'Dog'
my_dict2['answer'] = 42

my_dict2
>>> {'animal': 'Dog', 'answer': 42}

2. Nesting Dictionaries
CODE:

# Dictionary nested inside a dictionary nested inside a dictionary


d = {'key1':{'nestkey':{'subnestkey':'value01'}}}

# Keep calling the keys


d['key1']['nestkey']['subnestkey']
>>> 'value01'

3. Basic Dictionary Methods


CODE:

Python Basics 20
# Each of these methods return a dictionary view object

d = {'key1':1,'key2':2,'key3':3}

# 1. Keys - Method to return a list of all keys

[Link]()
>>> dict_keys(['key1', 'key2', 'key3'])

# 2. Values - Method to return a list of all values

[Link]()
>>> dict_values([1, 2, 3])

# 3. Items - Method to return tuples of all items

[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)

# Use indexing just like we did in lists


t[0]
>>> 'one'

# Slicing just like a list


t[-1]
>>> 2

2. Basic Tuple Methods


CODE:

# [Link] - Use .index to enter a value and return the index


[Link]('one')
>>> 0

# [Link] - Use .count to count the number of times a value appears


[Link]('one')
>>> 1

3. Immutability
CODE:

# tuples are immutable.

t[0]= 'new value'


>>> TypeError

# Because of this immutability, tuples can't grow. Once a tuple is made we


can not add to it.

Python Basics 22
[Link]('nope')
>>> AttributeError

4. When to Use Tuples


You may be wondering, "Why bother using tuples when they have fewer available
methods?" To be honest, tuples are not used as often as lists in programming, but
are used when immutability is necessary. If in your program you are passing
around an object and need to make sure it does not get changed, then a tuple
becomes your solution. It provides a convenient source of data integrity.

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()

# Add Method - We add to sets with this method.


[Link](1)

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]

# Cast as set to get unique values


set(list1)
>>> {1, 2, 3, 4, 5, 6}

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:

# Set object to be a boolean


a = True

a
>>> True

# We can also use comparison operators to create booleans.

# Output is boolean
1>2
>>> False

# None placeholder - We can use None as a placeholder for an object that


we don't want to reassign yet:

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.

1. Function to create a text file

# (this function is specific to jupyter notebooks only)

%%writefile <file_name>.txt
Hello, this is a quick test file. # write content of the text file

2. Function to opening a file

# the open() function will only allow us to read the 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]")

3. Function to check your notebook location

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:

# Seek to the start of file (index 0)


my_file.seek(0)
>>> 0

# Now read again


my_file.read()
>>> 'Hello, this is a quick test file.'

6. Read lines Method

# 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.

# Readlines returns a list of the lines in the file


my_file.seek(0)
my_file.readlines()
>>> ['Hello, this is a quick test file.','2nd line']

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.

# Add a second argument to the function.


# 'w' - stands for write.
# 'w+' - stands for read and write.

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!

# Write to the file


my_file.write('This is a new line')

# Read the file


my_file.seek(0)
my_file.read()
>>> 'This is a new line'

10. Appending to a file

# Add a second argument to the function.


# 'a' - this opens the file and puts the pointer at the end, so anything writt
en is appended.
# 'a+' - Like 'w+', 'a+' lets us read and write to a file. If the file does not ex
ist, one will be created.

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.

my_file.close() # To close the file

# Appending with %%writefile - (Jupyter Notebool only method)

%%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.

Operator Description Example

If the values of two operands are equal,


== (a == b) is not true.
then the condition becomes true.

If values of two operands are not equal,


!= (a != b) is true
then condition becomes true.

If the value of left operand is greater than


> the value of right operand, then condition (a > b) is not true.
becomes true.

If the value of left operand is less than the


< value of right operand, then condition (a < b) is true.
becomes true.

>= 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.

If the value of left operand is less than or


<= equal to the value of right operand, then (a <= b) is true.
condition becomes true.

CODE:

# [Link]

2 == 2
>>> True

1 == 0
>>> False

# Note that == is a comparison operator, while = is an assignment operato


r.

# [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

# [Link] Than or Equal to

2 >= 2
>>> True

2 >= 1
>>> True

# [Link] than or Equal to

2 <= 2
>>> True

2 <= 4
>>> True

Chained Comparison Operators:


An interesting feature of Python is the ability to chain multiple comparisons to
perform a more complex test. Here we are also using python statements such as
and and or .

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:

1<2 and 2<3


>>> True

# similarly

# Example 2

1<3>2
>>> True

1<3 and 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

1=1 and 2=1


>>> False

OR:

# The or used to make sure only one or the other to be true

1=1 and 2=2


>>> True

1=1 and 2=1


>>> True

1=2 and 2=1


>>> False

2. if, elif and else


Statements in Python allows us to tell the computer to perform alternative
if

actions based on a certain set of results.


Syntax format for if statements:

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!

# if, else statement

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

# if, elif & else statement - Multiple Branches

loc = 'Bank'

if loc == 'Auto Shop':


print('Welcome to the Auto Shop!')
elif loc == 'Bank':
print('Welcome to the bank!')
else:
print('Where are you?')
>>> Welcome to the 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:

for item in object:


statements to do stuff

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:

Example 1 - Iterating through a list

list1 = [1,2,3,4,5,6,7,8,9,10]

for num in list1:


print(num)

Python Basics 34
>>> 1
2
3
4
5
6
7
8
9
10

Example 2 - Use Modulo to check for even numbers

# Modulo returns remainder of the division.


10 % 3
>>> 1

# print only the even numbers from list1


for num in list1:
if num % 2 == 0:
print(num)
>>> 2
4
6
8
10

# Use an else statement


for num in list1:
if num % 2 == 0:
print(num)
else:
print('Odd number')
>>> Odd number
2
Odd number

Python Basics 35
4
Odd number
6
Odd number
8
Odd number
10

Example 3 - running tally during multiple loops

# for loop that sums up the list


# Start sum at zero
list_sum = 0

for num in list1:


list_sum = list_sum + num #(alternative method to add is 'list_sum += n
um' )

print(list_sum)
>>> 55

Example 4 - Iterating through a string

for letter in 'This is a string.':


print(letter)
>>> T
h
i
s

i
s

Python Basics 36
t
r
i
n
g

Example 5 - Iterating through a tuple

tup = (1,2,3,4,5)

for t in tup:
print(t)
>>> 1
2
3
4
5

# Example 6 - Iterating through a sequence of tuple - (same works with


sequence if list)

# this is an example of tuple unpacking

list2 = [(2,4),(6,8),(10,12)]

for tup in list2:


print(tup)
>>> (2, 4)
(6, 8)
(10, 12)

# Now with unpacking!


for (t1,t2) in list2:
print(t1)
>>> 2

Python Basics 37
6
10

Example 7 - iterating through dictionaries

d = {'k1':1,'k2':2,'k3':3}

# returns only keys


for item in d:
print(item)
>>> k1
k2
k3

# Using dictionaries methods like .keys(), .values() and .items()


# It supports operations like membership test and iteration, but its content
s are not independent of the original dictionary – it is only a view.

# Create a dictionary view object


[Link]()
>>> dict_items([('k1', 1), ('k2', 2), ('k3', 3)])

# The .items() method supports iteration, we can perform dictionary unpa


cking to separate keys and values
for k,v in [Link]():
print(k)
print(v)
>>> 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

while x < 10:


print('x is currently: ',x)
print(' x is still less than 10, adding 1 to x')
x+=1
>>> 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

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

Example 2: Using else statement

x=0

while x < 10:


print('x is currently: ',x)
print(' x is still less than 10, adding 1 to x')
x+=1

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!

Example 3: Using break , continue , pass

We can use break , continue , and pass statements in our loops to add additional
functionality for various cases. The three statements are defined by:

break: Breaks out of the current closest enclosing loop.


continue: Goes to the top of the closest enclosing loop.
pass: Does nothing at all.

Thinking about break and continue statements, the general format of


the while loop looks like this:

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

while x < 10:


print('step 1')
print('step 2')
x+=1
if x==3:
print('statement IF')
else:
print('statement ELSE')
continue
>>> step 1
step 2
statement ELSE
step 1
step 2
statement ELSE
step 1
step 2
statement IF
step 1
step 2
statement ELSE
step 1
step 2
statement ELSE
step 1
step 2
statement ELSE

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

Example with break

x=0

while x < 10:


print('x is:',x)
x+=1
if x==3:
print('Breaking because x==3')
break
else:
print('continuing...')
continue
>>> x is: 0
continuing...
x is: 1
continuing...
x is: 2
Breaking because x==3

# 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:

# DO NOT RUN THIS CODE!!!!


while True:
print("I'm stuck in an infinite loop!")

# 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.

# Notice how 11 is not included, up to but not including 11


list(range(0,11))
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 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.

# Let's imagine the following situation

index_count = 0

for letter in 'abcde':


print("At index {} the letter is {}".format(index_count,letter))
index_count += 1
>>> At index 0 the letter is a
At index 1 the letter is b
At index 2 the letter is c
At index 3 the letter is d
At index 4 the letter is e

# Keeping track of how many loops you've gone through is so common,


# that enumerate was created so you don't need to worry about creating a
nd updating this index_count or loop_count variable

# Notice the tuple unpacking!


for i,letter in enumerate('abcde'):
print("At index {} the letter is {}".format(i,letter))
>>> At index 0 the letter is a
At index 1 the letter is b
At index 2 the letter is c
At index 3 the letter is d
At index 4 the letter is e

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']

# This one is also a generator.


# transform two list in to one.

zip(mylist1,mylist2)
>>> <zip at 0x1d205086f08>

list(zip(mylist1,mylist2))
>>> [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

# To use the generator, we could just use a for loop

for item1, item2 in zip(mylist1,mylist2):


print('For this tuple, first item was {} and second item was {}'.format(ite
m1,item2))
>>> For this tuple, first item was 1 and second item was a
For this tuple, first item was 2 and second item was b
For this tuple, first item was 3 and second item was c

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.

'x' not in ['x','y','z']


>>> False

'x' not in [1,2,3]


>>> True

6. min and max


Quickly check the minimum or maximum of a list with these functions.

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

# This shuffles the list "in-place" meaning it won't return


# anything, instead it will effect the list passed
shuffle(mylist)

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

# we can input any values in the box

input('Enter Something into this box: ')


>>> Enter Something into this box:
|----------------------------|

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

# Grab every letter in string


lst = [x for x in 'word']

lst
>>> ['w', 'o', 'r', 'd']

Example 2

# Square numbers in range and turn into list


lst = [x**2 for x in range(0,11)]

lst
>>> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example 3:
Let's see how to add in if statements:

# Check for even numbers in a range


lst = [x for x in range(11) if x % 2 == 0]

Python Basics 49
lst
>>> [0, 2, 4, 6, 8, 10]

Example 4:
More complicated arithmetic:

# Convert Celsius to Fahrenheit


celsius = [0,10,20.1,34.5]

fahrenheit = [((9/5)*temp + 32) for temp in celsius ]

fahrenheit
>>> [32.0, 50.0, 68.18, 94.1]

Example 5:
Nested list comprehensions

lst = [ x**2 for x in [x**2 for x in range(11)]]

lst
>>> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]

Methods and Functions


Python built in functions and methods identification:

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]

# here len() is a built-in function. with function we have to pass in variable na


me.
len(my_list)

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

Let's try out a few of them:

# Create a simple list


lst = [1,2,3,4,5]

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]

# count - it method will count the number of occurrences of an element in


a list
# Check how many times 2 shows up in the list
[Link](2)
>>> 1

# 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 Built-in Functions:


List of functions

abs(): Returns the absolute value of a number.


all(): Returns True if all elements of the iterable are true.
any(): Returns True if any element of the iterable is true.
bin(): Converts an integer to a binary string.
bool(): Converts a value to a Boolean.
chr(): Returns a string representing a character whose Unicode code point
is the integer.
id(): Returns the identity (memory address) of an object.
len(): Returns the length of an object.
max(): Returns the largest item in an iterable or the largest of two or more
arguments.
min(): Returns the smallest item in an iterable or the smallest of two or mor
e arguments.
ord(): Returns an integer representing the Unicode character.
range(): Returns a sequence of numbers.
sum(): Returns the sum of all items in an iterable.
str(): Converts an object to a string.
type(): Returns the type of an object.
zip(): Returns an iterator of tuples, where the i-th tuple contains the i-th el
ement from each of the argument sequences.
help(<name_of_function>): Returns documentation of that function or mod
ule.
sorted(): It takes an iterable and returns a new sorted list (or sorted iterabl
e).

to_clipboard(): Write DataFrame to the clipboard.


to_csv(): Write DataFrame to a comma-separated values (csv) file.
to_datetime(): Convert argument to datetime.
to_dict(): Convert DataFrame to dictionary.

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.

Python Official documentation:

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]

Making New Functions (Topics):


def keyword

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.

Simple example of a function

def say_hello():
print('hello')

Calling a function with ()

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>

Accepting parameters (arguments)


A function that greets people with their name.

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

# Can also save as variable due to return


result = add_num(4,5)

print(result)
>>> 9

# if we input two strings

Python Basics 56
add_num('one','two')
>>> 'onetwo'

The difference between return and print

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

Save this result for later use with print .

my_result = print_result(10,5)
>>> 15

# this doens't return anything


my_result
>>> _ _ _ _

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

Adding in logic inside a function


Logical statements such as if/else/elif statements, for and while loops,
checking if an item is in a list or not in a list (Useful Operators Lecture). Let's
now see how we can perform these operations within a function.
Check if a number is even:
The mod operator % which returns the remainder after division, if a number is
even then mod 2 (% 2) should be == to zero.

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

Adding in loops inside a function:


Check if any number in a list is even
Let's return a Boolean indicating if any number in a list is even. Notice here
how return breaks out of the loop and exits the function.

# 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])
>>> _ _ _ _

# We're not returning anything if they are all odds!

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

# UH OH! It is returning False after hitting the first 1


check_even_list([1,2,3])
>>> 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

Return all even numbers in a list:

def check_even_list(num_list):

even_numbers = []

# Go through each number


for number in num_list:
# Once we get a "hit" on an even number, we append the even numb
er
if number % 2 == 0:
even_numbers.append(number)
# Don't do anything if its not even
else:
pass
# Notice the indentation! This ensures we run through the entire for loo
p
return 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)]

for item in stock_prices:


print(item)
>>> ('AAPL', 200)
('GOOG', 300)
('MSFT', 400)

for stock,price in stock_prices:


print(stock)
>>> AAPL
GOOG
MSFT

for stock,price in stock_prices:


print(price)
>>> 200
300
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):

# Set some max value to intially beat, like zero hours


current_max = 0
# Set some empty value before the loop
employee_of_month = ''

for employee,hours in work_hours:

Python Basics 62
if hours > current_max:
current_max = hours
employee_of_month = employee
else:
pass

# Notice the indentation here


return (employee_of_month,current_max)

employee_check(work_hours)
>>> ('Cassie', 800)

Interactions between functions


Functions often use results from other functions, let's see a simple example
through a guessing game. There will be 3 positions in the list, one of which is
an 'O', a function will shuffle the list, another will take a player's guess, and
finally another will check to see if it is correct. This is based on the classic
carnival game of guessing which cup a red ball is under.

from random import shuffle

mylist = [' ','O',' ']

# Function 1 - Take in list, and returned shuffle versioned


def shuffle_list(mylist):
shuffle(mylist)

return mylist

# Function 2 - asks player input guess until its in ['0','1','2']


def player_guess():

guess = ''

while guess not in ['0','1','2']:

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)

# Combine all 3 Function in a code - a logic to run all the functions

# Initial List
mylist = [' ','O',' ']

# Function 1 - Shuffle It
mixedup_list = shuffle_list(mylist)

# Function 2 - Get User's Guess


guess = player_guess()

# Function 3 - Check User's Guess


#------------------------
# Notice how this function takes in the input
# based on the output of other functions!
check_guess(mixedup_list,guess)

>>>

*args and **kwargs

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

Here the function returns 5% of sum a + b, but what if we want more


positional arguments in the function, one way to do it is,

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

but, this is not efficient.


Here we use *args , When a function parameter starts with an asterisk, it
allows for an arbitrary number of arguments, and the function takes them in as
a tuple of values. Rewriting the above function:

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

*args and **kwargs combined:


You can pass *args and **kwargs into the same function, but *args have to
appear before **kwargs .

def myfunc(*args, **kwargs):


if 'fruit' and 'juice' in kwargs:
print(f"I like {' and '.join(args)} and my favorite fruit is {kwargs['frui

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?

Placing keyworded arguments ahead of positional arguments raises an


exception:

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.

Lambda Expressions, Map, and Filter


map function:

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)

# To get the results, either iterate through map()

Python Basics 67
# or just cast to a list
list(map(square,my_nums))

More complex functions

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

# Sample Pandas DataFrame


df
>>> | Category |
0| A |
1| B |
2| A |
3| C |
4| B |
5| A |

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.

# Step 1: Lets slowly break down a lambda expression by deconstructing a


function:
def square(num):
result = num**2
return result

Python Basics 69
square(2)
>>> 4

# Step 2: We could simplify it:


def square(num):
return num**2

square(2)
>>> 4

# Step 3: We could actually even write this all on one line.


def square(num): return num**2

square(2)
>>> 4

# The lambda expression


# This is the form a function that a lambda expression intends to replicate.
# A lambda expression can then be written as:

lambda num: num ** 2


>>> <function __main__.<lambda>>

# You wouldn't usually assign a name to a lambda expression, this is just f


or demonstration!
square = lambda num: num **2

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(map(lambda num: num ** 2, my_nums))


>>> [1, 4, 9, 16, 25]

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.

# Lambda expression for grabbing the first character of a string:


lambda s: s[0]

# Lambda expression for reversing a string:


lambda s: s[::-1]

# 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

Nested Statements and Scope:


It is important to understand how Python deals with the variable names you
assign. When you create a variable name in Python the name is stored in
a name-space. Variable names also have a scope, the scope determines the
visibility of that variable name to other parts of your code.
Let's start with a quick thought experiment; imagine the following code:

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:

In simple terms, the idea of scope can be described by 3 general rules:

1. Name assignments will create or change local names by default.

2. Name references search (at most) four scopes, these are:

local

enclosing functions

global

built-in

3. Names declared in global and nonlocal statements map assigned


names to enclosing module and function scopes.

The statement in #2 above can be defined by the LEGB rule.

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,...

Quick examples of LEGB:


L: Local

# x is local here:
f = lambda x:x**2

f(2)
>>> 4

E: Enclosing function locals


This occurs when we have a function inside a function (nested functions)

name = 'This is a global name'

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

# here the scope of variable x as 2 is limited to the function.

The global statement:


If u want to change a global variable by reassigning it to a different value, but
inside a function. This can be done with global statement.
In given code the global x tells the python that whatever code runs after this
should jump to the global level and grab x there.

x = 50 # Global x

def func(): # here we dont pass x in function, we insted declear x as globa


l in 2nd line of code.
global x
print('x is', x)
# LOCAL REASSIGNMENT ON A GLOBAL VARIABLE
x = 2 # Local x
print('Changed local x to', 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)

We should avoid using global statement, because it affects the readability of


the code, instead we can return the result from the function and then reassign
to the global variable as shown in below

x = 50

def func(x): # x is passed in the function


print('x is', x)
x=2
print('Changed local x to', x)
return x

print(x)
>>> 50

func(x)
>>> x is 50
Changed local x to 2
x is now 2

print(x)
>>> 2

Installing Packages, Modules & Libraries in


python

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:

A module is a single Python file ( .py file) containing definitions, functions,


classes, and variables. It helps organize code into reusable pieces. For
example, if you have a file named math_ops.py with functions to perform
mathematical operations, that file is considered a 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

def subtract(a, b):


return a - b

You can import and use the functions like this:

from math_ops import add, subtract


result = add(5, 3)

Package:

A package is a collection of modules organized in a directory. The


directory must contain an __init__.py file (which can be empty or contain
initialization code) to be recognized as a package. This structure helps
organize code across multiple related modules.

A package can have sub-packages, allowing for even more granular


organization of code. It can help manage larger codebases with many
interrelated modules.
Directory structure example:

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:

from my_package.math_ops import add


from my_package.string_ops import concatenate

# OR

from my_package import math_ops


math_ops.add()

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])

# We can also import libraries with a short-form of their names like:


import pandas as pd

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

# Listing Installed Packages:


pip list

# Updating a Package:
pip install --upgrade package_name

# Installing Packages from a Requirements File:


pip install -r [Link]

# Freezing Installed Packages:


pip freeze > [Link]

Alternatives to pip:

Python Basics 79
conda
easy_install
virtualenv
poetry

Python Basics 80

You might also like