Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Azure
GitHub Repository: Azure/Azure-Sentinel-Notebooks
Path: blob/master/tutorials-and-examples/training-notebooks/A Python Crash Course - Part 1 - Fundamentals.ipynb
3253 views
Kernel: Python 3.6 - AzureML

Python Crash Course - Part 1 - Fundamentals

Python

author

Requires version

Introduction

This 📔 notebook takes you through the 👨‍🎓 learning the basic fundamentals of Python. Its an 👩‍💻 interactive self-paced tutorial within notebook. This course will have you learning variables, data types, loops in no time. 😋

Table of Contents

  • Getting Started

  • Variables

  • Data Types

  • Collections

  • Block Indentation

Note Be sure to click the table of contents under Menu -> View -> TOC to easily navigate the notebook.

Additional Resources

Getting Started

If you haven't already, you may want to understand how to use Jupyter notebooks and more specifically Azure Notebooks by using this guide "Getting Started with Azure ML Notebooks and Microsoft Sentinel"

docs

Note The order on when you run the each cells are important. Some cells will have a dependency on another cell in order to work.
Make sure you identify if the cell requires other cells to run, otherwise you may run into errors.

Keyboard Shortcuts
keydescription
🔼🔽Up/Down keys will navigate cell blocks
aAdd a cell above highlighted cell
bAdd a cell below highlighted cell
d dDelete a cell
cCopy a cell into clipboard
xCut a cell into clipboard
vPaste a cell below selected cell
zUndo your boo boo
EnterEdit a cell
EscapeEscape current cell in order to navigate
Ctrl + EnterRuns current cell and stays on the current cell.
Shift + EnterRuns current cell and moves once cell down after running
mConvert current cell to markdown cell format
yConvert current cell to code cell format

Use your table contents to quickly browse to certain topics or areas of interest.

Lets get 😎fancy by showing you how to quickly navigate a notebook. You will notice that in whatever cell your working in, it is highlighted indicating its your current or selected cell.

