@gdiannarbor | #GDIA2 | #IntroToPython
We can tell the computer to compare values and return True or False. These are called Boolean expressions
==
. We can't use =
because that is used for assignment>
and <
a = 5
b = 5
print(a == b)
# Combine comparison and assignment
c = a == b
print(c)
print(3 < 5)
The following chart shows the various Boolean operators
a == b |
a is equal to b |
a != b |
a does not equal b |
a < b |
a is less than b |
a > b |
a is greater than b |
a <= b |
a is less than or equal to b |
a >= b |
a is greater than or equal to b |
a = 3
b = 4
print(a != b)
print(a <= 3)
print(a >= 4)
Remember: Equals does not equal "equals equals"
When we want different code to execute dependending on certain criteria, we use a conditional
We achieve this using if statements
if x == 5:
print('x is equal to 5')
We often want a different block to execute if the statement is false.
This can be accomplished using else
if x == 5:
print('x is equal to 5')
else:
print('x is not equal to 5')
In Python, blocks begin when text is indented and
ends when it returns to the previous indentation
Let's look at the previous example again with a few minor changes and examine the meaning of its indentation
if x == 5:
print('x is equal to 5')
x_is_5 = True
print('Still in the x == 5 block')
else:
print('x is not equal to 5')
x_is_5 = False
print('Still in the else block of x == 5')
print('Outside of the if or else blocks.')
print('x_is_5:')
print(x_is_5)
Conditionals can also be chained
Chained conditionals use elif
as an additonal check after the preceeding if
predicate was False. For example
if x > 5:
print('x is greater than 5')
elif x < 5:
print('x is less than 5')
else:
print('x is equal to 5')
Conditionals can also be nested
Nested conditionals occur inside of other conditionals and are indented over once more.
When the code block is complete, they are unindented
if x > 5:
print('x is greater than 5')
if x > 10:
print('...it is also greater than 10')
print('Done evaluating the x > 10 block')
print('Done evaluating the x > 5 block')
Write a program that uses if statements to determine
what to do given some user input
The code below is an example:
health = 100
print("A vicious warg is chasing you.")
print("Options:")
print("1 - Hide in the cave.")
print("2 - Climb a tree.")
input_value = input("Enter choice:")
if input_value == '1':
print('You hide in a cave.')
print('The warg finds you and injures your leg with its claws')
health = health - 10
elif input_value == '2':
print('You climb a tree.')
print('The warg eventually looses interest and wanders off')
It is often useful to perform a task and to repeat the process until a certain point is reached.
The repeated execution of a set of statements is called iteration
One way to acheive this, is with the while loop.
x = 10
while x > 0:
print(x)
x = x - 1
print('Done')
The while statement takes a predicate, and as long as it evaluates to True, the code block beneath it is repeated.
This creates a loop. Without the x = x - 1
statement,
this would be an infinite loop
Consider the following example that uses iteration to derive a factorial
A factorial of a number is equal to that number * every positive integer less than that number. E.g. The factorial of 4 is 4 * 3 * 2 * 1, which equals 24
input_value = input('Enter a positive integer:') # input('')
n = int(input_value)
result = 1
while n > 1:
result = result * n
n = n - 1
print("The factorial of " + input_value + " is:")
print(result)
This implementation does not work for negative numbers. Why?
It is also useful to loop through a collection of elements, visiting each one to do some work, then stopping once all elements are processed.
This can be accomplished with a for loop
First, we need a collection. We create a list of numbers to loop over. This is called numbers
in the following example
numbers = [1, 3, 8]
for number in numbers:
print("The current number is:")
print(number)
Let's examine the example carefully
numbers = [1, 3, 8]
for number in numbers:
print("The current number is:")
print(number)
The for loop has three parts:
A named section of code that performs a specific task
When one uses a function, one makes a function call
We have already made a function call
when using the type
, int
, or float
functions
a = '3'
print(type(a))
a = float(a)
a = 3
print(type(a))
A function can take arguments
In the example above, the variable a
is passed
as an argument to the function type
Arguments can also be called parameters
# Some more function call examples
int('32')
str(32)
The following example is a function definition.
This allows us to create our own functions
def print_plus_5(x):
print(x + 5)
The function definition has the following parts
def
keyword signifies we are defining a functionprint_plus_5
x
print x + 5
A function can also return a value
To do this, one uses the return keyword
def plus_5(x):
return x + 5
y = plus_5(4)
plus_5(4)
evaluates to 9, and y
is set to this valueA function does not have to take arguments,
as in the following example:
def newline():
print('')
newline()
# prints an empty line. Nothing is returned
This is useful when the function does some work but doesn't need any parameters.
i.e. The function is intended to always do the same thing
A function can also take more than one argument separated by commas. For example:
def find_rectangle_area(width, height):
return width * height
area = find_rectangle_area(3, 4)
# area is set to the value 12
The scope of a variable is the area of code in which a variable is still valid and can be used.
Variables defined within a function can not be used elsewhere.
def get_triangle_area(base, height):
rect_area = base * height
return rect_area / 2.0
triangle_area = get_triangle_area(10, 20)
print(height)
# NameError
print(rect_area)
# NameError
The import statement allows us to use Python code that is defined in other files
Import statements can be used to import various specialized modules - such as scikit or nympy - into our code
module: A published collection of useful functions for doing a specific type of coding. There are math, statistics, data science, and graphics modules, to name a few types.
The from keyword allows us to only import parts of a Python file
from math import sqrt
sqrt(2)
#At the top of the file
from random import randint
# Use this line where you need to have a random number.
# (Hint, this is probably used before the user input loop)
random_number = randint(1, 10)
Write a function that a bar could use to check to see if a customer is of drinking age.
isOfDrinkingAge(age)
If it is a saturday in spring and it is above 65 degrees, Kermit plants flowers. Write a function to check whether he will plant flowers today.
willKermitPlantFlowers(dayOfWeek, season, currentTemperature)
Zach knows something is wrong with his basement if the temperature is below 50 or the humidity is above 70%. Write a function that can check whether his basement has a problem.
basementIsOk(temperature, humidity)
Given any list of any sort of mixed types,write a function that prints the type each item in the list.
You can try this list:
[1, 'hello', 12.33, 'data', [1,2]]
typeIdentifier(list)
#should output something like this:
1 is a <class int>
hello is a <class string>
12.33 is a <class float>
Write a function that asks the user to guess a number between 1 and 100
If their guess is within 20, tell them they are 'warm'
If their guess is within 10, tell them they are 'hot'
If their guess is within 5, tell them they are 'scalding'
if their guess is within 50, tell them they are 'cool'
otherwise tell them they are 'cold'
If they guess the number, congratulate them and ask if they'd like to play again.
# write a function to...
# ...add 10 to any number
# ...divide any number by 100
# ...add any 2 numbers
# ...subtract any 2 numbers
# ...convert celsius to farenheight
# ...convert farenheight to celsius
# ...convert inches to centimeters
# ...convert centimeters to inches
# ...calculate sales tax for any given total amount
# ...calculate the area of a triangle (1/2 base * height)
# ...calculate the volume of a rectangular prism (length * width * height)
Do this excercise from Learn Python The Hard Way
Make sure to do these problems by hand, not with python!Not on Slack? bit.ly/gdiaa-slack
@gdiannarbor | #GDIA2 | #IntroToPython