DEV Community

Cover image for Words, Numbers, & Variables, Oh My
Vicki Langer
Vicki Langer

Posted on • Edited on

Words, Numbers, & Variables, Oh My

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.


Jump To:

Programming’s Building Blocks - Data Types

Think about the world around you. There are lots of different types of things, right? We can take all of those things and break them down into different types. For everything we see, we’ll call them different pieces of data or information. Each piece of data can be broken down into different types. These different types are the building blocks of programming. We’ll go into more detail on all of these, but for the most part, we have words, numbers, and true or false things.

Look around you and take in your surroundings. We’re going to use them to make these data types. I’ll give examples with my surroundings, but please do use your own.

For me, my surroundings have:

  • a bookshelf with 23 books on it
  • a half-full (or half-empty?) water bottle
  • a dog bed with 2 cats sleeping on it
  • a keyboard with 68 keys on it

Strings

The first type of data we’ll use is called a string. A string is a bunch of characters (eg. letters, numbers, symbols) surrounded by quotes. Strings can be a single letter, a word, a sentence, or even a whole book.

Strings can use "" but they can also use single quotes, an apostrophe, ''. They must be in pairs though. If the quotes don’t match on both ends of a string, like this ’puppies”, it won’t work.

From my surroundings, I could have:

"Felix Ever After"
'They Both Die At The End'
"The Dangerous Art of Blending In"
"keyboard"
"Remmy and Beans are the 1 cats on the dog’s bed"
Enter fullscreen mode Exit fullscreen mode

If you want your string to show on multiple lines, you can surround it with three pairs of quotes. Here’s an example of a multi-line string with a dog haiku.

"""How do I love thee?
The ways are numberless as
My hairs on the rug.
-Author unknown
"""
Enter fullscreen mode Exit fullscreen mode

Useful Built-in Functions for Strings

Functions are actions you can use with your data. Python has a bunch that are already pre-built and ready for use. In order to use them, we first need to know the syntax, functionname(“your string”). Some helpful built-in functions for strings are len(), min(), and max().

  • len() - returns the length
  • min() - returns the smallest value; “A” being the smallest
  • max() - returns the biggest value; “z” being the biggest; capitals being smaller than lowercase
  • chr() - returns the character associated with a given Unicode number, “chr” is short for character
  • ord() - returns the Unicode number associated with a given character

Here are some examples. Try printing them.

len(Kitties)
min(Kitties)
max(Kitties)
chr(86)
ord("V")
Enter fullscreen mode Exit fullscreen mode

You may not use them often, but with chr() and ord() is it helpful to know that each character is assigned and associated with a unicode code number. You can use ord() to find out what that number is or you can look it up at https://www.lookuptables.com/text/ascii-table. You’ll find that lowercase letters range from 97 to 122 and uppercase numbers range from 65 to 90. With that known, 97 a is the lowercase version of 65 A.

a line showing uppercase A 65 to uppercase Z 90 and lowercase a 97 to lowercase z 122
Note, we are about to talk about the .upper() method. Later on, we’ll learn how to code that using chr() and ord().

Some Methods You Can Use with Strings

Methods are special functions available based on an object’s type. We just learned that strings are a type. Let’s go over some methods we can use on strings. First, we should talk about how to use them or the syntax. String methods will look like ”your string”.methodname(). Sometimes there will be something in the parentheses, but not always.

  • ”your string”.upper() - returns string all uppercase
  • ”your string”.title() - returns string with first letter of each word uppercase
  • ”your string”.split() - returns your string cut up at it’s spaces and put into a list Here are some examples. Try printing them.
"Chickens slipping on a fondue fountain".upper()
"Llamas melting on a math recipe".title()
"Snakes jumping on a potato pie".split()
Enter fullscreen mode Exit fullscreen mode


By the way, you can use multiple methods together. We call it method chaining. In order to chain methods, you put one method first, then the next one. They will still be separated by a .. The methods will be applied in the order they are given. The below example will take the string and make each word start with an uppercase letter, then make all of the letters uppercase, lastly, it’ll cut the words apart and put them into a list. We’ll talk about lists later, don’t worry about them yet.

"Llamas melting on a math recipe".title().upper().split()
Enter fullscreen mode Exit fullscreen mode

Yes, this is a goofy example. I can’t actually think of a time it would make sense to chain .title() and .upper(), but it is possible.

Numbers

The next type of data we’ll use is not called numbers. Instead, numbers are broken down into two different types. We have whole numbers and decimal numbers.

