CSc 250: Lecture Notes: printing, math, and types in python

Printing

As we know by now, echo is used in bash to print a string of characters to stdout. Similarly, we can use print() in python. That being said, let’s write our very first python, very simple, python program:

>>> print('Hello World')
Hello World

print() is a python built-in function. As the name suggests, this function prints whatever text (string) data is passed to it within the parentheses. In python, when calling functions (including print), one writes the name of the function, and then places the arguments to the function in parentheses. In this case, we passed one string argument to print(). In python, strings must always be surrounded by ' (or ") characters, to indicate the beginning and end of the string. Strings will be covered in more depth soon.

We will cover built-in functions, function calls, and writing our own functions later in the course. For now, all we need to know is that this is how things are printed to stdout in python.

Numbers and math

So far, all that we’ve learned to do with python is print characters to stdout. Python can also be used as a calculator, and is capable of many math operations.

We can add:

>>> 3 + 5
8
>>> 123 + 456
579
>>> 3.14 + 1.1111
4.2511
>>>

And subtract:

>>> 3 - 5
-2
>>> 789 - 111
678
>>> 2.222 - 1.111
1.111
>>>

And multiply:

>>> 3 * 5
15
>>> 12 * 12
144
>>> 1.1 * 1.1
1.2100000000000002
>>>

And divide:

>>> 1.0 / 2.0
0.5
>>> 75 / 3
25
>>>

Python is capable of even more math operations, which we will talk about more later in this lecture. All of the above operations can be combined as well. For example:

>>> 42 + 40 - 30
52
>>> 3 * 5 - 2
13
>>>

Try a few combinations of these operators on your own, and see if you get what you expect.

When combining these operators on numbers, it is important to keep in mind the order of operations. In algebra class, you probably had to study the order of operations for addition, subtraction, multiplication, and division. In general, the order of math operations in python is the same as it is for algebra. Multiplication and division take precedence to addition and subtraction. You can also use parenthesis to force a particular order of operations, just like in algebra class.

When we run:

>>> 40 + 20 / 4
45

This is equivalent to running:

>>> 40 + ( 20 / 4 )
45

Even though the division operator is listed after the addition operator, it is executed first because it has mathematical precedence. We can force the addition to happen first by executing:

>>> ( 40 + 20 ) / 4
15

And as can be seen, this produces a different result. Let’s look at another example. What do you think will happen when 40 - 5 * 17 + 22 / 2 is executed? Before reading through my explanation of it below, try to think it through and figure out the order of operations and the resulting value.

OK, let’s walk through it:

40 - 5 * 17 + 22 / 2

Is equivalent to:

40 - (5 * 17) + (22 / 2)

So 5 * 17 and 22 / 2 will be evaluated first, which results in:

40 - (85) + (11)

Which is:

40 - 85 + 11

Which is -34. Indeed, when we run this in python, that is the result returned:

>>> 40 - 5 * 17 + 22 / 2
-34

If there are multiple operators in the same precedence class, and the order between them is not forced by parentheses, then the operators are evaluated from left to right. The examples below demonstrate this functionality:

>>> 13 - 5 + 4
12
>>> 13 - (5 + 4)
4
>>> (13 - 5) + 4
12
>>> 1300 * 4 / 2 * 2
5200.0
>>> (1300 * 4 / 2) * 2
5200.0
>>> (1300 * 4) / 2 * 2
5200.0
>>> 1300 * 4 / (2 * 2)
1300.0
>>>

If you need to brush up on your order of operation and precedence knowledge, use the order of operations Wikipedia page.

Variables

In python, we can declare variables in a similar way to how variables are declared in bash. For example:

>>> office_number = 826
>>> pi = 3.14
>>> name = "Mr LeBron James"
>>> description = "A really good basketball player who plays for the Cleveland Cavaliers."

All of these are variable declarations. In doing this, we give a name to a particular value in our program. Using variables is a convenient way to store and re-use values in a program. Rather than having to use the literal values (3.14, 826, "Mr LeBron James", etc) throughout the program, the values can be assigned to variables and then referenced when needing to be used. Perhaps we want to print out description in more than one place in our program. Without variables, we would have to write something like:

