Introductory Python: Strings, Ints, Floats, and Booleans

by Justin Skycak (@justinskycak) on

We can store and manipulate data in the form of variables.

This post is part of the series Introduction to Python Programming.


Want to get notified about new posts? Join the mailing list and follow on X/Twitter.

View in Colab

Variables

When we program in IPython notebooks, we store and manipulate data in the form of variables.

To assign data a variable name, we use the = symbol. Then, when we print the variable, the data will appear.


my_variable = 'The variable contains this sentence.'
print(my_variable)

OUTPUT
------
The variable contains this sentence.

Exercise 1

Assign 'This is a sentence.' to the variable my_sentence. Then, print the sentence by printing the variable.


# assign 'This is a sentence.' to my_sentence
# print the variable my_sentence

Overwriting Strings

Note that we can also assign an existing variable to a new variable.


my_variable = 'The variable contains this sentence.'
my_variable_again = my_variable
print(my_variable_again)

OUTPUT
------
The variable contains this sentence.

Likewise, we can overwrite an existing variable with new data.


my_variable = 'The variable contains this sentence.'
my_variable = 'This variable has been overwritten with a new sentence!'
print(my_variable)

OUTPUT
------
This variable has been overwritten with a new sentence!

Exercise 2

Overwrite the variable my_sentence with a new sentence 'I have commandeered your sentence.' Then, print the new sentence by printing the variable.


my_sentence = 'This is my sentence.' # overwrite this
# print the variable my_sentence

Strings, Ints, Floats, and Booleans

We will primarily be using 4 types of variables: strings, ints, floats, and booleans.

  • Strings are sequences of characters and are surrounded by quotes. Characters can include not only letters, but also numbers and symbols such as punctuation and spaces. Examples of strings include `'cat'`, `'The dog is happy!'`, and `'asdf1234!! !@#^&'`.
  • Ints are integers such as 1, 2, 3, 512, 87743, and -3432178.
  • Floats are decimals, also known as floating point numbers. Examples of floats include 1.5, 3.141592654, 112.0, and -32.018.
  • Booleans can be either True or False.

Strings

Strings can be concatenated (combined one after another) with the + symbol.


print('a'+'b')

OUTPUT
------
ab

Notice that a space is not automatically added between concatenated strings – so if we want a space, we need to add it manually.


var1 = 'hello'
var2 = ' '
var3 = 'there'
print(var1+var2+var3)

OUTPUT
------
hello there

Strings can also represent symbols other than words.


print('The number 225 is a perfect square! Here are some symbols: @#$&*&^.')

OUTPUT
------
The number 225 is a perfect square! Here are some symbols: @#$&*&^.

Exercise 3

Add the following variables in some order to create the string 'The dog jumped over the cat.'


var1 = 'dog'
var2 = 'over'
var3 = 'cat'
var4 = 'the'
var5 = 'jumped'
var6 = 'The'
var7 = ' '
var8 = '.'

# change this
print(var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8)

OUTPUT
------
dogovercatthejumpedThe .

Indexing

We can pick out an individual character within in a string by using the index of the character. The index just counts how many characters are before our desired character – so the first character in a string has an index of 0, the second character has an index of 1, the third character has an index of 2, and so on.


print('abcdefg'[0])

OUTPUT
------
a

print('abcdefg'[1])

OUTPUT
------
b

print('abcdefg'[2])

OUTPUT
------
c

print('abcdefg'[5])

OUTPUT
------
f

We can also pick out a substring, or a group of characters within a string, by using two indices and a colon. The first index tells us where we should start picking out characters, and the second index tells us where we should stop picking out characters. (The character located at the second index is not included in the substring.)


print('abcdefg'[0:3])

OUTPUT
------
abc

print('abcdefg'[2:4])

OUTPUT
------
cd

print('abcdefg'[3:7])

OUTPUT
------
defg

Exercise 4

Pick out the substring 'shoes have' from the string below. (Remember that spaces count as characters!)


# change the indices 0 and 20 so that the
# resulting substring is just 'shoes have'
print('My shoes have laces.'[0:20])

OUTPUT
------
'My shoes have laces.'

String Functions and Methods

There are various functions and methods that can be used to process strings. For now, you can think of functions and methods in the same way – except that functions are called in the form function(string), whereas methods are applied in the form string.method().

For example, the len() function tells us how many characters are in a string.


print(len('This is a string.'))

OUTPUT
------
17

Likewise, the .upper() method converts all letters in the string to be uppercase.


print('This is a string.'.upper())

OUTPUT
------
THIS IS A STRING.

There are many, many functions and methods that can be applied to strings. As such, we will not go through all of them.

However, it is important to know how to find a function or method when you need it. You can usually find them by searching Google. For example, to find the method or function which converts a string to all lowercase, you can search Google with something like “python string lowercase”.

Exercise 5

Use functions or methods to perform the desired operations on the following strings.


# convert this string to uppercase
print('This should look like shouting.')

OUTPUT
------
This should look like shouting.

# remove spaces from the beginning and end of the string
print('         This should have no spaces at the beginning nor the end.             ')

OUTPUT
------
         This should have no spaces at the beginning nor the end.             

Ints and Floats

Operations on ints and floats follow the rules of mathematics.

Floats and ints are very similar – the only difference is that floats have decimal parts, while ints do not.


print(2 + 3)

OUTPUT
------
5

print(4 - 3)

OUTPUT
------
1

print(6 * 2)

OUTPUT
------
12

print(-4 / 8)

OUTPUT
------
-0.5

Caution 1

In Python, the carrot symbol does not mean exponentiation. If you use the carrot symbol for exponentiation, then your result will probably be incorrect.


# 2 to the power of 3 should be 8...
print(2^3)

OUTPUT
------
1