Try

  • 🗺 Navigating - So lets press the escape key and navigate up and down by using our arrows 🔼 🔽

  • ➕ Adding Cells - Now, lets hit the a or b key. This will either add a cell above/below your currently selected cell when navigating.

  • ❌ Deleting - Highlight any cell when you are navigating and then press d d. (Make sure you aren't editing a cell escape)

  • 📝 Editing - To edit a cell, just navigate to the cell and press enter which puts you in edit mode.

  • ✂ Cutting/Pasting - Highlight a cell and press c or x to copy/cut a cell. Then navigate to where you want to paste it and press v which will paste the cell below your selected/currentEditing - To edit a cell, just navigate to the cell and press enter which puts you in edit mode.

  • Undo - Oops, you made a mistake? 😓 Press z to undo that boo boo 💩.

☝ Above is a helpful reference guide. Try to get familiar with the ⌨ keyboard shortcuts to help you navigate, add, copy, paste, delete, and run cells.

Exercise Think you can try navigating the rest of the notebook without using your mouse 🐭 at all.
Remember to navigate using your arrows 🔼 🔽 and the enter/escape key to enter/exit a cell.

👋🏾 Hello World

In the code cell below, enter "Hello World" enclosed in some quotation marks.

"Hello World"

This simply just prints/output the input you provided which was enclosed double quotes ".

"Hello Jing"

But sometimes, you may want to print multiple outputs and control/modify the output. So more often you will utilize the print function. print("Hello World")

print("Hello World")

Exercise Can you modify Hello World and print something else out?

print("Hello World") print("Hello Jing")

Cell types

📓 Notebook cells can be in two different formats, markdown or code cells.

  • 📃 Markdown - allows you to comment and document your notebook

    • Markdown Guide - The Markdown Guide is a free and open-source reference guide that explains how to use Markdown to format virtually any document.

  • 👩🏾‍💻 Code Cells - code cells are the actual runnable code.

Exercise

  • Press the escape key to ensure you are not editing a code cell and then press either m or y to convert a cell to either format.

  • How would you add a code cell below this cell and convert it to a markdown cell using what shortcuts you have learned, ?

Comments

You will want to make it a habit to comment your code so you and others can otherstand what its purpose is.

Single line comments is using a # character and any following string after will be ignored

# This is a single line comment. print ("Hello")
# This is a single line comment and will be ignored print ("Hello")

Using Help

The python help🆘 function is used to display the documentation of modules, functions, classes, keywords, etc.

syntax

help([object])

syntax

help(print)
help("print")

Importing modules

A module is a file containing Python definitions and statements. There will be times you need to do something specific and most likely someone has already created a module you can use. In most cases you can save alot of time if there is a module that already exists you can leverage to help you get to your desired outcome faster 🚀. And who doesn't like to save time ⌚.

👍 Make sure package is installed

If you ever want to use a module, you first must install it. The most common way is to use a native package manager like pip to install the module so you can import it. Remember you can't use what you don't have!

Most of the time to install any module, you can reference the name your trying to import.

!pip install <package_name> # Example: !pip install numpy
!pip install numpy

Note There is also a magic %pip command that will ensure you install the module in the right kernel (rather than the instance of Python that launched the notebook)

Be sure its the first line you have on your cell block.

%pip install numpy

Sometimes the above command might not work 😫. It could because of mismatch if versions, OS, where notebook is hosted. In that case, you will use the following command to ensure pip installs the module on the python kernel you're running Jupyter Notebooks.

# Install a pip package in the current Jupyter kernel import sys !{sys.executable} -m pip install <package_name>

Or open a terminal 🖥 session and run this command so pip will load the module in the proper python kernel.

python -m pip install <package_name> # Example: python -m pip install numpy

⏬ Import the modules you need

Once you confirm pip has installed the module ✔, those modules can now be used in the current notebook 📒.

You will import any module by using the import command along with the name of the module you want to import

Sometimes packages have different names than their importable name. E.g. pip install scikit-learn -> import sklearn

import datetime print(datetime.datetime.now()) # output: 2021-10-15 17:15:45.247946

If you don't require the whole module library, its always best practice to specify exactly what you want to import

from datetime import datetime print(datetime.now()) # output: 2021-10-15 17:15:45.247946

Notice also the line is shortened because you can call directly what you imported datetime instead of the full module path datetime.datetime

from datetime import datetime print(datetime.now())

Importing module using as

tip To make it easier to call modules, shorten the module name by using as to define an alias.

from datetime import datetime as d print(d.now())
from datetime import datetime as dt print(dt.now())

Restart the Kernel

If you are not able to use the module, it may require restarting the kernel. You can do that by importing IPython and restarting it or click on the restart icon 🔃

Warning You will lose all cached variables when you restart the kernel.

import IPython IPython.Application.instance().kernel.do_shutdown(True) #automatically restarts kernel from cell.

Variables

A variable is a value that can change, depending on conditions or on information passed to the program

Note

  • The Python interpreter automatically picks the most suitable built-in data-type for the variable if no type is provided

  • You cannot use python keywords as a variable name. You can see a list of keywords by typing import keyword; print(keyword.kwlist)

Creating variables and assigning values

We first will assign Hello World to the variables s1,s2. We will then print the variables by referencing it in print. Try it below:

s1 = "Hello" s2 = "World" print(s1,s2)

Exercise How would you print Microsoft Sentinel using what you know?

s1 = "Hello" s2 = "World" s3 = "!" print(s1,s2,s3)

Assigning multiple variables

  • You can assign multiple values to multiple variables in one line.

  • Note that there must be the same number of arguments on the right and left sides of the = operator:

Example

a, b, c = 1, 2, 3 print(a, b, c)

Exercise: Try assigning an additional variable with value to this list

a, b, c = 1, 2, 3 print(a, b, c)

Note Remember pretend the mouse 🖱 has feelings and doesn't want to be touched, Practice using your keyboard ⌨ only.

Temporary variables

It is common to have temporary or dummy variable assignments for a cell. It is conventional to use the underscore for these type of unwanted values.

Example

a, b = 1, 2 ## assigns a,b the value 1,2 _ = a+b ## _ is temporary assignment that adds a and b together _temp = b-a print(a,b, "equals", _) ## prints the output

Exercise Exercise: change the unwanted variable _ to the result of b-a

a, b = 1, 2 _ = a+b _temp = "1" + "1" print(a,b, "equals", _) print("_temp equals", _temp, "since 1 has quotes around it indicating a string data type")

Data Types

Data TypeDescriptionExample
intIntegers, floating-point, complex numbers1,2,3,4,5
boolan expression that results in a value of either true/false.True/False
strstrings of characters"John"
listmutable sequence that group various objects together[1,True,"John"]
dictDictionary{'name':'red','age':10}
tuplesimilar to list but they are immutable.(123,'hello')
setunordered and mutable collections of arbitrary but hashable Python objects{"apple","banana","orange"}

Note

String

Strings can be declared a number of ways.

Single quotes

print('This string is in single quotes')

Double quotes

print("This string is in double quotes")

Triple double quotes

print( """ This multi-line string is in triple double quotes """)

Note Why would you want different ways of declaring a string?

print('This string is in single quotes') print("This string is in double quotes") print(""" This multi-line string is in triple quotes""")

Answer: Because this allows you to embed quotes inside a string by declaring it with another way. You cannot use the same quotes you used to declare the string because it would end the string and the output would not be what you wanted.

## This is wrong print(" I am a string with "quotes" ") ## This is right print(' I am a string with "quotes" ') print(" I am a string with 'quotes' ") print(""" I am a string with 'two' types of "quotes" """) Output

Exercise Press escape if you need to and navigate ⬇. Press enter to edit the cell and try running the current cell. Can you fix it using what we learned?

print(" I am getting pretty good with "Azure Notebooks" ")

Escaping special characters

If your string has special characters or punctuation, you may have problems using it. In order to do that, you will need to use the backslash \ key. This tells python to ignore the character that follows the backslash.

print ('It\'s getting \'hot\' in here')

Exercise Try removing the backslash and run the cell. What happens?

print ('It\'s getting \'hot\' in here')

Inserting values into a string and evaluating expressions

age = 30 print(f"You are {age} years old. {1 + 1}")

Notice how we prefix f in front the string "You are {age} years old.". This allows us to evaluate any expression within curly braces { }. In this case, we grab the value for variable age and insert it into the string when evaluated.

age = 30 print(f"You are {age} years old. {1 + 1}")

Numeric data

There are three types of numbers used in Python: integers, floating, and complex numbers.

x = 5 # int y = 10.024 # float z = 5j # complex

Exercise Run the cell below (shift-enter). Make a guess what the type() command does?

s = "I am a string" x = 5 # int y = 10.024 # float z = 5j # complex print ("Class", "\t\t\t", "Value") print (type(s), "\t\t", s) print (type(x), "\t\t", x) print (type(y), "\t", y) print (type(z), "\t", z)

Here are some arithmetic operations you can perform

OperatorNameDescription
a + bAdditionSum of a and b
a - bSubtractionDifference of a and b
a * bMultiplicationProduct of a and b
a / bTrue divisionQuotient of a and b
a // bFloor divisionQuotient of a and b, removing fractional parts
a % bModulusInteger remainder after division of a by b
a ** bExponentiationa raised to the power of b
-aNegationThe negative of a
## Arithmatic Operations Examples print(True) print(5 + 5) print(5 - 3) print(10 / 2) print(5.0 / 2)

Boolean

Comparison Operations
OperationDescriptionOperationDescription
a == ba equal to ba != ba not equal to b
a < ba less than ba > ba greater than b
a <= ba less than or equal to ba >= ba greater than or equal to b
5.0 == 5 '3' == 3 True == True True == False True == 1 True == 0 '🍎' == '🍏'

Exercise ▶ Run the following 👇🏾 cell block and identify why each expression either resolves true or false.

print("5.0 == 5,", 5.0 == 5) print("'5' == 5,", '5' == 5) print("True == True,", True == True) print("True == False,", True == False) print("not True == False,", not True == False) print("True == 1,", True == 1) print("True == 0,", True == 0) print("'🍎' == '🍏',", '🍎' == '🍏')

Combining Boolean values

You can combine boolean values by using and,or, and not

5 > 1 and "🍎" == "🍌"

Here 5 > 1 evaluates to true, but "apple" == "banana evaluates to false. This then results to false.

Exercise Run the following cell 👇🏾, and then see if you can make the result of both conditions evaluate to True.

5 > 1 and "🍎" == "🍌"

Converting Data Types

There may be situations you will need to convert a data type to another in order for the script to work.

int_to_float = float(10) ## Convert integer to floating number str_to_float = float("200.1243") ## Convert string to floating number print (int_to_float) print (str_to_float)

Exercise Can you try converting a number/string with a decimal to an integer? What happens?

str_to_float = float("200.1243") print (str_to_float)

Here are some more data types to practice with

## Converting Data Types x = (5/2) print("Type:", type(x), ", Output", (x)) ## Convert to string x = str(5/2) print("Type:", type(x), ", Output", (x)) ## Convert to int x = int(5/2) print("Type:", type(x), ", Output", (x)) ## Convert from int to bool x = bool(0) print("Type:", type(x), ", Output", (x))

Collections

There are four collection data types in Python
Namesortindexedmutableduplicates
List✅ ordered✅ indexed✅changeable✅Allows duplicate members
Tuple✅ ordered✅ indexed❌unchangeable✅Allows duplicate members
Set❌ unordered❌Unindexed✅changeable❌No duplicate members
Dictionary✅ ordered✅ indexed✅changeable✅No duplicate keys, but duplicate values are ok

There will be situations where a certain collection type makes more sense than another. Example is you want a set of distinct items with no duplicates set. Or you want a collection that you can grab the age or name of a person in a collection dictionary.

List

Namedescriptionsortindexedmutableduplicates
Listordered sequence of values✅ ordered✅ indexed✅changeable✅Allows duplicate members

Exercise

  • A list is a sequence, where each element is assigned a position (index)

  • First position is 0. You can access each position using

Allright, first lets create a list

Exercise

list_name = ['value1','value2','value3','value4','value5']

Notice how a list is enclosed in square brackets [ ].

Exercise Run the cell below to create a list, which also will be referenced in the following cells. Any variables created in the session, could be referenced later as long as the kernel was not restarted.

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

Access items from list

You can access items in a list with the same [ ] square brackets, but inside you put the index location of what items you want returned.

Lets print the third item in the list

  • Note: The very first position in a list is 0, so the third item in the list is pulled by referencing 2

print(myList[2])

Exercise 🏃🏾‍♀️ Run the following cell, but how would you print the last item on the list?

print(my_list[2])

You are ✔ correct if you answered:

print(my_list[9]) # 10

But you can also print the last item on the list by using a -1

print(my_list[-1]) # 10

Exercise Using what you know, how would you get the 2nd from the last item on the list

print(my_list[-1])

Answer You would reference the index -2 since any negative value starts from the right. print(my_list[-2])

Adding item to the list

You can add item to the list using the append() method.

my_list.append(1000); print(my_list)

Modify a list

You may want to modify values in a list

myList[2] = 5000 #changed the 3rd item in list from 3 to 'changed'
my_list[2] = 5000 print(my_list)

Removing item from list

del(my_list[1]) ## deletes the 2nd item (1) in the list since we start with 0 first which is the number 2

Exercise Remove the first two items on the list using a range [<start>:<finish>]

del(my_list[1]) print(my_list)

Merging Lists together

Exercise

  • When you want to merge two lists together, you can simply use +

  • Note: There are still duplicates when lists are merged.

Lets create list x,y and another variable myList that is a combination of both.

new_list = [20, 21, 22, 23, 24]; my_list = my_list + new_list

Exercise Can you add more items to the list or even make another list and merge all 3 together using what we learned?

# Concatenation new_list = [20, 21, 22, 23, 24]; my_list = my_list + new_list print(my_list)

Slicing and Dicing a list

There may be situations where you don't want the first item in a list or only want the first 5. You will need to reference the range you want after the list variable.

syntax

my_list[<start_here>:<end_here>]

Lets slice (extract) the first and second item in the list

print(my_listt[0:2]) ## 0 identifies where to start (value is grabbed). The 2 indicates the location you want to stop. (the value at the end location isn't pulled).
print("Full list:", my_list) print("Spliced List:", my_list[0:2]) ## Slice the first and second item in the list

Checking if list contains a value

You can check if a list contains a item by using in

Exercise

'search_word' in list

Exercise

  1. Modify the line and search for the number 10 in the list.

  2. How would you an and conditional to check for two values

1 in my_list

Counting

Count how many items in a list by using len(<list>)

len(my_list)

Count how many times an item is in the list list_name.count("<what_to_search_for>")

my_list.count(5)

Exercise Count how many times the number 5 shows up in the list.

how_many_items = len(my_list) ## Gets item count and assigns it to `how_many_items` variable how_many_times = my_list.count(1) ## Counts how many times `1` shows up in `myList` print(my_list) print("The list has", how_many_items, "items.") print("The number 1 shows up", how_many_times, "times.")

Getting the highest value in a list

To get the highest number in the list you will use the max() function. You cannot calculate max if the values are not all numeric.

#Get the highest numeric year in the list print(my_list) print( max(my_list) )

Lists can have various data types

Elements in the lists can be different data types, but be careful of performing any calculation with mixed data types.

mylist = ['string1', 1, "string2", True]
multitype_list = ['string1', 1, "string2", True] print(multitype_list)

Sets

Namesortindexedmutableduplicates
Set❌ unordered❌Unindexed✅changeable❌No duplicate members

Sets are similar to list but is an unordered collection data type that is iterable, mutable and has no duplicate elements.

  • Unordered and sets cannot change once the set has been created.

Lets create a set from the list and notice duplicates are removed

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} #> {'orange', 'banana', 'pear', 'apple'}