print("A really good basketball player who plays for the Cleveland Cavaliers.")

Each place it needs to be printed. This would get really annoying if this string needed to be printed in more than 2-3 places.

With the description variable, we could instead do:

print(description)

Not only does this save typing (or copy/pasting), but it makes it much easier to change the description at a later time. If we tried to change it without using variables, the description string would need to be edited in each place it is used in the program. Using variables, it only needs to be changed in one place (where the variable is declared), because all of the print() calls reference the variable.

Each variable has a unique name. A variable name cannot contain a space, but can contain all alphanumeric characters, as well as several special symbols such as _ and -. _ and - are commonly used in lieu of spaces. Python variables cannot begin with a number.

>>> 8teen = 18
  File "<stdin>", line 1
      8teen = 18
          ^
SyntaxError: invalid syntax

As can be seen, an error will be generated if this is attempted.

Types

In python, each variable has a type. There are many built-in types in python, and we likely will not cover all of them in this class. However, we will discuss many of the important ones for beginners to know, and today we start with a few.

Boolean

Boolean variables are fairly straightforward to understand. A boolean variable can have two possible values: “true” or “false”. A boolean variable is used to represent a truth-value. For example:

>>> the_sky_is_blue = True
>>> the_sky_is_blue
True
>>> the_sky_is_green = False
>>> the_sky_is_green
False
>>>

The type of a variable can be checked using the built-in call type():

>>> type(the_sky_is_blue)
<class 'bool'>

This tells us that the variable is a bool (boolean) type.

In python, we can use a variety of keywords to combine boolean values to make boolean expressions. And expression is a set of python code that represents some value (could be a number, a boolean, a string, or something else). Specifically, we are going to discuss how to use and, or, and not to create complex expressions with booleans.

To check if two variables (or values) are both true, and can be used: X and Y is true only if X is True and Y is True. and represents logical conjunction. A few examples:

>>> the_sky_is_blue = True
>>> the_sky_has_clouds = True
>>>
>>> the_sky_is_green = False
>>> the_sky_is_purple = False
>>> 
>>> the_sky_is_blue and the_sky_has_clouds
True
>>> the_sky_is_blue and the_sky_is_green
False
>>> the_sky_is_purple and the_sky_is_green
False
>>> the_sky_is_blue and True
True
>>> the_sky_is_purple and True
False
>>> True and True
True
>>> False and False
False
>>> False and True
False

The and keyword takes two arguments (one to the left, and one to the right). It evaluates each side. If both sides evaluate to True, it returns True. Otherwise, it always evaluates to False.

The or keyword is used similarly, but it is semantically different. X or Y is true if X is True, or if Y is True, or if both X and Y are True. or represents logical disjunction. A few examples:

>>> the_sky_is_blue or the_sky_has_clouds
True
>>> the_sky_is_blue or the_sky_is_green
True
>>> the_sky_is_purple or the_sky_is_green
False
>>> the_sky_is_blue or True
True
>>> the_sky_is_purple or True
True
>>> False or True
True
>>> True or True
True
>>> False or False
False
>>>

The not keyword operates on a single boolean variable (or expression). not represents logical negation not evaluates to the opposite boolean value of the variable that follows it. For example:

>>> not the_sky_is_blue
False
>>> not the_sky_is_green
True
>>> not True
False
>>> not False
True

I encourage you to try out various combinations of these operators on your own.

Numbers (int, float, complex)

Numbers are also commonly used and needed when writing programs. Today, we are going to spend time talking about the types of numbers that python supports. In general, there are three types of python number types: int, float, and complex.

As the name suggests, the int type represents mathematical integers (A number that can be written without a fractional component). The following numbers are integers: 1, 5, 387, 0, -4, -76, etc. The following numbers are not integers: 0.0001, -1.456, 3.14, 7.777777, 14723.1

Float numbers are numbers that can contain a fraction (decimal) component. All of the numbers shown above are valid floats in python.