Numbers do not need and should not have any quotes around them unless they are part of a string. Being part of a string would make them a string and not a type of number.

Integers

Just like in math class, integers are whole numbers. Integers are never decimals or fractions. They are whole things. For example, you wouldn’t have 1.7 airplanes or 2.3 dogs. For things like this, you want to use the integer data type.

From my surroundings, I could have:

23 # books
2  # cats
68 # keys on the keyboard
Enter fullscreen mode Exit fullscreen mode

Note: unlike real life, we don’t include commas in our numbers. If you have 1,000,000 it would just be 1000000.

Useful Built-in Functions for Integers

We have built-in functions for whole numbers too!

  • pow() - returns 1st number to the power of the second number, exponents
  • abs() - returns the absolute value or positive of a negative number Here are some examples. Try printing them.
pow(2, 3)  # 2 * 2 * 2
abs(-3)  # |3|
Enter fullscreen mode Exit fullscreen mode


​​

Floats

Similar to integers, but not the same, we have a type of data called floats. Floats are also called floating-point numbers. Floats are numbers with decimals. Floats can also be whole numbers, but typically only when you may need to count the portion of a thing.

From my surroundings, I could have:

0.5
Enter fullscreen mode Exit fullscreen mode

In this example, I only have the contents of my water bottle. From my surroundings, unless they’re broken, I can’t very well have a decimal number of books, cats, or keyboards.

Useful Built-in Functions for Floats

I’m sure it comes as no surprise that floats have some built-in functions.
Here are some examples. Try printing them.

  • pow() - returns 1st number to the power of the second number, exponents
  • `abs()’ - returns the absolute value or positive of a negative number
  • round() - returns a rounded decimal Here are some examples. Try printing them. python pow(4.1, 2) abs(-3.234) round(3.65) round(1.29)

You’re yes then you’re no - Booleans

The last type of data we are going to cover is boolean. Like numbers, booleans do not need and should not have any quotes. They must start with a capital letter. Your only two options are the keywords True and False.

Booleans use True and False but they can be used as stand-ins for yes/no and on/off. If you choose to think of booleans as, yes/no or on/off, use True for “yes” & “on” then use False for “no” & “off”.

From my surroundings, I could have:

python
True # Remmy is sleeping
False # Beans is sleeping
False # Water bottle is full

Keep Your Data Dry with Variables

Now that we know the different types of data, let’s find a way to use each piece of data without having to type it over and over again. In programming, this concept of not retyping things is called Don’t Repeat Yourself(DRY). Variables help us keep code dry by holding data for us.

Writing variables is incredibly similar to math class where you may have had x = 5 to mean there are 5 watermelons. The biggest and best difference is that we don’t typically use x. Instead, we give descriptive names that help us understand what data we are working with. Instead of a letter variable, we can actually say what the variable stands for. Instead of x = 5 we could have watermelon_count = 5.

Picking out a Name

There are some rules with naming that have to be followed or your code won’t work as expected. Then there are some suggestions that you may or may not find helpful.

Here are the requirements:

  1. Must start with a letter or _
  2. Not allowed to use keywords (words set aside for different processes)
  3. Use lowercase letters and numbers
  4. No spaces, use _ instead

Some suggestions to make your life easier:

  • Make the names descriptive
  • Include the data type or structure
  • Avoid single letter and atypically shortened names
  • Variables are typically nouns

From my surroundings, I could have:
python
books_count_int = 23
cat_one_name = "Remmy"
cat_two_name = "Beans"
water_level = 0.5
keys_count_int = 68
cat_one_sleeping = True
cat_two_sleeping = False

Did you notice that with the variable names, I didn’t have to include comments and you understood what each of those numbers meant? That’s why descriptive names are important. Had I called something x, you wouldn’t have known which thing I was referring to.

Assignment

Did you notice above where we used = for our variables? We call the = an assignment operator. I know it’s an equals sign, but I find it helpful to read it as “is”. In cat_one_name = "Remmy", I would read this out loud as “cat one name is Remmy”.
Whatever is on the left of the = is the variable name. The data on the right side is the value being assigned to the variable.

More Dry with Built-ins and Methods

Remember earlier where we printed the outcome of those built-in functions and methods? Let’s find a better way to get data from those. Before we do that, can we adjust each example line to use a variable?
python
cat_str = “Kitties”
len(cat_str)
min(cat_str)
max(cat_str)

Instead of printing each line, we can make them into variables. We call this “saving into a variable”. When you use, or run, a function or method in return it gives you some data. Usually, we will want to save that data to use later.

`python
cat_str = "kitties jumping on a trampoline"
cat_str_len = len(cat_str)
cat_str_min = min(cat_str)
cat_str_max = max(cat_str)
heading = cat_str.title()