Exercise Modify the line and add another fruit to the basket.

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket)

Create set from string

a = set('abracadabra') ## Notice duplicates are removed. #> {'a', 'r', 'b', 'c', 'd'}

Run the following cell and do you understand whats happening ? Why is the list shorter 🤔?

a = set('abracadabra') print(a) fruits = set( {'🍎','🍏','🍏','🍊','🍌','🍏','🌮','🍉','🍌'} ) print(b)

Add item to set

a.add('z') #> {'a', 'c', 'r', 'b', 'z', 'd'}
a.add('z') print(a)

Making a set immutable (Cant be modified)

If you ever want to declare a list and ensure the list is not modified, you can freeze the list using frozenset(<set_name>)

b = frozenset('asdfagsa') #> frozenset({'f', 'g', 'd', 'a', 's'})

Exercise Notice we add Dallas to the set cities. Uncomment # the commented line #frozen_cities.add("Tampa") and run the cell again. What happens?

## Create a cities set and adds Dallas to the set cities = {"Houston", "New York","San Diego"} cities.add("Dallas") print(cities) frozen_cities = frozenset(cities) #frozen_cities.add("Tampa") print(frozen_cities)

Dictionary

Namesortindexedmutableduplicates
Dictionary❌ unordered✅ indexed✅changeable✅No duplicate members