The complex type is used to represent mathematical complex numbers. This type is not commonly used, and will not be needed for this class, so we will ignore it for now. Feel free to do some research on your own if really interested.

Here are some example integer operations:

>>> james = 23
>>> curry = 30
>>> bledsoe = 2
>>>
>>> type(james)
<class 'int'>
>>>
>>> james + curry
53
>>> james + curry + bledsoe
55
>>> james - curry + bledsoe
-5

As would be expected, many of the common math operators on your keyboard will work with both integers and floats:

>>> pi = 3.14
>>> two_pi = 6.28
>>> neg_pi = -3.14
>>> 
>>> pi + two_pi
9.42
>>> pi + neg_pi + two_pi
6.28
>>> pi + neg_pi
0.0
>>> two_pi - pi + neg_pi
0.0
>>> type(pi)
<class 'float'>
>>>

What happens when types are combined in math operations?

>>> james + pi
26.14
>>> jp = james + pi
>>> type(jp)
<class 'float'>
>>> type(james)
<class 'int'>

When arithmetic is done with a float and an int, the value of the int (james) is converted to a float during the operation. However, the type of the variable james does not change.

What do you think happens when we assign a float to an int variable, or vice-versa?

>>> james = 23
>>> type(james)
<class 'int'>
>>> james = 23.0
>>> type(james)
<class 'float'>
>>> 
>>> pi = 3.14
>>> type(pi)
<class 'float'>
>>> pi = 314
>>> type(pi)
<class 'int'> 

The variable type conversion happens automatically!

Numbers and Math

Python has many math operators, which work with both integers and floats. Below are short examples of how to use each of them. I encourage you to try these experiments out on your own, and build upon them with more complex examples.

Addition:

>>> 3 + 7
10
>>> 3.2 + 7.3
10.5

Subtraction:

>>> 3 - 7
-4
>>> 3.2 - 7.3
-4.1

Multiplication:

>>> 3 * 7
21
>>> 3.2 * 7.3
23.36

Division:

>>> 3 / 7
0.42857142857142855
>>> 7 / 3
2.3333333333333335
>>> 3.2 / 7.3
0.4383561643835617

Floor division:

>>> 3 // 7
0
>>> 7 // 3
2
>>> 3.2 // 7.3
0.0

Modulus:

>>> 19 % 4
3
>>> 19 % 5
4
>>> 19 % 6
1

Exponent:

>>> 3 ** 2
9
>>> 4 ** 3
64
>>> 4.2 ** 5
1306.9123200000004

Numbers and comparison

Python has many comparison operators. Comparison operators take two values (left-hand side and right-hand side) and return a boolean, indicating the result of the comparison. Below are several examples of using comparison operators:

Equality:

>>> 3 == 5
False
>>> 3 == 3
True
>>> 3.2 == 3.2
True
>>> 3.2 == 3.7345
False

Inequality:

>>> 3 != 5
True
>>> 3 != 3
False
>>> 3.2 != 3.2
False
>>> 3.2 != 3.7345
True

Less than (LT) and greater than (GT):

>>> 3 < 5
True
>>> 3 > 5
False
>>> 3.492 < 5.234
True
>>> 3.492 > 5.234
False

Less-than-or-equal-to (LEQ) and greater-than-or-equal-to (GEQ):

>>> 3.1 <= 3.1
True
>>> 3.1 <= 3.2
True
>>> 3.1 >= 3.2
False

TutorialsPoint has a great article discussing the basic operator types in python.

Strings

We have already used some strings in python, such as when we first ran print("hello World"). A str (string) type in python is a sequence of characters. A string can be declared by using normal assignment, like we have used for booleans and integers. A string can be defined in several ways.

Double-quotes:

name = "Lebron James"

Single-Quotes:

name = 'LeBron James'

The single or double quote is used to determine the beginning and end of the string. One reason why it is useful to have both ways of defining a string is that when single-quotes are used, double-quotes can be placed in the string. When double quotes are used, single-quotes can be used in the string.

