Learning about Variables - 🐳#
When we are developing our idea, we sometimes need to use values multiple times or change the value based on our code. This concept is where variables become very helpful. Let’s look at an example.
In this example, we are adding a few numbers together. In this instance, if all we care about is getting the result (similar to a calculator). Then variables are not needed.
5 + 3 + 16
24
But let’s look at an example where we need to get the circumference of a circle using multiple radii. The equation for the circumference of a circle is: \(C = 2 \pi r\)
Let’s say the radius is 5
2 * 3.14159265359 * 5
31.4159265359
OK, how about radius 10 and 11 and 4 and … Well, in this example, we might not want to rewrite 3.14159265359 over and over. So, in this case, we want to create a variable for this, and we will call it pi.
pi = 3.14159265359
Now, every time we reference the variable called pi it will refer to the number 3.14159265359
Let’s try those radii again (10, 11, 4)
2 * pi * 10
62.8318530718
2 * pi * 11
69.11503837898
2 * pi * 4
25.13274122872
By the way, if you happen to get an error:
NameError: name 'pi' is not defined
Make sure you go to the cell that has
pi = 3.14159265359
and run this cell first then try the other calculations.
Type of Variables#
There are multiple types of variables. The most common (and the ones we will talk about) are:
Integers (whole numbers)
Float (Floating points or numbers with a decimal)
Text
Lists
Dictionaries
The nice thing about Python is that we do not need to specify (or declare) which type we are using. Python will figure this out for us!
BUT FIRST, a quick detour…
We need to talk about Camel Casing.
Camel Case#
File:CamelCase new.svg. (2020, April 15). Wikimedia Commons, the free media repository. Retrieved 15:25, June 3, 2020 from https://commons.wikimedia.org/w/index.php?title=File:CamelCase_new.svg&oldid=411544943.
Integers or int#
As mentioned, integers are whole numbers. Let’s create an example. How about we use our numberOfKittens. We will then set this value to 0. As in, we have 0 kittens.
numberOfKittens = 0
One thing we might want to do is to have Python tell us what type this variable is. Well, Python has a function for this called
type()
type( numberOfKittens )
int
So this checks out, we made an int, and it is showing us we have an int.
Now, once we have a variable, it is not static. We can change the value as much as we need to. Running the next cell will continually add 10 to our original variable.
Try running this a few times.
numberOfKittens = numberOfKittens + 10
numberOfKittens
10
or
in more human-readable terms.
numberOfKittens (new value 10) = numberOfKittens (originally 0) + 10
numberOfKittens is now 10
or
Floating points or floats#
Floats are similar to integers, but with more precision. Float comes from a Floating point or a number with a decimal point.
This example starts at 0, but note that this is .0 Adding the decimal tells Python that we should have a float value instead of an integer.
aFloatVariable = .0
Let’s again, check the variable type.
type( aFloatVariable )
float
Looks good.
And again, we will add 10 to this. There is something specific interesting here; see if you spot it.
aFloatVariable = aFloatVariable + 10 aFloatVariable
If you guessed “mixing a float and an integer,” you got it. Let’s see an example.
Mixing integers and floats#
In Python (3, more specifically), the variable will always take the form of the most precision. So, by default, a float.
letsSeeWhatHappens = numberOfKittens + aFloatVariable
letsSeeWhatHappens
10.0
We can force variables to be a certain type. We call this ‘type-cast’ and can be used to:
make an integer into a float
a float to an integer
an integer to a string (we have not discussed this yet)
a float to a string (we have not discussed this yet)
etc…
type-cast#
Note
type-cast is temporary. If you do not use a type-cast, the variable will revert to its original variable type.
Let’s switch our numberOfKittens to a float using
float()
and turn our aFloatVariable to an integer using
int()
float(numberOfKittens)
10.0
int(aFloatVariable)
0
Common Question
What happens when you convert a float like .5 to an integer? Does it round up or down?
Well let’s see what happens.
Show code cell source
printList = []
for i in range(10): printList.append("for value %s we will get %s" % ((i/10),int(i/10)))
display(md('<br />'.join([str(elem) for elem in printList])))
for value 0.0 we will get 0
for value 0.1 we will get 0
for value 0.2 we will get 0
for value 0.3 we will get 0
for value 0.4 we will get 0
for value 0.5 we will get 0
for value 0.6 we will get 0
for value 0.7 we will get 0
for value 0.8 we will get 0
for value 0.9 we will get 0
So, in conclusion. It will always round down.
String or str#
So, up to this point, we started our conversation working with numbers. Well, what about the other things that are not numbers… like text? Well, for text, we use something called a String or str.
Strings allow us to capture a single character up to thousands of characters (actually, much more than this). Let’s go through a traditional example of “Hello, World!” but with my slight spin to it.
helloStatement = "Hello, everyone!"
As you can see, can capture text and other alphanumeric and special characters. There are several unique functions for strings but first, let’s double-check and see what type we from our helloStatement.
type( helloStatement )
str
Not too surprising, we see this is type str or string.
Note
For those coming from another programming language. Sometimes other programming languages will have a specific designation for a single character string or, as it is called, a character. Python has a one-size-fits-all label for text, and that is a string. Here, let me prove it.
singleCharacter = "a"
type( singleCharacter )
str
String Indexing/String Slicing#
One of the first ways to interact with our string is to take a look at individual characters by using their index.
The index is position (or multiple positions) for each character in the string. So, if we look at our string, we have Hello, everyone! If we wanted to see the first letter H, we could reference this using the index or the position where the letter is in the string.
helloStatement[1]
'e'
ohh.. wait a minute. We were expecting the letter H, but we got e. What happened?
Note
For indexes, we always start at the number 0. So, 0 is the first thing, 1 is the second thing, and so on.
Let’s try this again.
helloStatement[0]
'H'
There we go!
Visually, this is how the string looks to Python.
Indexing Multiple Letters#
print( helloStatement[0:5] )
Hello
Wait a second!
The way you should think of this is:
helloStatement[0 : 5 - 1]
helloStatement[(starting number) to (ending number - 1)]
There is also a shortcut way of writing this, without the 0.
print( helloStatement[:5] )
Hello
print( helloStatement[5:] )
, everyone!
String functions#
Find#
print( helloStatement.find("one") )
print( helloStatement.find("me") )
print( helloStatement.find("hello") )
print( helloStatement.find("Hello") )
12
-1
-1
0
Note
When using .find(), if the function can NOT find the sequence of the letters given. It will return -1.
Formatting#
print( helloStatement.capitalize() )
print( helloStatement.lower() )
Hello, everyone!
hello, everyone!
Split#
print( helloStatement.split(" ") )
['Hello,', 'everyone!']
Note
.split() will eventually become your best friend. .split() is a great function to use when using uniquelly spaced data. As in comma separated values or CSV.
Chaining Functions#
print( helloStatement )
print( helloStatement[0:5].capitalize() )
print( helloStatement.find("hello") )
print( helloStatement[:5].lower().find("hello") )
Hello, everyone!
Hello
-1
0
Concatenating Strings#
When you want to put two strings together, we say you concatenate the strings. There are multiple ways of doing this but presented are what I believe to be the three most common ways.
+ Method#
This is the most straightforward method of the three, but there can be some issues. You simply add a plus sign + between your strings. Let’s take a look at this.
print ( "hello, " + "everyone!")
hello, everyone!
This works fine, but when you add a number to this idea. We run into issues.
print ( "hello, " + "every" + 1 + "!")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-1f53f06cad5c> in <module>
----> 1 print ( "hello, " + "every" + 1 + "!")
TypeError: can only concatenate str (not "int") to str
In this case we need to type-cast the integer as a string using
str()
print ( "hello, " + "every" + str(1) + "!")
hello, every1!
% Method#
This is my favorite method out of the three. Let’s see how this works with the same example.
In this case, we use a %s (s = string) for each string we want to embed in our overall string.
print ( "%s, %s" % ("hello", "everyone") )
hello, everyone
There are three parts to this.
The format
"%s, %s"
The break
%
The fill
("hello", "everyone")
We have two %s, meaning we need to feed it with two strings.
OK, but what about numbers?
print ( "%s, %s%s%s" % ("hello","every",1,"!") )
hello, every1!
Still works! This reason is why I like this method. You pick the formating and feed in the strings.
join() Method#
The .join() method uses a function called
.join()
This is a create function to be aware of, as it will allow you the ability to join strings with a specific, static format. What do I mean by static formatting? Well, unlike the % method, that can be formatted exactly how I want it. The .join() method requires a specific pattern. Example time!
print ( " ".join(["hello, ", "everyone!"]) )
hello, everyone!
There are two parts to this.
The splitter
" "
The fill
.join(["hello, ", "everyone!"])
Notice that the join has the brackets around it. Technically, you are feeding this an array or list (we have not talked about this yet). This function again, like .split(), will be a great asset to you in the future.
Let’s show this with our number again.
print ( " ".join(["hello, ", "every", 1, "!"]) )
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-54-e926f0c4c025> in <module>
----> 1 print ( " ".join(["hello, ", "every", 1, "!"]) )
TypeError: sequence item 2: expected str instance, int found
The same issue as before, we need to type-cast.
print ( " ".join(["hello, ", "every", str(1), "!"]) )
hello, every 1 !
Notice the spaces? Again, we are saying with the splitter what each string is going to be seperated by, so in this case, everything will be split by spaces.
Booleans#
Booleans are used to do comparisions (true/false), (1/0), (yes/no)
someCondition = True
type( someCondition )
bool
Boolean Logic#
We will talk about boolean logic more in the next section (Comparisons)
(someCondition == False)
False
if (False):
print( "yes for False!" )
if (True):
print( "yes for True!" )
yes for True!
Note
A more “traditional” way to do booleans is to use 0 and 1. In Python, any number other than 0 is True. Including negative numbers and decimals.
if (0):
print( "yes for 0!" )
if (1):
print( "yes for 1!" )
if (2):
print( "yes for 2!" )
if (-3):
print( "yes for -3!" )
if (.4):
print( "yes for .4!" )
yes for 1!
yes for 2!
yes for -3!
yes for .4!
Lists#
Lists (or also known as Arrays) are exactly that. A list of data.
There are two options for creating a List.
Define the list initially
groceryList = ["apple", "banana", "eggs"]
print( groceryList )
['apple', 'banana', 'eggs']
Create a list and add to it using
.append()
groceryList = []
groceryList.append("apple")
groceryList.append("banana")
groceryList.append("eggs")
print( groceryList )
['apple', 'banana', 'eggs']
Note
For indexes, we always start at the number 0. So, 0 is the first thing, 1 is the second thing, and so on.
print( groceryList[2] )
print( groceryList[0] )
print( groceryList[1] )
eggs
apple
banana
So what happens if we use an index outside of our list?
print( groceryList[3] )
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-44-0a77fb05d512> in <module>
print( groceryList[3] )
IndexError: list index out of range
Note
Typically, going through an array, one index at a time is not how we want to use lists. We will talk about going through lists using a loop in an upcoming notebook.
Dictionary#
Dictionaries are used to index based on a specific key. As in:
dictionary[“street adddress” (key)] = “123 Apple St.” (value)
personalInformation = {}
personalInformation["streetAddress"] = "123 Apple St."
personalInformation["firstName"] = "Patrick"
personalInformation["lastName"] = "Dudas"
print( personalInformation )
{'streetAddress': '123 Apple St.', 'firstName': 'Patrick', 'lastName': 'Dudas'}
Note the order.
Again, to do this more efficiently, we will be using loops (we will talk about later).
Your turn!#
Create a list
append() three items
an integer
a float
a string
print this list
## list create
## append() integer
## append() float
## append() string
## print() list