Dictionary consists of key-value pairs {<key> : <value>}. It is enclosed by curly braces {} and values can be assigned and accessed using square brackets [].

Create a dictionary

Lets create a dictionary object with a name and age key

person={ 'name' : 'bob', 'gender' : 'male', 'age' : 30 }
person={ 'name' : 'bob', 'gender' : 'male', 'age' : 30 } print(person)

Getting a property

Lets grab the age property from this dictionary object by reference the right key which in this case its the string "age" enclosed in double quotes .

print(person['age'])
print(person['age'])

Get list of keys/values

To get the list of keys or values only, you would specify the method

Get list of keys

print( person.keys() ) # output: dict_keys(['name', 'gender', 'age'])

Get list of values

print( person.values() ) # output: dict_values(['bob', 'male', 30])
print(person.keys()) print(person.values())

Adding to dictionary

To add to the list, you simply just reference an unused key name in the dictionary object

person['location'] = 'US' # {'name': 'bob', 'gender': 'male', 'age': 30, 'location': 'US'}

Exercise Try adding another item to the dictionary object.

person['location'] = 'US' ## This adds a location with the value US to the dictionary object print(person)

Tuple

Namesortindexedmutableduplicates
Tuple✅ ordered✅ indexed❌unchangeable✅Allows duplicate members

