Here is how you tell the computer to do some of the basic arithmetic operations in python.
# To add two numbers a and b, we write a + b. For example:
print("2 + 3 =",2 + 3)
# To multiply two numbers a and b, we write a * b. For example:
print("2 * 3 =", 2 * 3)
# To subtract the number b from the number a, we write a - b. For example:
print("2 - 3 =", 2 - 3)
# To divide the number a by the number b, we write a / b. For example:
print("2 / 3 =", 2 / 3)
# To raise the number a to the exponent b, we write a**b. For example:
print("2**3 =", 2**3)
# Pay particular attention to the convention a**b for exponentiation versus the more widely used a^b. This
# expression a^b has a meaning in python, but it is not exponentiation. Do not use a^b when you instead want to
# calculate a**b.
2 + 3 = 5 2 * 3 = 6 2 - 3 = -1 2 / 3 = 0.6666666666666666 2**3 = 8
We often use computers in the following way:
Computers can do all kinds of things with all kinds of data. What a computer can and cannot do with a piece of data largely depends on what "type" of data it is. Here are some of the common data types that we will encounter:
True
and False
. These don't cover all possible data types, but this is a good starting point for us. Depending on what type of data you give the computer, the computer knows how to do certain things with the data. We don't really need to get into data types too heavily at the moment. We just need to know that they are an important concept in computer programming and that computers can do different things with data depending on what type of data it is.
Referring to the discussion above, we give a computer some data, and we tell the computer what we want to do with the data. One of the ways that we can get the computer to do stuff with our data is by telling the computer to apply a function or an operator to the data. Here, we use the words function and operator synonymously for the sake of simplicity. We will also only talk about how to use functions that have been previously defined for us. It is possible to create our own functions, but we will save that discussion for a later day.
Now, let us see what a function is and figure out how to use it. Essentially, a function is something that takes in some input, does something, and returns some output. Here is a diagram: $$\text{input} \rightarrow \text{[function]} \rightarrow \text{output}$$ Let's look at a bunch of different functions and see how they work. Remember, we are using the words function and operator synonymously.
The print
function tells the computer to display stuff on the screen. It's input is some text, and what it does to the input is that it displays the inputted text on the screen. Here is an example showing how to use it.
# Let's tell the computer to display the phrase "Hello, world!" to the screen.
print("Hello, world!")
# Now let's see what happens when we input a number to the print function instead of text.
print(7)
# As we can see, print still works with numbers as well as text. What about Boolean values?
print(True)
# Yep, still works! Now, what if I want to print multiple things at the same time, such as "Hello, world!", and the
# number 7? Here's how you can do that:
print("Hello, world!", 7)
# As we can see, we can input multiple things to the print function, separated by commas, and the print function
# will display all the inputs on the screen as one line, separated by spaces. The order in which we write the
# inputs matters. For instance:
print(7, "Hello, world!")
# gives us a different output from the previous print statement. We don't have to stop at 2 inputs either:
print(7, 8, "Hello, world!", False, ":)")
# We can supply any number of inputs to the print function, all separated by commas, and it will print all of them
# to the screen, all separated by spaces on the screen.
# What if we don't want spaces to be in between the multiple inputs when they get displayed? For instance, if we
# run the following print statement:
print("The final answer is",7,".")
# we see that there is an annoying space between the 7 and the '.'. We want this to go away. Here's how:
print("The final answer is",7,".",sep="")
# The sep input stands for separator, and it tells the computer what symbol to insert between each of the different
# inputs when it prints them to the screen. By default, sep = " " (a single space). We just changed it to sep = ""
# (no spaces at all). This gets rid of the space between the 7 and the '.', but now we don't have a space between
# 'is' and 7. We can fix it by adding it back in manually:
print("The final answer is"," ",7,".",sep="")
# Now the computer prints to the screen in the way that we want it to.
Hello, world! 7 True Hello, world! 7 7 Hello, world! 7 8 Hello, world! False :) The final answer is 7 . The final answer is7. The final answer is 7.
=
versus the Comparison Operator ==
¶In regular mathematics, we can see statements such as $x = 7$, which can mean either that (1) we are assigning the variable $x$ to have the value $7$, or it can mean that (2) we are comparing the variable $x$ and the number $7$ and saying that $x$ is equal to (as in, the same number as) $7$. Humans have no problem using the same symbol $=$ to have these two separate meanings, but computers aren't capable of making the distinction unless we tell them which definition of $=$ we are using.
Hence, we have to use two different symbols to let the computer differentiate between the two different meanings. In computer code, when we see something such as x = 7
, we mean that we are assigning the variable $x$ to have the value $7$. The single =
in computer programming is called the assignment operator for this reason.
In contrast, when we see something like x == 7
in computer code, we mean that we are comparing a previously defined variable $x$ and the number $7$ and saying that they have the same value. This ==
is called the comparison operator. Let's look at an example to make this distinction more clear.
=
¶# First we take a look at the assignment operator.
# Let's create a variable called x and assign the number 7 to its value.
x = 7
# Now let's check the value of x.
print("1. The value of x is", x)
# Now let's reassign the variable x to have the value 8.
x = 8
# Question: what do you think the value of x is now? Uncomment the line below to check your answer.
# print("2. The value of x is now", x)
# We see that the variable x only stores the most recently assigned value to it. This is convenient, because we can
# re-use the same variable name throughout a code. This makes writing code more efficient and enjoyable.
# Now the value of a variable doesn't have to be a number. It could also be text, Boolean, or some other data type.
# Here are some examples of variables being assigned to have values that aren't numbers:
y = "hello, world!" #this is text
z = 'twelve' #this is also text
w = True #this is the Boolean value True
r = False #this is the Boolean value False
print("3. The value of y is", y)
print(" The value of z is", z)
print(" The value of w is", w)
print(" The value of r is", r)
# The moral of the story is that we think of statements such as x = a in coding as "take the value a and store it
# in the variable x".
1. The value of x is 7 3. The value of y is hello, world! The value of z is twelve The value of w is True The value of r is False
==
¶# Now let's take a look at the comparison operator.
# Abstractly, the comparison operator takes in two values a and b, that the computer somehow knows if they are
# the same or not, and compares them. If they are the same value, then the computer tells us True, and if they are
# not the same value, then the computer tells us False. Here are some examples.
# The computer knows how to compare numbers with one another:
print("1. Is 1 the same number as 1? Computer says:", 1 == 1)
print("2. Is 1 the same number as 2? Computer says:", 1 == 2)
# As you can see, when I write some code of the form a == b, the computer is taking in a and b as inputs, and
# returning either True or False as outputs. Put into a diagram
# a, b --> [comparing a and b] --> True or False
# Since the assignment operator returns either True or False, and since we know that we can assign variables to
# have the value of True or False, then we can do things such as the following:
y = 7
x = y == 3
# Question: what value does x have? Uncomment the line below to check your answer:
# print("3. The value of x is", x)
# As we can see, the computer reads x = y == 3 as "first I compare the
# value stored at the variable y with the value 3 to see if they are equal, then I take
# the result of that comparison and store it in the variable x"
# The computer also knows how to compare text. Humans know that the words 'yes', 'Yes', 'YEs', 'yEs', and 'yES'
# are all the same word, just with some slightly different capitalization. Computers are not as smart. For the
# computer to call two words or phrases the same, they must be written in exactly the same way. Capitalization
# cannot be different; spelling cannot be different; commas, periods, exclamation points, and other punctuation
# cannot be different; and so on and so forth. Here is an example showing how we have to be extremely precise when
# comparing text:
print("4. Is 'yes' the same as 'Yes'? Computer says:", 'yes' == 'Yes') # Different capitalization -> different
# text
print("5. Is 'y es' the same as 'yes'? Computer says:", 'y es' == 'yes') # Any extra / missing spaces -> different
# text
print("6. Is \"yes\" the same as 'yes'? Computer says:", "yes" == 'yes') # Doesn't matter if we use single quotes
# or double quotes for text
# The comparison operator is an operator that gives either True or False as its output. Operators of this type are
# called logical operators. Logical operators are most useful for writing programs in which you want the computer
# to make decisions based on whether something is True or False. We will explore logical operators and how to get
# the computer to make decisions later.
1. Is 1 the same number as 1? Computer says: True 2. Is 1 the same number as 2? Computer says: False 4. Is 'yes' the same as 'Yes'? Computer says: False 5. Is 'y es' the same as 'yes'? Computer says: False 6. Is "yes" the same as 'yes'? Computer says: True
# One last thing about the comparison operator. What do you think the output of the next line is (True or False)?
# Uncomment to check your answer.
# print("Is the number 7 the same as the text '7'? Computer says:", 7 == '7')
# After checking, you may be a little surprised. You see, for humans, we make no differentiation between the symbol
# 7 (without quotations) and the symbol '7' (with quotations). They both refer to the same concept in our minds:
# the number 7. Computers, however, are not as smart, and understand the symbol 7 and something completely different
# from the symbol '7'. The computer interprets the first symbol 7 as the number 7, for which it knows how to do
# things with numbers. The computer interprests the other symbol '7' as text, which is not a number.
# Because 7 and '7' refer to two different kinds of data (number versus text), the #computer says that they are
# different.
# The moral of the last exercise is that the type of data you are working with matters to a computer. We must always
# make sure that whatever data we are working with is of the correct type, so that we don't tell the computer to
# try and do something with a piece of data that it doesn't know how to do.
There are only two Boolean values. They are either True
or False
. Computers use these values to help make logical decisions. There are certain operators that take some input and return either True
or False
as its output. Such an operator is called a logical operator. The comparison operator ==
is an example of a logical operator. Here are some other basic logical operators:
<
Operator¶Given two numbers x
and y
, x < y
gives True
if x
is smalled than y
, and gives False
otherwise.
>
, Less than or Equal to <=
, and Greater than or Equal to >=
Operators¶These three behave similarly to the <
operator. We leave as an exercise to the reader to determine when these three logical operators return True
and when they return False
.
and
and Logical or
Operators¶These operators take in two Boolean values and return either True
or False
. Here is some code displaying how they behave:
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)
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)
True and True is: True True and False is: False False and True is: False False and False is: False True or True is: True True or False is: True False or True is: True False or False is: False
These operators are best for combining multiple other Logical operators together. Here is an example:
# Suppose that we want to ask a computer if some given number x is between 1 and 7. In other words, does the
# number x satisfy 1 < x and x < 7. Here's how we would do that:
x = 3
print("Is 1 <", x, "< 7? Answer:", 1 < x and x < 7)
# Feel free to test this with different values for x to see that it works. We see that, in a way, we combined the <
# on the left with the < on the right by using the 'and' operator.
Is 1 < 3 < 7? Answer: True
not
Operator¶The not
operator takes in one Boolean value and returns either True
or False
. Here's how it works:
print("not True is:", not True)
print("not False is:", not False)
not True is: False not False is: True
This operator is useful for when you are interested in when some condition does NOT happen. We will see this be used later.
input
Function and the type
Function¶Sometimes we want the computer to ask someone else to give it data. We do this by telling the computer to use the input
function. Here's how it works.
x = input("Give me some data:") #when you run this, type something into the box and hit the enter key
print("The data you gave me is:", x)
# As we can see, the 'input' function takes in some text, displays it to the screen, lets the user type some stuff
# in, and then outputs whatever the user typed in. In a diagram:
# text -> [let the user type something in] -> the thing that was typed in
# Now, what type of data is the output of the 'input' function? Let's find out by using the type function
print("The type of data you gave me is:", type(x))
# If you run this code, no matter what you type into the box, the type of data the computer says you gave it is
# <class 'str'>. Remember how I said that some types of data are Number, Text, and Boolean? Different programming
# languages have different names for these types of data. In python, Text data is called 'str', which stands for
# string. Basically, if some data is of the data type <class 'str'>, then that means it is some Text.
# Why did we just talk about all of this? Because even if you type in some numbers into the box, the 'input'
# function stores that data as some Text. The computer knows how to do arithmetic with numbers, but it doesn't know
# how to do arithmetic with Text. How do we get the computer to store our data as a number instead of as text?
# This is the motivation for the next function.
Give me some data:1 The data you gave me is: 1 The type of data you gave me is: <class 'str'>
eval
Function to Change Text to Numbers¶The eval
function is a very powerful (and somewhat dangerous if used incorrectly) function. We won't dive into the details discussing what all eval
actually does or what all it can be used for, but rather we will only talk about how we can use eval
to change a piece of text data such as '7' into the number 7. One can easily look up the eval
function online and learn more about it there.
Here's how we'll be using the eval
function:
# Let's make the computer ask the user for some numerical input and store it in the variable x.
x = input("Give me any real number: ")
print("1. The data type of x is", type(x))
# Recall that even though we asked the user to input a number, x currently is of the text data type. We want to
# convert x to a number. Let's stick x into the eval function.
x = eval(x)
# Now let's see what x is and what data type it is.
print("2. x is:", x)
print(" The new data type of x is:", type(x))
# Depending on what the user types in the box, the end result after using eval on x is that x is one of the
# following data types:
# 1. <class 'int'>, which is python's way of saying that x is an integer
# 2. <class 'float'> which is python's way of saying that x is a real number that has decimal points in it
# The moral of the story is that when you want the computer to get some numerical input from a user, we first get
# the data from them as text using input, and then we convert that data to a number using eval.
Give me any real number: 2 1. The data type of x is <class 'str'> 2. x is: 2 The new data type of x is: <class 'int'>
Suppose that I have two functions $f$ and $g$, and let $x$ be a possible input to the function $g$. Let $g(x)$ be the output of $g$ when it receives $x$ as an input. In a diagram: $$x \rightarrow_g g(x)$$ which is meant to be read as "the input $x$ is sent by the function $g$ to the output $g(x)$". Now suppose that $g(x)$ is a possible input for the function $f$, and let $f(g(x))$ be the output of the function $f$ when it receives $g(x)$ as an input. Once again, in a diagram: $$x \rightarrow_g g(x) \rightarrow_f f(g(x))$$ which is meant to be read as "the input $x$ is sent by the function $g$ to the output $g(x)$, and then $g(x)$ is sent by the function $f$ to the output $f(g(x))$". This process of chaining together the functions $f$ and $g$ by sending $x$ to $f(g(x))$ is called composing $f$ and $g$. Let's look at an example to see how we can use this concept to write better code.
# Recall that the 'input' function take in some text and outputs whatever the user types as more text. We will use
# the input function as our function g with reference to the notation above.
x = "Input a real number: "
print("1. x =",x)
gx = input(x) # the output of the function g, g(x)
print(" g(x) =",gx)
print(" The type of g(x) is",type(gx))
# Now suppose that the user types in a number, such as the number 12, when prompted, so that g(x) = "12" (recall
# that the text "12" is not the same as the number 12 to a computer). We also recall that the eval function takes in
# some text of the form "y" where y is a number, and outputs the number y. We will use the eval function as our
# function f with reference to the notation above. Let's apply our function f to the output g(x).
fgx = eval(gx) # the output f(g(x)) with reference to the above notation
print(" f(g(x)) =",fgx)
print(" The type of f(g(x)) is", type(fgx))
# Now since f(g(x)) = eval(g(x)), and g(x) = input(x), we have
# that f(g(x)) = eval(input(x)). Using this fact, we can rewrite the above code with much fewer lines:
x = "Input a real number: "
print("2. x =", x)
fgx = eval(input(x))
print(" f(g(x)) =", fgx)
print(" The type of f(g(x)) is", type(fgx))
# Notice how in the second version of the code, we didn't have to define an intermediate variable gx to store g(x).
# We just went straight from x to f(g(x)). This is the power of function composition: it saves us time writing code,
# it makes code more readable, and we don't have to define any unnecessary variables.
1. x = Input a real number: Input a real number: 2 g(x) = 2 The type of g(x) is <class 'str'> f(g(x)) = 2 The type of f(g(x)) is <class 'int'> 2. x = Input a real number: Input a real number: 3 f(g(x)) = 3 The type of f(g(x)) is <class 'int'>
while
Loops¶A while loop is a block of code that the computer will repeatedly execute until some stopping condition is met. This is most useful when you want the computer to perform the same task over and over again until it produces some desired result.
Let's look at an example to see how to write a while loop and to better understand how it works.
Given two real numbers $a$ and $b$ such that $1 < a < b$, what is the smallest positive integer $n$ such that $a^n > b?$ We can use while loops to answer this question experimentally. Let's look at the following code that solves our problem below:
# First, we prompt the user for the numbers a and b. If the user doesn't give us numbers where 1 < a < b, then we
# keep asking them to give us the correct numbers.
a = 0
b = 0
# Loop 1
while not(1 < a and a < b):
print("Give me two numbers a, b such that 1 < a < b:")
a = eval(input("a = "))
b = eval(input("b = "))
# Now that we have a and b, we keep multiplying a with itself until the result is larger than b. We use the number
# n to keep track of how many times we do this.
n = 1
# Loop 2
while a**n <= b: #a**n means "a to the nth power"
n = n + 1
# This loop stops once a^n > b, and the resulting integer n will be the smallest one such that a^n > b. The last
# thing we need to do is display our answer.
print("Given that a = ",a," and b = ",b,", the smallest integer n such that a^n > b is n = ",n,".",sep="")
# Now all that is left to do is to run our code and supply some values to it to see that it works. Feel free to
# run this code with different choices of a and b.
Give me two numbers a, b such that 1 < a < b: a = 2 b = 3 Given that a = 2 and b = 3, the smallest integer n such that a^n > b is n = 2.
In the code above, we used two different while loops. The general structure of the loop is of the form
while (some condition is true):
do something
For instance, in Loop 2, the condition the computer checks is if $a^n \leq b$. In Loop 1, the three indented lines of code that follow the "while" statement is the "something" that the computer does.
In a while loop, the computer first checks if the condition is true, and if it is, then the computer does whatever you've told it to do. Then the computer checks if the condition is still true. If it still is true, then the computer does whatever you've told it to do a second time. It keeps repeating this process of checking and then doing something forever and ever until it checks the condition and finds out that it is no longer true. Once the computer sees that the condition is false, it stops the loop and moves on with the program.
In both loops, we make the computer change the values of some of the variables that are involved in the condition to be checked before it runs through the loop another time. For instance, in Loop 2, we increase the value of the variable $n$ before we make the computer check if $a^n \leq b$. This guarantees that the while loop will eventually stop, since we will eventually reach a large enough $n$ such that $a^n > b$.
It is possible to write a while loop that never stops. This is one of the dangers of while loops. If your computer gets caught in an infinite loop, then it will never proceed with the rest of the code and you will never get the code to do what you want it to do. Here is an example of an infinite loop:
# WARNING: INFINITE LOOP
x = 1
while 1 == 1:
print(x)
x = x + 1
print("You'll never see this statement be printed to the screen.")
Since $1$ is always equal to $1$, if you run the code above, it will keep printing out integers until you manually hit the stop button at the top of your jupyter notebook. The second print statement that is outside of the while loop will never be printed to the screen, since the computer will be stuck in the while loop forever.
The moral of this story is that you should always make sure the condition the computer checks in the while loop will eventually become false after running through the loop enough times.
SymPy is short for Symbolic Python, and is a package that allows us to make the computer work with symbolic expressions such as $ax^2 + bx + c = 0$ or $(a+bi)(c+di) = (ac - bd) + (ad + bc)i$. Let's learn some of the basic commands and see how it works.
# Whenever we want to use SymPy, we have to tell the computer that we want it to use SymPy. Here is the command for
# that:
from sympy import *
# Essentially, this command tells the computer "take everything in the sympy toolbox and be ready to use it when
# told to do so". We include this at the very beginning of our code every time we want to use sympy.
# Next, let's learn what the symbols function does.
x = symbols('x')
# This function takes in a letter and makes it into a symbol. Symbols are the first type of data we have encountered
# that are not any of the number, text, or Boolean data types that we've talked about previously. Basically, the
# symbol data type is a special data type that the computer needs in order to do all of the algebraic manipulations
# that sympy allows it to do. We don't need to know much more about it than that.
# Now that we have defined x as a symbol, we can use x to create expressions involving it.
expr = x - 1
print("expr = ",expr)
# As we can see, the variable expr carries around the mathematical expression x**2 + x + 1. We can do many things
# with expressions. The most important thing we can do involving expressions is use the solve function on them.
# Here's how the solve function works:
solutions = solve(expr, x)
print("The solutions to",expr,"= 0 are x =",solutions)
# The solve function takes in two inputs: a mathematical expression involving some symbol, and the symbol we wish to
# solve for. The syntax is solve(expression, symbol). Then the solve function solves the equation
# expression = 0 for the given symbol. For example, above we have that expr = x - 1, so the code solve(expr, x) is
# solve(x-1, x), and it tells the computer to solve the equation x - 1 = 0 for x. It returns all possible values for
# x that solve the equation.
The goal of this section is to learn some of the useful commands for plotting with the sympy package. As per usual, this is best learned through examples.
# First, let's tell the computer we are using sympy.
from sympy import *
# Now, let's tell the computer what symbols we are working with. We will only create one symbol called x.
x = symbols('x')
# Okay, now let's tell Python to plot the function f(x) = x**2 on the interval (-3, 3). We will use the plot function to do
# this.
plot(x**2, (x, -3, 3))
# The first input to the plot function is the expression we wish to plot. In this specific example, it is x**2. The second
# input to the plot function is a tuple with 3 entries. The first entry of the tuple tells the computer what the independent
# variable of our expression is. In this example, the independent variable is x. The next two entries tell the computer which
# interval we want the independent variable to be plotted over. In this example, the interval is (-3, 3).
# When we run our code, we produce the plot of the function f(x) = x**2 as x takes values in the interval (-3, 3).
Okay, we have seen an example showing us how to use the plot function in Python, specifically with the SymPy package. Now let's explore what else we can do with the plot function.
# Let's plot the functions f(x) = x**2 and g(x) = sqrt(x) on the same plot.
# As per usual, we first tell the computer we are using SymPy.
from sympy import *
# Next, we define our symbol x.
x = symbols('x')
# Now, let's plot our two functions at the same time. We will plot them on two different intervals.
plot( (x**2, (x, -2, 2)), (sqrt(x), (x, 0, 3)) )
# Notice that there are two inputs to plot, (x**2, (x, -2, 2)) and (sqrt(x), (x, 0, 3)). The first input says we are plotting
# x**2 with independent variable x on the interval (-2, 2). The second input says we are plotting sqrt(x) with independent
# variable x on the interval (0, 3). Running our code gives the expected results below.
div
function¶Suppose we have two different polynomial expressions $p(x)$ and $q(x)$ in a single variable $x$. If we want to divide $p(x)$ by $q(x)$, we can use the div
function. Let's see how this works:
from sympy import * # using sympy
x = symbols('x') # make a symbol x
p = x**2 + x + 1 # Let's make our first expression p(x) = x**2 + x + 1
q = x + 1 # Let's make our second expression q(x) = x + 1
# Now let's see what we get when we divide p by q using div
print(div(p,q))
# We see that we get a tuple with two entries: x and 1. The first entry, x, is the quotient that we get when we divide p(x) by
# q(x). The second entry, 1, is the remainder that is left over after dividing p(x) by q(x).
# To fully understand what the output of div is trying to say, we interpret it as
# p(x) / q(x) = x + 1 / q(x). In other words:
# (x**2 + x + 1) / (x + 1) = x + 1 / (x + 1).
# Let's divide x**2 by x to make sure we are understanding what is going on:
print(div(x**2, x))
# Now we see that we get (x,0) as our output. In other words:
# (x**2) / x = x + 0 / x = x, which is expected.
# In general: div(p(x), q(x)) returns two values: (quotient, remainder), where we interpret the outputs as
# p(x) / q(x) = quotient + remainder / q(x).
# Pro-tip: you can store both of the outputs at once in the following way:
quotient, remainder = div(x**3, x) # notice how we have two different variable names on the left side, separated by a comma.
# the first output of div is stored in quotient, while the second output of div is stored in remainder. Printing these out along
# with div(x**3, x) confirms this:
print(quotient)
print(remainder)
print(div(x**3, x))
(x, 1) (x, 0) x**2 0 (x**2, 0)
If we have some expression involving a symbol $x$, we can substitute another symbol or a specific value for $x$ using sympy. Here's how:
from sympy import *
x = symbols('x')
expr = 2*x # here is an expression involving a single symbol x
# Let's substitute an actual number in for x in the above expression. We do this using .subs:
print('Substitute 2 for x: ', expr, '=', expr.subs(x,2))
# We see that we just call the expressions name expr, and we add a .subs(x,2) at the end of it. The first input to .subs(x,2)
# is the symbol to be substituted out, in this case, x. The second input is the symbol (or number) that we wish to substitute
# for, in this case, the number 2.
# In general, if we have an expression called expr, and it uses a symbol called x, we can substitute x for another symbol
# (or number) called y by saying expr.subs(x,y).
Substitute 2 for x: 2*x = 4
if
statements¶Sometimes we wish the computer to check some condition and make a decision based on what that condition says. The if
statement is how we get the computer to do this. Here is an example.
# Let's create a variable x and assign it the value 0.
x = 0
# Now let's create a variable y and assign it the value 1.
y = 1
# Now let's tell the computer to add 1 to x and print the result, but only if y is positive.
if y > 0:
print("1. Since", y,"> 0,", "x + 1 =", x + 1)
# What the computer does above is check if the value stored in y is greater than 0. If it is, then the computer will run
# whatever code is written in the indentation below the if statement. Here, y currently holds the value 1, which is greater
# than 0. Since y > 0 is a true statement, the computer executes the code 'print(x+1)' below it. Running our code verifies this.
# Now let's modify our code slightly.
if y < 0:
print("2. Since", y, "< 0,", "x + 1 =",x + 1)
# Since y holds the value 1, and 1 > 0, the statement y < 0 is false. Therefore, the computer will not execute the code written
# below 'if y < 0:'. Running our code verifies this.
This example captures what the if statement does. The computer checks if some condition is true, and if it is, it will do whatever you tell it to do. Otherwise, the computer will do nothing and skip to the next available line of code (or stop if there is no more code after the if statement).
else
¶Now, what if instead of telling the computer to do nothing if the condition it checks is false, what if we want the computer to do something else instead? This is where the else
statement comes in. Let's look at an example.
# Let's create a variable x and store the value 2 in it.
x = 2
# Let's have the computer print the word 'positive' if x is positive, else we'll have the computer print the word 'negative'.
if x > 0:
print('1. Positive')
else:
print('1. Negative')
# If we run our code, the computer will print 'Positive' since x > 0 is a true statement.
# If we now define a variable y that stores the value -2:
y = -2
# And have the computer do the same if, else statement but with y instead of x:
if y > 0:
print('2. Positive') # line 1
else:
print('2. Negative') # line 2
# Then since y > 0 is a false statement, the computer skips over the code in line 1 and instead runs the code in line 2. The
# end result is now the computer prints out the word 'Negative'
As we can see from the example above, the else
statement is written after an if
statement for when you want the computer to do something else besides nothing if the condition being checked in the if
statement turns out to be false.
We've learned about a few different data types: numbers, text, and Boolean. We now introduce another data type called a list. Before talking about what lists are in python, we should review what we know about lists in an intuitive sense.
We think of a list as an ordered collection of things. Here is an example of a list:
We see that the first item on the list is the number 12, the second item is the word Banana, the third is a smiley face :), and the last item is the phrase Howdy! Many different kinds of items can be put together on one list, and each item on the list has a clearly defined order in which it comes in.
We can re-write the list above in a more compact way: [12, Banana, :), Howdy]. The square brackets tell us that we have a list, and each item in the list is separated by a comma. Moreover, the order in which the items are written tell us which order they belong to in the list.
Now we are ready to talk about how lists are defined in Python. Let's look at an example:
# Let's make the list that we created above:
my_list = [12, 'Banana', ':)', 'Howdy']
# The right hand side gives us the syntax for a list. You list out the objects you want to be in your list, separated by commas,
# and you use square brackets at the start and the end of the list.
# If we print out our list, we get the following:
print(my_list)
[12, 'Banana', ':)', 'Howdy']
There are many more things we can learn about lists, such as different ways to create them, how to combine lists, how to add or remove elements from a list, how to sort through a list, etc. However, we will learn about that later.
for
Loops¶Sometimes we wish to tell the computer to repeat a certain command for a certain amount of time. This is what for
loops are used for. In contrast with while loops, we know exactly how many times we want the computer to do something. Let's look at an example.
# Let's make a list of numbers.
my_list = [1,2,3,4]
# The list above contains the numbers 1, 2, 3, and 4. Now let's tell the computer to add up all the numbers in the list using
# a for loop.
running_total = 0 # we create a variable called running_total which we will use to add up our numbers
for number in my_list: # this tells the computer to run through our list and grab one number from it at a time
print('We are currently on the number', number) # this shows us what number we are on
running_total = running_total + number # this tells the computer to take the number we are currently at in our list and
# add it to the running total
print('Our current running total is', running_total) # this shows us what our running total is at each step
# When we run this code, we see that the computer does exactly what we said it woud do. This example shows us the basic
# syntax of a for loop. In general, the syntax is:
# for item_variable_name in list_of_items:
# do something
# do more things
# do even more things
# Here list_of_items is a list of things you want to iterate over, and item_variable_name is the variable name that you will use
# for each item in the list. It's important that you include the colon at the end of the first line, and you indent any
# following lines that you want included in your for loop.
We are currently on the number 1 Our current running total is 1 We are currently on the number 2 Our current running total is 3 We are currently on the number 3 Our current running total is 6 We are currently on the number 4 Our current running total is 10
As mentioned in the example, there are many other ways one can use a for loop, but this is good enough for now.