The way to do exponentiation in Python is to use two multiplication symbols in a row.


# this actually means 2 to the power of 3
print(2**3)

OUTPUT
------
8

Overwriting Floats and Ints

Floats and ints can be assigned to variables and modified through operations on those variables.


a = 1
a = a + 2
print(a)

OUTPUT
------
3

a = 10
b = 5.2
c = (b - 1) * a
print(c)

OUTPUT
------
42.0

Caution 2

Floats are sometimes rounded because the computer can only store a finite number of digits. As a result, operations with floats can be slightly inaccurate due to roundoff error.

In practice, this often won’t pose a problem, since the roundoff error is so small.


# computer will store a value very close to the true value of 0.8
print(4 - 3.2)

OUTPUT
------
0.7999999999999998

However, we can run into serious issues if we try to work with extremely large numbers.

Recall that $\lim_{n \to \infty} \left( 1+\frac{1}{n} \right)^n \approx 2.7182…$

If we approximate this limit using $n=10^6,$ we get a sensible result.


n = 10**6
result = (1 + 1/n)**n
print(result)

OUTPUT
------
2.7182804690957534

However, if we approximate the limit using $n=10^{100}$, we get a nonsense result.


n = 10**100
result = (1 + 1/n)**n
print(result)

OUTPUT
------
1.0

The reason why we get this result is that when n is extremely large, the 1/n part is treated as 0 due to roundoff error. The inside of the parentheses is then treated as 1.0 exactly, and 1.0 raised to any power is still 1.0.


n = 10**6
print(1 + 1/n)

OUTPUT
------
1.000001

n = 10**100
print(1 + 1/n)

OUTPUT
------
1.0

Exercise 6

In the cell below, write c as an expression of a and b so that c takes the value of 15.


a = 3
b = 2.5
c = a - b
print(c)

OUTPUT
------
0.5

Booleans

Booleans can only take two values: True, False. They can be manipulated through logical operations including not, and, or.

The not operation returns the opposite of the boolean to which it is applied.


print(not True)

OUTPUT
------
False

print(not False)

OUTPUT
------
True

The and operation returns True if the booleans preceding and following it are both True.

Otherwise, if at least one of them is False, then the operation returns False.


print(True and True)

OUTPUT
------
True

print(True and False)

OUTPUT
------
False

print(False and True)

OUTPUT
------
False

print(False and False)

OUTPUT
------
False

The or operation returns True if any of the booleans preceding and following it is True.

In order to return False, the or operation requires both of the booleans preceding and following it to be False.


print(True or True)

OUTPUT
------
True

print(True or False)

OUTPUT
------
True

print(False or True)

OUTPUT
------
True

print(False or False)

OUTPUT
------
False

Like strings, ints, and floats, booleans can be assigned to variables and those variables can be manipulated just as the booleans would.

Boolean variables often follow a naming convention is_XXXX where XXXX is some property that another thing may or may not have.


is_open=False
print(not is_open)

OUTPUT
------
True

is_open = True
is_closed = False
print(is_open and is_closed)

OUTPUT
------
True

Exercise 7

Create an expression using the variables is_normal, is_surprising, and is_weird that evaluates to True.


is_normal = False
is_surprising = False
is_weird = True

# change this so that it evaluates to True
print(is_normal and is_surprising and is_weird)

OUTPUT
------
False

Boolean Operations, Functions, and Methods

There are various operations, functions, and methods that return boolean values when applied to strings, ints, and floats. Such operators, functions, and methods are meant to test whether a particular thing or group of things has a particular property.


print(2 > 1)

OUTPUT
------
True

print(5 <= 4.9) # less than or equal to

OUTPUT
------
False

print(1 == 1.0) # tests equality

OUTPUT
------
True

print('asdf'.isdigit())

OUTPUT
------
False

print('1234'.isdigit())

OUTPUT
------
True

print('abc' == 'ABC')

OUTPUT
------
False

print('abc'.upper() == 'ABC')

OUTPUT
------
True

Exercise 8

Use functions or methods to perform the desired operations on the following strings, ints, and floats. (You may have to do some Googling!)


# test if every character in the string is a letter
'asdf98qoiuretkjld'

# test if this is an integer
4.2

Solutions

Exercise 1


my_sentence = 'This is a sentence.'
print(my_sentence)

OUTPUT
------
This is a sentence.

Exercise 2


my_sentence = 'I have commandeered your sentence.'
print(my_sentence)

OUTPUT
------
I have commandeered your sentence.

Exercise 3


var1 = 'dog'
var2 = 'over'
var3 = 'cat'
var4 = 'the'
var5 = 'jumped'
var6 = 'The'
var7 = ' '
var8 = '.'

print(var6 + var7 + var1 + var7 + var5 + var7 + var2 + var7 + var4 + var7 + var3 + var8)

OUTPUT
------
The dog jumped over the cat.

Exercise 4


print('My shoes have laces.'[3:13])

OUTPUT
------
shoes have

Exercise 5


print('This should look like shouting.'.upper())

OUTPUT
------
THIS SHOULD LOOK LIKE SHOUTING.

print('         This should have no spaces at the beginning nor the end.             '.strip())

OUTPUT
------
This should have no spaces at the beginning nor the end.

Exercise 6


a = 3
b = 2.5
c = 30*a - 30*b
print(c)

OUTPUT
------
15.0

Exercise 7


is_normal = False
is_surprising = False
is_weird = True

print(is_normal or is_surprising or is_weird)

OUTPUT
------
True

Exercise 8


print('asdf98qoiuretkjld'.isalpha())

OUTPUT
------
False

print(4.2.is_integer())

OUTPUT
------
False


This post is part of the series Introduction to Python Programming.


Want to get notified about new posts? Join the mailing list and follow on X/Twitter.