Tuples are like lists except cannot be changed

tuple = (123,'hello') print(tuple) #will output whole tuple. (123,'hello') print(tuple[0]) #will output first value. (123)
tuple = (123,'hello') print(tuple) print(tuple[0]) print(tuple[1])


After running the previous cell, try updating the tuple by running the cell below

tuple[1] = "update"

Exercise What happens when you run the cell and do you know why it happened based on how tuples work?

tuple[1] = "update"

Block Indentation

Python uses indentation to define and control function, loops, and conditions. This makes Python easy to read, but the user must play close attention to the whitespace (space/tabs) usage. Always use 4 spaces for indentation and most code editors are able to convert tabs to spaces to reduce any error.

Note Do not mix tab and spaces. Stay consistent. Indentation Errors will occur or cause the program to do something unexpected

Functions

A function is a block of code which only runs when it is called. This is helpful to run repeatable blocks of code you plan on using often.

Note

  • You can pass data, known as parameters, into a function.

  • A function can return data as a result.

Creating a functions

Declare the function name with Syntax

def <function_name>()

Then any lines you want to belong to the function is associated by using 4 empty spaces

Note

def ping(): # Declare the function with `def <name>():` print("pong")
def ping(): print("pong 🏐")

Call a function

Call your custom function you declared by referencing the name of the function ping()