>>> name = 'Steph "thirty" Curry'
>>> print(name)
Steph "thirty" Curry
>>>
>>> name = "Steph 'thirty' Curry"
>>> print(name)
Steph 'thirty' Curry
>>> 
>>> name = 'Steph 'thirty' Curry'
  File "<stdin>", line 1
    name = 'Steph 'thirty' Curry'
                        ^
SyntaxError: invalid syntax
>>> 
>>> name = "Steph "thirty" Curry"
  File "<stdin>", line 1
    name = "Steph "thirty" Curry"
                        ^
SyntaxError: invalid syntax

If we try to use single-quotes in a single-quoted string (and similarly, double-quotes in a double-quoted string), we end up with a SyntaxError, indicating that we used the wrong programmatical syntax when declaring the string.

String operators

Some of the operators we learned about when studying numbers can also operate on strings. However, they work a bit differently, so lets cover a few common ones here:

+ (Concatenation)

The + sign concatenates two strings together:

>>> player1 = "LeBron James"
>>> player2 = "Steph Curry"
>>> players = player1 + " and " + player2
>>> print(players)
LeBron James and Steph Curry

String multiplication

The * operator multiplies strings:

>>> ' Hello World ' * 4
' Hello World  Hello World  Hello World  Hello World '
>>> 
>>> 'ABC' * 14
'ABCABCABCABCABCABCABCABCABCABCABCABCABCABC'

String equality

The == operator can be used to compare the equality of two strings. Similarly, the != operator can be used to check that two strings are not equal. Some examples:

>>> title = "The amazing race"
>>> another_title = "Around the world in 80 days"
>>> 
>>> title == another_title
False
>>> title == "The amazing race"
True
>>> title == "..The amazing race.."
False
>>> title != another_title
True
>>> title != "The amazing race"
False
>>> title != "..The amazing race.."
True
>>> 

String comparison

The <, >, <=, >= operators can be used to check if two strings are less than, greater than, less than or equal to, and greater than or equal to, respectively.

These comparison operators compare strings lexicographically. From the official python docs:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

In the case of letter, for example, “a” is less than “b”, “b” is less than “c”, and so on.

Below are several examples of using these comparisons on strings. You are encouradged to play around with these various comparison operators until you are comfortable with ho they work when using various types of characters.

>>> "a" < "b"
True
>>> "b" < "c"
True
>>> "a" > "b"
False
>>> "b" > "c"
False
>>> "Annie" < "Billy"
True
>>> "Candice" < "Billy"
False
>>> "Zach" < "Zach"
False
>>> "Zach" > "Zach"
False
>>> "Zach" <= "Zach"
True

Converting types and printing

In the print() function, we can use the operators to concatenate and multiply strings:

>>> print( "This is " + "Really Cool" )
This is Really Cool
>>> print( "This is cool " * 5 )
This is cool This is cool This is cool This is cool This is cool 
>>> 

What if we want to print a number, or boolean?

>>> age = 45
>>> print( "Your age is: " + age )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: must be str, not int

We cannot use the + on a string and an int, because the + operator means two different things for each of those types. In order to print out the number age, we must convert it to a string.

One type can be converted to another type using type casting. The inner-workings of type-casting is relatively complex, but doing it in your code is easy. To do so, just use the syntax name_of_type(thing_to_convert). A few examples:

>>> curry = 30
>>> type(curry)
<class 'int'>
>>>
>>> curry_str = str(curry)
>>> type(curry_str)
<class 'str'>
>>> 
>>> curry_float = float(curry_str)
>>> type(curry_float)
<class 'float'>
>>> 
>>> curry_int = int(curry_float)
>>> type(curry_int)
<class 'int'>

Cool! So, to print out age in our other example, we can do:

>>> print( "Your age is: " + str(age) )
Your age is: 45

Another example:

>>> age = 45
>>> 
>>> favorite_number = 3.14
>>> 
>>> print( "Your age is: " + str(age) + " and your favorite number is: " + str(favorite_number) )
Your age is: 45 and your favorite number is: 3.14

A great technique for printing chains of values is to use a combinations of strings, the concatenation operator (+), and casting non-string values to strings using str().