Comments

print("Hello World!")
Hello World!

Comments are lines of code that the programming language ignores. Comments are for the people writing and reading the code. In Python, you define a comment with a line starting with a #.

# This is a comment!
# Comments are for people to read
# Python does nothing with comments
print("This is not a comment!")
This is not a comment!

Python does Math

print(2+2)
print(3+1*4)
print((3+1)*4)
4
7
16
## + is for addition
## - is for subtraction
## * is for multiplication
## / is for division
## ** is for exponent
print(2.5+2.5) # this is going to do math
print("2.5+2.5") # This will print what is between the the quotes
5.0
2.5+2.5

Variables

A symbol/placeholder which represents a piece of data.

my_number = 2 #x now has the value of 2
print(x)
print("The value of my_number is", my_number)
my_name = "Butler" # x now has the value of "Butler"
print("The value of my_name has been changed to", my_name)
Butler
The value of my_number is 2
The value of my_name has been changed to Butler
# Variables should have good and descriptives names that too long
# Variable names can contain letters, numbers, or underscores (_)
# Variable names must start with a letter

Types

The type of a piece of data tells you what it is

Examples: * int: a whole number, no decimal (short for integer) * float: a number with a decimal * string: a sequence of characters between quotation marks (““)

x = 2 # this is a int
y = 2.0 # this is a float
print("The type of x is:", type(x))
print("The type of y is:", type(y))
The type of x is: <class 'int'>
The type of y is: <class 'float'>

Performing Math with Variables

x = 2
y = 3

add = x+y
sub = x-y
mul = x*y
div = x/y
exp = x**y

print("Addition:", add)
print("Subtraction:", sub)
print("Multiplication:", mul)
print("Division:", div)
print("Exponent:", exp)
Addition: 5
Subtraction: -1
Multiplication: 6
Division: 0.6666666666666666
Exponent: 8
temp_C = -30 # This is a temperature in Celsius
temp_F = 1.8*(temp_C) + 32 # This is the temperature converted to Farenheit
temp_K = temp_C + 273.15 # This is a temperature in Kelvin

print("The temperature in Celsius:", temp_C)
print("The temperature in Farenheit:", temp_F)
print("The temperature in Kelvin:", temp_K)
The temperature in Celsius: -30
The temperature in Farenheit: -22.0
The temperature in Kelvin: 243.14999999999998
# Code cells remember what was above
print("The temperature in Celsius:", temp_C)
The temperature in Celsius: -30

Conditional Statement

Conditional statements perform differently depending on if a given condition is true or false.

temp_C = 20 # Redefining
if temp_C > 20:
    print("It is hot!")
    print("We should go to the pool!")
temp_C = 19 # Redefining
if temp_C < 20:
    print("It is cold!")
    print("Bring a jacket!")
else:
    print("It is hot!")
    print("Do not bring a jacket!")
It is cold!
Bring a jacket!
temp_C = 23 # Redefining
if temp_C < 15:
    print("It is cold!")
elif temp_C <= 22:
    print("It is moderate!")
elif temp_C <= 30:
    print("Its kinda hot!")
else:
    print("It is hot!")
Its kinda hot!

Boolean

A new data type that must evaluate to either True or False

print(type(False))
<class 'bool'>
# > is greater than
# < is less than
# >= is greater than or equal to
# <= is less than or equal to
# == is equal to
# != is not equal to
print(3!=2)
True

Functions

Functions prevent to need to copy and paste code by letting you reuse code by referencing a name. They work variables but for large pieces of code.

def about_me():
    print("My name is Julie Butler")
    print("I have a dog")
    print("I live in Alliance")
    print("I am a professor")
# Once you have defined a function, it can be referenced
# anywhere in the notebook
about_me()
My name is Julie Butler
I have a dog
I live in Alliance
I am a professor
# Functions can be passed information (called arguments)
# Functions can return information

# Docstrings are a special type of comment for a function
def C_to_F(temp_C):
    """
    Converts a temperature in Celsius to Farenheit.
    Arguments:
        temp_C (float or int): a temperature in Celsius
    Returns:
        temp_F (float or int): a temperature in Farenheit
    """
    temp_F = 1.8*temp_C+32
    return temp_F