ping()

Passing information to functions

Information can be passed into functions as arguments.

def greeting(name): ## we declare the parameter `name` as a variable that will be used in the nested code print("Hello",name) ## we print Hello with the value of the name provided greeting("John") ## we call the function greeting and pass the argument `John` as the name

Exercise How would you pass another value to the greeting function and print it out on the response?

  • Example: Print a response like, "Hello <name>, You are <age> years old"

def greeting(name): print("Hello", name) greeting("John")

You can also pass multiple arguments by separating each value with a comma

def greeting(name, age): print("Hello", name, "You are", age, "years old.") greeting("John", 30)

Exercise Can you pass third argument and print it in the output when the function is called?

def greeting(name, age): print("Hello", name, "You are", age, "years old.") greeting("John", 30)

Commenting in functions

Docstrings are not like regular comments. They are stored in the function documentation. You can then use help() to get some helpful guidance on the particular function

Comment your function

def ping(): """ This function replies pong. This is custom documentation you can build to describe the function """ return "pong" ping()

Get help details on function

help(ping)
def ping(): """ This function replies pong. This is custom documentation you can build to describe the function """ return "pong" ping() help(ping)

Multi-level indentation and nesting

You can nest conditions, loops, and functions within each other. If a function is not indented to the same level it will not be considers as part of the parent class

def separateFunction(provided_list): #Loops are also indented and nested conditions start a new indentation for i in provided_list: ## loop through each item in the list if i == 1: ## We will check each `item` in the list for the value of `1`. return True return False separateFunction([2,3,5,6,1])

This will call the function separateFunction() and provide the list [2,3,5,6,1] as an input argument for the function separateFunction()

Exercise Try searching for another item in the array, or add an additional argument in separateFunction() to search against that argument instead of the static value 1.

def separateFunction(provided_list): ## loop through each item in for item in provided_list: ## We will check each `item` in the list for the value of `1`. if item == 1: return True return False separateFunction([2,3,5,6,1])

Passing values into a function

Default values in a function

You can provide default values if you want to assume certain values. Then if input IS provided, it overrides the static default value.

First lets create another function that has a default value for the greeting. We also will call help() function to get the documentation of the greet() function.

def greet(name="anonymous", greeting="Hello"): """ Print a greeting to the user `name` Optional parameter `greeting` can change what they're greeted with. Example: greet("John","Sup") """ print("{} {}".format(greeting, name)) help(greet)

Lets call the function first by providing no input or arguments

greet()
greet()

This time lets call the function greet() but also provide the arguments name='john' and greeting='sup'

We can pass arguments based on the position in the list

greet("john", "sup") # output: sup john

