if / else" statementProgramming is a lot like giving someone instructions or directions. For example, if I wanted to give you directions to my house, I might say...
Turn right onto Main Street
Turn left onto Maple Ave
If there is construction, continue straight on Maple Ave, turn right on Cat Lane, and left on Fake Street; else, cut through the empty lot to Fake Street
Go straight on Fake Street until house 123
The same directions, but in code:
In [ ]:
construction = False
print "Turn right onto Main Street"
print "Turn left onto Maple Ave"
if construction:
print "Continue straight on Maple Ave"
print "Turn right onto Cat Lane"
print "Turn left onto Fake Street"
else:
print "Cut through the empty lot to Fake Street"
print "Go straight on Fake Street until house 123"
This is called an "if / else" statement. It basically allows you to create a "fork" in the flow of your program based on a condition that you define. If the condition is True, the "if"-block of code is executed. If the condition is False, the else-block is executed.
Here, our condition is simply the value of the variable construction. Since we defined this variable to quite literally hold the value False (this is a special data type called a Boolean, more on that in a minute), this means that we skip over the if-block and only execute the else-block. If instead we had set construction to True, we would have executed only the if-block.
Let's define Booleans and if / else statements more formally now.
True or False.True and False are always capitalized and never in quotes. True and False as words! You can't treat them like you would strings. To Python, they're actually interpreted as the numbers 1 and 0, respectively.if / else statementPurpose: creates a fork in the flow of the program based on whether a conditional statement is True or False.
Syntax:
if (conditional statement):
this code is executed
else:
this code is executed
Notes:
True / False) value of a conditional statement, either executes the if-block or the else-blockelse-block is optional. if condition and after the else.if or else blocks must be indented.Example:
In [ ]:
x = 5
if (x > 0):
print "x is positive"
else:
print "x is negative"
So what types of conditionals are we allowed to use in an if / else statement? Anything that can be evaluated as True or False! For example, in natural language we might ask the following true/false questions:
is
aTrue?is
aless thanb?is
aequal tob?is
aequal to "ATGCTG"?is (
agreater thanb) and (bgreater thanc)?
To ask these questions in our code, we need to use a special set of symbols/words. These are called the logical operators, because they allow us to form logical (true/false) statements. Below is a chart that lists the most common logical operators:
Most of these are pretty intuitive. The big one people tend to mess up on in the beginning is ==. Just remember: a single equals sign means assignment, and a double equals means is the same as/is equal to. You will NEVER use a single equals sign in a conditional statement because assignment is not allowed in a conditional! Only True / False questions are allowed!
In [ ]:
a = True
if a:
print "Hooray, a was true!"
In [ ]:
a = True
if a:
print "Hooray, a was true!"
print "Goodbye now!"
In [ ]:
a = False
if a:
print "Hooray, a was true!"
print "Goodbye now!"
Since the line
print "Goodbye now!"is not indented, it is NOT considered part of theif-statement. Therefore, it is always printed regardless of whether theif-statement wasTrueorFalse.
In [ ]:
a = True
b = False
if a and b:
print "Apple"
else:
print "Banana"
Since
aandbare not bothTrue, the conditional statement "a and b" as a whole isFalse. Therefore, we execute theelse-block.
In [ ]:
a = True
b = False
if a and not b:
print "Apple"
else:
print "Banana"
By using "
not" beforeb, we negate its current value (False), makingbTrue. Thus the entire conditional as a whole becomesTrue, and we execute theif-block.
In [ ]:
a = True
b = False
if not a and b:
print "Apple"
else:
print "Banana"
"
not" only applies to the variable directly in front of it (in this case,a). So here,abecomesFalse, so the conditional as a whole becomesFalse.
In [ ]:
a = True
b = False
if not (a and b):
print "Apple"
else:
print "Banana"
When we use parentheses in a conditional, whatever is within the parentheses is evaluated first. So here, the evaluation proceeds like this:
First Python decides how to evaluate
(a and b). As we saw above, this must beFalsebecauseaandbare not bothTrue.Then Python applies the "
not", which flips thatFalseinto aTrue. So then the final answer isTrue!
In [ ]:
a = True
b = False
if a or b:
print "Apple"
else:
print "Banana"
As you would probably expect, when we use "
or", we only needaorbto beTruein order for the whole conditional to beTrue.
In [ ]:
cat = "Mittens"
if cat == "Mittens":
print "Awwww"
else:
print "Get lost, cat"
In [ ]:
a = 5
b = 10
if (a == 5) and (b > 0):
print "Apple"
else:
print "Banana"
In [ ]:
a = 5
b = 10
if ((a == 1) and (b > 0)) or (b == (2 * a)):
print "Apple"
else:
print "Banana"
Ok, this one is a little bit much! Try to avoid complex conditionals like this if possible, since it can be difficult to tell if they're actually testing what you think they're testing. If you do need to use a complex conditional, use parentheses to make it more obvious which terms will be evaluated first!
In [ ]:
x = 6 * -5 - 4 * 2 + -7 * -8 + 3
# ******add your code here!*********
Python provides some useful built-in functions that perform specific tasks. What makes them "built-in"? Simply that you don’t have to "import" anything in order to use them -- they're always available. This is in contrast the the non-built-in functions, which are packaged into modules of similar functions (e.g. "math") that you must import before using. More on this in a minute!
We've already seen some examples of built-in functions, such as print, int(), float(), and str(). Now we'll look at a few more that are particularly useful: raw_input(), len(), abs(), and round().
raw_input()Description: A built-in function that allows user input to be read from the terminal.
Syntax:
raw_input("Optional prompt: ")
Notes:
raw_input() function and wait for the user to input something. raw_input() can then be stored in a variable and used in the code.Examples:
In [ ]:
name = raw_input("Your name: ")
print "Hi there", name, "!"
In [ ]:
age = int(raw_input("Your age: ")) #convert input to an int
print "Wow, I can't believe you're only", age
In [ ]:
print len("cat")
In [ ]:
print len("hi there")
In [ ]:
seqLength = len("ATGGTCGCAT")
print seqLength
In [ ]:
print abs(-10)
In [ ]:
print abs(int("-10"))
In [ ]:
positiveNum = abs(-23423)
print positiveNum
In [ ]:
print round(10.12345)
In [ ]:
print round(10.12345, 2)
In [ ]:
print round(10.9999, 2)
If you want to learn more built in functions, go here: https://docs.python.org/2/library/functions.html
Modules are groups of additional functions that come with Python, but unlike the built-in functions we just saw, these functions aren't accessible until you import them. Why aren’t all functions just built-in? Basically, it improves speed and memory usage to only import what is needed (there are some other considerations, too, but we won't get into it here).
The functions in a module are usually all related to a certain kind of task or subject area. For example, there are modules for doing advanced math, generating random numbers, running code in parallel, accessing your computer's file system, and so on. We’ll go over just two modules today: math and random. See the full list here: https://docs.python.org/2.7/py-modindex.html
Using a module is very simple. First you import the module. Add this to the top of your script:
import <moduleName>
Then, to use a function of the module, you prefix the function name with the name of the module (using a period between them):
<moduleName>.<functionName>
(Replace <moduleName> with the name of the module you want, and <functionName> with the name of a function in the module.)
The <moduleName>.<functionName> synatx is needed so that Python knows where the function comes from. Sometimes, especially when using user created modules, there can be a function with the same name as a function that's already part of Python. Using this syntax prevents functions from overwriting each other or causing ambiguity.
math moduleDescription: Contains many advanced math-related functions.
See full list of functions here: https://docs.python.org/2/library/math.html
Examples:
In [ ]:
import math
print math.sqrt(4)
print math.log10(1000)
print math.sin(1)
print math.cos(0)
random moduleDescription: contains functions for generating random numbers.
See full list of functions here: https://docs.python.org/2/library/random.html
Examples:
In [ ]:
import random
print random.random() # Return a random floating point number in the range [0.0, 1.0)
print random.randint(0, 10) # Return a random integer between the specified range (inclusive)
print random.gauss(5, 2) # Draw from the normal distribution given a mean and standard deviation
# this code will output something different every time you run it!
For the following blocks of code, first try to guess what the output will be, and then run the code yourself. These examples may introduce some ideas and common pitfalls that were not explicitly covered in the text above, so be sure to complete this section.
The first block below holds the variables that will be used in the problems. Since variables are shared across blocks in Jupyter notebooks, you just need to run this block once and then those variables can be used in any other code block.
In [ ]:
# RUN THIS BLOCK FIRST TO SET UP VARIABLES!
a = True
b = False
x = 2
y = -2
cat = "Mittens"
In [ ]:
print a
In [ ]:
print (not a)
In [ ]:
print (a == b)
In [ ]:
print (a != b)
In [ ]:
print (x == y)
In [ ]:
print (x > y)
In [ ]:
print (x = 2)
In [ ]:
print (a and b)
In [ ]:
print (a and not b)
In [ ]:
print (a or b)
In [ ]:
print (not b or a)
In [ ]:
print not (b or a)
In [ ]:
print (not b) or a
In [ ]:
print (not b and a)
In [ ]:
print not (b and a)
In [ ]:
print (not b) and a
In [ ]:
print (x == abs(y))
In [ ]:
print len(cat)
In [ ]:
print cat + x
In [ ]:
print cat + str(x)
In [ ]:
print float(x)
In [ ]:
print ("i" in cat)
In [ ]:
print ("g" in cat)
In [ ]:
print ("Mit" in cat)
In [ ]:
if (x % 2) == 0:
print "x is even"
else:
print "x is odd"
In [ ]:
if (x - 4*y) < 0:
print "Invalid!"
else:
print "Banana"
In [ ]:
if "Mit" in cat:
print "Hey Mits!"
else:
print "Where's Mits?"
In [ ]:
x = "C"
if x == "A" or "B":
print "yes"
else:
print "no"
In [ ]:
x = "C"
if (x == "A") or (x == "B"):
print "yes"
else:
print "no"
Surprised by the last two? It's important to note that when you want compare a variable against multiple things, you only compare it to one thing at a time. Although it makes sense in English to say, is x equal to A or B?, in Python you must write: ((x == "A") or (x == "B")) to accomplish this. The same goes for e.g. ((x > 5) and (x < 10)) and anything along those lines.
So why does the first version give the answer "yes"? Basically, anything that isn't
Falseor the literal number 0 is considered to beTruein Python. So when you say 'x == "A" or "B"', this evaluates to 'False or True', which isTrue!