"Programming languages allow us to formalize instructions and express logical rules, business rules, mathematics, processes, and automation instructions in one single notation." - Ryan Orsinger
print() function¶print("Good afternoon, ya'll!")
2 + 2
# assigning a value to a variable
today = "Today is a great day to learn"
print(today)
print("Use the print command")
print("To print")
print("Prints each and every line")
"Notebook cells automatically print the last line of code"
# run this cell and the number 5 will be printed
5
5 * 2
"Multiple lines"
"do not print automatically"
"only the last line"
"I'm writing Python with ya'll right now"
print("That means")
print("The print command is important.")
print("When we want to print each line")
# Exercise: Print your name in this cell. Be sure to use quotation marks around the letters.
# Exercise: Print your favorite number in this cell
# Exercise: Print the number 7 in this cell
# Exercise: Print out 3 + 4 in this cell
# Make Python do the math rather than adding 3 + 4 in your head
# Exercise: Print out 3 * 5 in this cell, * means multiply
# This is a comment. Run this cell. Do you see anything? Why or why not?
# First, run this cell.
# Then delete the hashtag at the beginning of the last line.
# Last, run the cell again.
print("This is a 'commented out' print command")
# In Python
# Comments are a best-practice when it comes to communicating to your future self and to fellow developers
print("Once the # at the beginning of this line is removed, this string will print.") # additional hashtags make additional comments
# Variables hold values that we use later in the program by name.
# "Assigning a variable"
# Single = sign is called the assignment operator
message = "Hello, Everybody!"
print(message)
favorite_quote = "If you can't solve a problem, then there is an easier problem you can solve: find it."
print(favorite_quote)
# Variables are assigned to point to values.
favorite_food = "lasagna"
print("My favorite food is", favorite_food)
# Variables can also be re-assigned to point to different values.
favorite_food = "pizza"
print("I changed my mind. My favorite food is actually", favorite_food)
# Exercise: Reassign the favorite_food variable to hold your own favorite food, then print the variable.
# Exercise: Create and assign the variable favorite_number to hold your own favorite number.
# Exercise: Reassign the favorite_food variable to hold the number 7.
# What happens and why? Does this match your expectations?
Each piece of data has two fundamental characteristics:
# The "None" data type represents the absence of a value. This is called "null" in some other programming languages
type(None)
type(True)
type(False)
# Numbers without a decimal are integers. Integers can be negative or positive.
type(-99)
type(2.3)
.5 * .5
type("Howdy!")
# True and False are the only two Boolean values.
True
False
print(True)
print(False)
+ adds two numbers together- subtracts the second number from the first* multiplies both numbers and returns the product/ divides the first number by the second% provides the remainder of dividing the first number by the second. (called the modulo operator)** is the exponentiation operator. 2 raised to the 3rd power is 2**3# Exercise: Add 1 plus 2 plus 3 plus 4 plus 5 plus 6 plus 7 plus 8 plus 9 plus 10
# Exercise: Subtract 23 from 55
# Exercise: Multiply 2.3 by 4.4. What's the data-type that this returns?
# Exercise: Multiply 3 by 5.
# Exercise: Print out the data-type of the result of multiplying 11 * 7
# Exercise: Divide 1 by 2. What happens? What data type is returned?
# Exercise: Divide 5 by 0. What happens? Why do you think that is?
# Exercise: Use the modulo operator to obtain the remainder of dividing 5 by 2
5 % 2
# Exercise: Use the modulo operator to obtain the remainder of dividing 8 by 2
# Exercise: Use the modulo operator to obtain the remainder of dividing 7 by 2
# Exercise: Use the exponent operator to raise 2 to the 3rd power
# Exercise: Use the exponent operator to raise 10 to the 10th power
# Exercise: Use the exponent operator to raise 100 to the 100th power
# Exercise: Use the exponent operator to raise 2 to the negative 1st power
# Exercise: Use the exponent operator to raise 123 to the 0th power
# Exercise: Use what you have learned to determine the average of the following variables
== compares two values to see if they are the same value.!= asks if the values on each side of the operator are not the same.]< and <= are less than and less than or equal to> and >= are greater than and greater than or equal to, respectively.2 < 3 returns True because it's a true statement that two is less than three2 <= 2 returns True because two is less than or equal to two2 < 2 returns False because two is not less than two4 <= 2 returns False because four is not less than or equal to two10 < 5 returns False because 10 is not less than 510 > 5 returns True because ten is greater than 52 == 2 returns True because the number two is equal to the number two2 == 3 returns False because two is not three3 != 2 returns True because three is not equal to two.4 in [1, 2, 3, 4] returns True because 4 exists in the list [1, 2, 3, 4]"b" in "banana" returns True because the string "b" exists inside the string "banana"If we have x = 3 followed by result = x > 0 on the next line, the result variable will hold True because 3 is greater than 0.
print("5 > 4 is", 5 > 4)
print("1 > 0 is", 1 > 0)
# Comparison operators give us back a True or False
print(5 == 5)
print(-4 + 4 == 0)
# False because they're not the same data type
5 == "5"
print("Hello" == "Goodbye")
print("Hello" != "Goodbye") # != means "not equal to"
# = assignment# False because they're not the same data type
5 == "5"
# Exercise: assign the variable favorite_number to hold your favorite number
# Exercise: Write the Python code necessary to answer if your favorite number is less than 100
# Exercise: Write the code to determine if your favorite number is greater than 0
# Exercise: Write the code to determine if your favorite number is five
# Exercise: Write the code to determine if your favorite number is greater than or equal to 3
# Exercise: Write the code to determine if your favorite number is greater than or equal to -100
# Before running this code, consider if this will return True or False, given your favorite_number variable's value
favorite_number < 0 and favorite_number > 10
# Before running this code, consider if this will return True or False, given your favorite_number variable's value
favorite_number < 10 or favorite_number > 20
not True
not False
not not True
not note False
# Truth table for AND
print("Truth Table for AND logic")
print("True and True is:", True and True)
print("True and False is:", True and False)
print("False and True is:", False and True)
print("False and False is:", False and False)
# Truth table for OR
print("Truth Table for OR logic")
print("True or True is:", True or True)
print("True or False is:", True or False)
print("False or True is:", False or True)
print("False or False is:", False or False)
# Boolean values assigned to variables
right_here_now = True
learning_python = True
on_the_moon = False
# Ands need all values to be true for the entire expression to be True
print(right_here_now and on_the_moon)
# Read the line of code below and think about the result.
# An OR statement only needs a single True for the entire expression to be True
print(learning_python or on_the_moon)
ifif, elseif, elseif, elseTrue then Python runs the code that's indented after the "if" line# the "if" evaluates the code to the right to see if it returns True or False.
# If the code returns `True`, then we run the code that's indented below the if.
right_here_now = True
if right_here_now:
print("So glad you made it today!")
print("Wherever you go, there you are.")
else:
print("You are not right here now.")
print("Unindented means the if/else is over, and we're back to our regularly scheduled programming.")
# Before running this cell, think about and predict the outcome.
# the "if" evaluates the code to the right to see if it returns True or False.
# If true, then we run the code that's indented below the if.
on_the_moon = False
if on_the_moon:
print("You are currently on a lunar base.")
else:
print("You are not on the moon!")
# Before running this cell, think about and predict the outcome.
if right_here_now and learning_python:
print("We are right here now and learning python.")
# Before running this cell, think about and predict the outcome.
if right_here_now and learning_python and on_the_moon:
print("You must be magic since you're on the moon and here and learning Python all at the same time.")
# Before running this cell, think about and predict the outcome.
if right_here_now or on_the_moon:
print("How many True values does it take with an OR for the entirety to be True?")
# Before running this cell, think about and predict the outcome.
# Carefully consider the parentheses...
if learning_python and (right_here_now or on_the_moon):
print("In addition to learning python, you are either right here now or on the moon")
# Exercise: Create a variable called is_raining and assign it True or False depending on if it's raining right now
# Exercise: Create a variable named will_rain_later and assign a value of True or False if it may rain later today
# Exercise: Create an "if" condition that checks if it's raining now or later.
# If it is going to rain now or later, then print out "I'll bring an umbrella"
# Lists are created with square brackets. Each item on the list is separated by a comma. Lists can hold any data type
beatles = ["John", "Paul", "George"]
print(beatles)
# Lists have built-in functions
beatles.append("Ringo") # Don't forget Ringo
beatles
# .append and .reverse are some of the built-in list functions
beatles.reverse()
print(beatles)
beatles
# We can also use lists to hold numbers
odds = [1, 3, 5, 7, 9, 11, 13, 17, 19, 21]
odds
# for variable in list:
# For each number in the list of odds, do something
# thing we do each time through the loop IS the code indented within that loop
# for new_variable in list_variable
for number in odds:
print(number)
print("The loop is going")
print("The Loop is complete.")
for number in odds:
print(number + 10)
There are 2 kinds of functions in Python: built-in and user defined functions.
Some built in functions:
# sum is a built in function
numbers = [2, 3, 5, 7]
sum(numbers)
# len is a built-in function short for length
len(numbers)
# calculate the average of a list of numbers
sum(numbers) / len(numbers)
# The len function also works on strings
programming_language = "Python"
print("The number of letters in Python is", len(programming_language))
Imagine the exercise asks us to write a function called is_five that takes in a variable and returns True/False if that variable is the number five. The function would look like this:
def is_five(x):
result = x == 5
return result
Or we could write this a little more succinctly (since returning the result is the same as returning the expression assigned to the result variable)
def is_five(x):
return x == 5
The result of this function is entirely dependent on the input values we send into the function. For example:
is_five(10) will return Falseis_five(-5) returns False because -5 is not 5.is_five("hello") returns False because the string "hello" certainly isn't the number 5.is_five(5) returns True because 5 == 5 evaluates to True.Notice how this function is returning the result of a comparison operation and that the comparison operator will give us a True or a False, depending on the value contained in the input variable sent into the function.
If the exercise was to make a function named is_more_than_three, we could define the function in the following way:
def is_more_than_three(x):
return x > 3
Notice that we're returning the result of x > 3, which can change with different inputs. For example:
is_more_than_three(10) returns Trueis_more_than_three(30) returns Trueis_more_than_three(3) returns False (because 3 is not greater than 3)is_more_than_three(3.025) returns True because 3.023 > 3 returns True.is_more_than_three(-23) returns False b/c negative 23 is less than 3.# Exercise: Use the examples above to write a function called is_greater_than_1 that takes in an input and returns True/False if that number is greater than 1
# Exercise: Use the examples above to write a function called is_less_than_100 that takes in an input and returns True/False if that number is less than 100
# how to define our own functions
# def function_name(variable_name_for_the_input):
# output = guts of the function
# return output
def is_even(number):
remainder = number % 2 # the % operator returns the remainder of integer division of the number on the left by the number on the right
if remainder == 0: # even numbers have no remainder
return True
else:
return False
# calling a function means to run it
print(is_even(2))
print(is_even(4))
print(is_even(2.3))
print(is_even(3))
# lots of built in functions work on sequences
names = ["John", "Paul", "George", "Ringo"]
print("The number of items on the list is", len(names))
numbers = [2, 3, 5, 7]
print("The highest number on the list is", max(numbers))
print("The smallest number on the list is", min(numbers))
# def keyword to define, name_of_function, parentheses for parameters
def square(number):
return number * number # return is the output we hand back to the code that called the function (calling == execute == run)
square(3)
square(4)
# How to average a list of numbers.
numbers = [2, 3, 5, 7]
total = sum(numbers)
average = total / len(numbers)
average
def average(numbers):
total = sum(numbers)
average = total / len(numbers)
return average
print(average([1, 2, 3]))
print(average([1, 2]))
# Max returns the longest string
print(max(["a", "aa", "aaa"]))
print(min(["a", "aa", "aaa"]))
workshop = {
"name": "Introduction to Python",
"instructor": "Ryan",
"platform": "Kaggle"
}
# We use the variable that holds the dictionary followed by square brackets (like a list), with the string holding the key name.
workshop["name"]
'Introduction to Python'
workshop["platform"]
'Kaggle'
# To add new values to a dictionary, use a new key name
workshop["programming_language"] = "Python"
workshop["language_version"] = 3.6
workshop
{'name': 'Introduction to Python',
'instructor': 'Ryan',
'platform': 'Kaggle',
'favorite_programming_language': 'Python',
'programming_language': 'Python',
'language_version': 3.6}
# Exercise
# Add a new key=>value pair to the "workshop" dictionary variable.
# The key should be called "my_name" and the value should be a string holding your name
# Exercise
# Make a new variable called preferences.
# Set up a key for "favorite_number" and assign a value
# Setup a key for "favorite_color" and assign a string with your favorite number