print(C_to_F(-50))
print(C_to_F(20))
-58.0
68.0
# Values returned by functions can be saved in variables
temp_F_32 = C_to_F(32)
print("32 Celsius in Farenheit is", temp_F_32)
32 Celsius in Farenheit is 89.6
# Functions can have more than one argument
# and more than one return type
def convert_temp (temp_C, isPrint):
    """
    Convert a temperature in degrees Celsius to both
    Farenheit and Kelvin and will print the conversion
    if needed.
    Arguments:
        temp_C (float or int): a temperature in Celsius
        isPrint (boolean): if True, print information about the temperatures
    Returns:
        temp_F (float): the temperature in Farenheit
        temp_K (float): the temperature in Kelvin
    """
    # Calculate the temperature in Farenheit and Kelvin
    temp_F = 1.8*temp_C+32
    temp_K = temp_C + 273.15
    # Print information if needed (if isPrint is True)
    if isPrint:
        print("The temperature in Celsius is", temp_C)
        print("but in Farenheit it is", temp_F)
        print("and in Kelvin it is", temp_K)
    # Return the calculated temperatures
    return temp_F, temp_K
temp_F_15, temp_K_15 = convert_temp(15, False)
print(temp_F_15, temp_K_15)
59.0 288.15

Lists

List is a data type which let’s you store, access, and manipulate large amounts of information

# Lists are defined with square brackets []
# Each piece of data in a list is called an element
my_list = [10, 22, "Julie", 5, 28]
print(type(my_list))
<class 'list'>
# Each element has a location associated with it identified by a number called an index
# The index of element can be used to extract it from the list
# The index of the first element is 0, the index of the last element is length of list - 1
print(my_list[4])
28
# Save one element of the list with a variable
element = my_list[3]
print(element)
5
# Find the length of a list using the len function
print(len(my_list))
5
# Access multiple elements with index splicing
# The first index is inclusive (meaning we use it)
# The second index is exclusive (meaning we up to it, but do not include it)
# The result of using an index splice on a list is a list
print(my_list[0:3])
[10, 22, 'Julie']
my_smaller_list = my_list[1:4]
print(type(my_smaller_list))
<class 'list'>
# Lists have functions that give them extra abilities
# len is one of the functions that gives us the length of the list

# append is a function that let's us add data to a list
print(my_list)
my_list.append("sponge") # append adds to the end of the list
print(my_list)
[10, 22, 'Julie', 5, 28]
[10, 22, 'Julie', 5, 28, 'sponge']
# pop lets you remove an element at a given index
print(my_list)
my_list.pop(1)
print(my_list)
[10, 22, 'Julie', 5, 28, 'sponge']
[10, 'Julie', 5, 28, 'sponge']
# sort and reverse let you control the order of elements in the list
new_list = [15, 19, 17, 16, 18]
print(new_list)
# orders the list in ascending order (smallest to largest)
new_list.sort()
print(new_list)
# flips the order of the list (first element becomes last element, last element becomes first element)
new_list.reverse()
print(new_list)
[15, 19, 17, 16, 18]
[15, 16, 17, 18, 19]
[19, 18, 17, 16, 15]
# min and max let you pull out the smallest and largest values in a list
print(min(new_list))
print(max(new_list))
15
19
# Reverse list indexing let's you access elements starting from the end of the list
print("The last element in the list is", new_list[4])
print("The last element in the list is", new_list[-1])
print("The second to last element in the list is", new_list[-2])
The last element in the list is 15
The last element in the list is 15
The second to last element in the list is 16

Strings

# A string is a bunch of characters between double quotes
my_name = "Julie Butler"
print(my_name)
Julie Butler
# You can access the letters of a string with indices or index splicing
print(my_name[1])
u
print(my_name[4:8])
e Bu
print(my_name.upper())
JULIE BUTLER
print(my_name.lower())
julie butler
print(my_name.count("l"))
2