print(heading)
print(cat_str, "is", cat_str_len, "characters long")
print(cat_str, "biggest letter:", cat_str_max, "smallest letter:", cat_str_min)
`

In this example, we could have easily counted how long the string was, but not everything will be that short. We were able to save the length of the string into a variable and use it later. This will become even more helpful as we learn more things.

A Teensy Tiny Bit of Math

I know, I know. I said there wouldn’t be a lot of math and it feels like everything has been about math. Whether we like it or not, a lot of the cool things we can do are based on some math concepts. For example, you can add and multiply words. Adding words is called concatenation but if you prefer, you can call it “smashing multiple strings together”.

python
short_greeting = "hey"
long_greeting = short_greeting * 3
different_greeting = short_greeting + "you"

If you put this code into Python Tutor, you’ll get the below. On the right, it will show you your variables and what values they hold.

Notice that you can mix variables and data when using these math operators.

Screenshot of Python tutor:  code:<br>
short_greeting = “hey”<br>
long_greeting = short_greeting * 3<br>
different_greeting = short_greeting + “you”<br>
 then it shows a chart to the right Frames<br>
Global frame<br>
short_greeting  long_greeting "heyheyhey"
different_greeting "heyyou"
"/>

By the way, we also have addition +, subtraction -, multiplication *, and division /. These all work exactly as you would expect. They follow the same order of operations (eg PEMDAS or BODMAS) that you learned in math class. You may also choose to put parentheses () around things you would like done first.

There is another math operator %, called modulus. It looks like and is a percent sign. However, it does something very different. % is used like / but it gives the remainder instead.

Let’s use some variables and do a little math. We have some fruits and we want to share them with a group of people. If you divide them, you’ll find you would have to cut fruits in order to split them evenly. Instead, we can use % or modulus to find out how many fruits are remaining. You can choose what to do with the remaining fruits.

python
kiwis = 10
apples = 7
total_fruits = kiwis + apples
people = 6
fruits_per_person = total_fruits / people
fruits_left_over = total_fruits % people
print(fruits_left_over)

If you run this code in Python Tutor, it will look like this. On the right, it has an output box where all of your print() statements show up. Under that it says “Frames”, that’s where it will show you your variables and what values they hold.
Screenshot of Python tutor: code:<br>
kiwis = 10<br>
apples = 7<br>
total_fruits = kiwis + apples<br>
people = 6<br>
fruits_per_person = total_fruits / people  <br>
fruits_left_over = total_fruits % people<br>
print(fruits_left_over)<br>
 then it shows a chart to the right Frames<br>
Global frame<br>
kiwis   10<br>
apples  7<br>
total_fruits    17<br>
people  6<br>
fruits_per_person   2.8333<br>
fruits_left_over    5<br>


Do you remember?

Here's some practice challenges. Let’s practice what we’ve learned so far. Go ahead and comment on this post with your answers. Do you remember? If not, you can always go back to read sections again.

Match data with their data types

Match each block on the left with its data type on the right. Each data type block should be used only twice.
On the left, there are lego building blocks with different data type examples on them. On the left, there are lego building blocks with the data types on on them. The left has 3.14<br>
True<br>
92802834<br>
False
"It’s True"
185
4591.28701
The right has: Boolean, Float, String, Integer"/>

Give an example or three of each Type of Data

Example 1 Example 2 Example 3
String
Integer
Float
Boolean

Can You Fix What’s Wrong with These?

Some of these have more than one right answer. Believe in yourself and give it a try.

'234 Puppies in 3 bathtubs" 45,345.012
true 291’345’710.5
27,345,192 90.0000° N, 135.0000° W
"4,823 bunnies frolicking in a field' Off

Make some Variables with each Type of Data

Example 1 Example 2 Example 3
String
Integer
Float
Boolean

How would you read these out loud?

Examples
book_name = "The Meet Cute Diary" print(book_name)
cat_summoning_spell = "Here, " + ("Kitty " * 3)
people = 7 treasure_chest_loot = 1000000 gold_coins_leftover = treasure_chest_loot % people

Top comments (0)