Or we can directly specify what value is for what argument (which now doesn't need to be in the proper list position)

greet(greet="sup", name="bob") # output: sup bob

Exercise Try passing different arguments in different positions. Or modify the function and add another argument that will be used in the response

## Call the greet function and pass a name greet(greeting="sup", name="bob")

Conditional statements

if/else/elif Example

if conditionA: statementA elif conditionB: statementB else: statementD this line will always be executed (after the if/else)

Exercise: Run the cell below shift-enter, How would you modify the if statement to evaluate to false?

Creating a conditional statement

You will nest lines that you want included in each condition evaluated

Exercise Run the following command and see if you can make the expression evaluate false?

a = 5; ## Initializes variables a,b with values 2,4 b = 2; #If block starts here if a > b: # If the value of a > b, nested indented lines will run print("✅", a) else: # if above if statement evaluates to false, the following nested indented lines will run. print("❌", b) b = 2;

One-liner if statement (no indentation)

Please Note Most style guides and linters (error checking) discourage using this as its not the best practice 👎. Try using lines and spaces as its easier to read for everyone else 💓

You can write the if statement to one line if there isn't a need for nesting multiple lines within the statement.

a = 5; ## initializes variables a,b with values 2,4 b = 2; if a > b : print(True, ",", a) ## Evaluate if a > b, If its true run this line, else run the else statement. else: print(False, ",", b)
a = 5; b = 2; if a > b : print(True, ",", a) else: print(False, ",", b)

👍 Even shorter if statement for default values.

You don't have to write a whole conditional statement if all you want is to check if a value exist or use a default value if the condition evaluates to false

a = 5 b = 3 result = "A is bigger than B" if (a>b) else "A is less than B" print(result)

The value of result is "A is bigger than B" only if the expression in the following if statement evaluates to True, otherwise the value following else is used.

Exercise Try writing another statement that maybe evaluates a string or collection.

a = 5 b = 3 result = "A is bigger than B" if (a>b) else "A is less than B" print(result)

Using conditional statement to validate an input provided

Example of searching a list based on the input provided Exercise

mylist = [1,2,3,4,5] userInput = int(input("Enter a number from 1-10:")) if userInput in mylist: print(userInput, "is in the list `mylist`")

When this cell is ran, the userInput variable will call the input() function and request input from the user. After the input is provided, the cell will take the input value and check if it it matches any item in the list my_list.

my_list = [1,2,3,4,5] userInput = int(input("Enter a number from 1-10:")) if userInput in my_list: print(userInput, "is in the list `mylist`")

Loops

Loops are simply computer instruction that will keep repeating until a specified condition is reached.

For Loops

  • Used for interating over a sequence (list, tuple, dictionary, set) and runs a set of statements, once for each item in the list. The loop will end when it reaches the last item on the list its iterating.

Simple For Loop

print("== For Loops ==") for x in range(0, 3): ## Iterate from 0 to 3 print("Let's go %d" % (x)) ## print `Let's go` and the populates the value of the variable `x`

We will loop starting at 0 and end at 3. On each iteration, we will print the current value of x

Exercise How would you make the for loop iterate 10 times instead of 3?

## For Loops print("== For Loops ==") for x in range(0, 3): print(f"Let's go {x}")

You can process any iterable (string, list, dict, etc) with a for loop

my_list = [5,10,15,20,25] for item in my_list: print(f"{item} * 10 = {item * 10}")

Explained

  1. First we create the list of 5 values [5,10,15,20,25]

  2. then we will use the for loop to iterate through each item in the list and print the string for each item.

my_list = [5,10,15,20,25] for item in my_list: print(f"{item} * 10 = {item * 10}")

Nested for Loop

print("\n== Nested For Loops ==") for x in range(0, 3): for y in range(0,2): print("Let's go %d %d" % (x,y))

Exercise Can you nest another condition or loop nested inside this for loop and output the values?

## Nested for loop print("\n== Nested For Loops ==") for x in range(0, 3): for y in range(0,2): print(f"Let's go {x} {y}")

Using For loop to iterate through array of dictionary objects

states = [ {"name" : "Alabama", "capital" : "Montgomery", "country": "United States"}, {"name" : "Colorado", "capital" : "Denver", "country": "United States"}, {"name" : "Texas", "capital" : "Austin", "country": "United States"}, {"name" : "New Mexico", "capital" : "Sante Fe", "country": "United States"}, ] for state in states: print(f"{state['name']} is located in the {state['country']} and it's capital is {state['capital']}")

Explained

  1. First we initialize a list(array) of dictionary objects with key value pairs name, capital, country

  2. Then we use a for loop to iterate through each state and reference the keys within each dictionary item being iterated to retrieve the values.

Challenge Can you add another key to each dictionary object and print that key value when its been iterated in the for loop?

## Sort list by key name states = [ {"name" : "Alabama", "capital" : "Montgomery", "country": "United States"}, {"name" : "Colorado", "capital" : "Denver", "country": "United States"}, {"name" : "Texas", "capital" : "Austin", "country": "United States"}, {"name" : "New Mexico", "capital" : "Sante Fe", "country": "United States"}, ] for state in states: print(f"{state['name']} is located in the {state['country']} and it's capital is {state['capital']}")

Iterating through dictionary key/values

Let's use the same list, but iterate it a different way. Lets iterate each state and print the key/value pair for each item.

for state in states: for key, value in state.items(): print(f"State:{state['name']}, Key:{key}, value:{value}")

Explained

  1. We first will iterate through each state in the states list.

  2. We then grab each key and value from state.items()

  3. We reference directly the key and value variables instead of calling state[<key>]

for state in states: for key, value in state.items(): print(f"State:{state['name']}, Key:{key}, value:{value}")

Using For loop to enumerate through dictionary keys

Or maybe you want the index location of each key in the list. You can enumerate the dictionary

## enumerate through states for state in states: for index, key in enumerate(state): ## use the enummerate function which will convert the dictionary object a list with an numeric index location you can reference. print(f"State:{state['name']}, index:{index}, key:{key}, value:{state[key]}")

Explained

  1. We first will iterate through each state in the states list.

  2. We iterate through each state then grab the index and key from enumerate(state)

  3. We now can reference the index location of the keys and use the key to reference properties in the state variable.

## enumerate through states for state in states: for index, key in enumerate(state): ## use the enummerate function which will convert the dictionary object a list with an numeric index location you can reference. print(f"State:{state['name']}, index:{index}, key:{key}, value:{state[key]}")

Using Loop to modify list values

You can use a loop to iterate through a list and modify values or execute lines for each item being looped.

from datetime import datetime ## Imports the datetime module needed to get current date. years = [1955,1987,1978,2019,1967,1955] ## defines the array of years to loop through for year in years: currentDate = datetime.today().year ## grabs the current date age = currentDate - year ## subtracts the value of x(year) from the current date print(f"date:{currentDate}, year:{year}, You are {age} years old." ) ## replaces all placeholders in curly braces with variable

Note Import the datetime module and create the years array

  1. Import the datetime module to be used in the years array.

  2. years array is created that will used as the input to the for loop

  3. This example will iterate through each year in the years list [1955,1987,1978,2019,1967,1955] .

    1. Inside this loop we first will calculate the currentDate variable by calling the imported datetime function and extracting the year.

    2. We can then calculate the age by subtracting the currentDate for each year being looped.

    3. Then we will print a line that outputs these variables being iterated.

  4. The last command to run is printing out the loop has completed.

## This type of string formatting will require Python >= 3.6 from datetime import datetime ## Imports the datetime module needed to get current date. years = [1955,1987,1978,2019,1967,1955] ## defines the array of years to loop through ## This is the loop that will iterate through each year in the years array. print ("--For loop start--") for year in years: currentDate = datetime.today().year ## grabs the current date age = currentDate - year ## subtracts the value of x(year) from the current date print(f"date:{currentDate}, year:{year}, You are {age} years old." ) ## replaces all placeholders in curly braces with variable print(years) ## This statement is printed outside of the while loop

While Loop

Most of the time you will be using for loops. This loop will continue to execute the nested statements (indented) in the while loop until a specified condition is true

Example

i = 0 # Initialization print("While Loop starting") while (i < 10): # Condition print(f"{i} is less than 10. Looping") # do_something i = i + 1 # Why do we need this? print("While Loop has ended") ## Last line to run. notice its not nested in the loop so it runs last.

Explanation This while loop example will run the lines nested in the while loop until i reaches a value that is greater than 10

## While Loop i = 0 # Initialization print("While Loop starting") while (i < 10): # Condition print(f"{i} is less than 10. Looping") # do_something i = i + 1 # Why do we need this? print("While Loop has ended") ## Last line to run. notice its not nested in the loop so it runs last.

Finished

You are done 🎈🏁🐱‍👓 with part 1 of this Python Crash Course and you are well on your way to knowing Python.

Have some cake to celebrate 🍰. If you are still thirsty🧉 for more, you should now be able to step into the other Notebooks 📓 and it may actually make sense!

Remember to check back as the 2nd part of the series will focus on building on top of this knowledge by learning how to manipulate data using:

PandasNumPy

We will use this knowledge to manipulate and restructure data in order to render charts and visualize output for investigation or sending it.

Keep learning! ❤