2: Numbers and Strings
- Page ID
- 47978
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\ket}[1]{\left| #1 \right>}\)
\(\newcommand{\bra}[1]{\left< #1 \right|}\)
\(\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right| \left. #2 \vphantom{#1} \right>}\)
\(\newcommand{\braopket}[3]{\left< #1 \vphantom{#2}\vphantom{#3} \right| #2 \vphantom{#1}\vphantom{#3} \left| #3 \vphantom{#1}\vphantom{#2} \right>}\)
\(\newcommand{\qmvec}[1]{\mathbf{\vec{#1}}}\)
\(\newcommand{\op}[1]{\hat{\mathbf{#1}}}\)
\(\newcommand{\expect}[1]{\langle #1 \rangle}\)
\(\newcommand{\dfn}[1]{\emph{\textbf{#1}}}\)
In the previous chapter we saw that data scientists apply statistical concepts on a dataset to find patterns or insights from the data. To be efficient with statistical calculations on the data, data scientists take advantage of the fast computation speed of the computer. In this chapter we learn how to use the computer to do math calculations and print the results along with text strings.
We want to write math instructions that can be understood by the computer so that it can follow the instructions and produce the result we need. Writing instructions for the computer to do work is called programming, and the list of instructions makes up a program or code. The language that we use to write code is the Python programming language. Python is a popular language for data science because it supports many data science tasks.
When we write a document in the English language, we need to follow the grammar rules or the syntax of the English language. Similarly, when we write instructions in the Python language, we need to follow the syntax of Python. This chapter covers the syntax of instructions that do basic calculations and printing the results.
Printing Text
To tell the computer to print a line of text or a result to screen, use the print function. A function is a block of Python code that does a task, and the print function's task is to print the given data to screen.
The general syntax to run or call any function is:
function_name( input to the function )
When we write an instruction, or a statement, in the above format in a Code cell and run the cell, the computer will run the block of code that belongs to the function name, and the block of code will use the input to the function to do its task.
Therefore, to print two lines of text to screen, we write:
Hello world
Python is used for this output
Note that:
- The text
Hello worldis the input to the function print, and the text needs double quotes or single quotes around it. When the text is printed, Python automatically removes the quotes. - Each
printstatement produces one line of output.
Note that:
- The text
Hello worldis the input to the function print, and the text needs double quotes or single quotes around it. When the text is printed, Python automatically removes the quotes. - Each
printstatement produces one line of output.
Printing blank lines
If blank lines are needed in the output, there are two ways:
- Use "\n" at the end of a line of text.
\nis short for newline. - Use
print()with no input
Can you predict how many lines of output will be printed from the code below?
First line of text that's followed by a blank line.
Second line of text that's also followed by a blank line.
Third line of text, followed by no blank line.
Fourth line of text.
Arithmetic Expressions
An arithmetic expression is made of operands and operators.
An operand is a data value, and an operator is a symbol that represents the work that the computer will do.
For example:
4 + 3
is an expression where 4 and 3 are the operands, and + is the operator that tells the computer to add.
In a Code cell, we can simply type the math expression and then run the cell to tell the computer to do the work and display the result of the math expression.
7
An arithmetic expression can have the following common operators:
+: add-: subtract*: multiply (note that it's an asterisk, notx)/: divide%: modulus, which finds the remainder of a division**: exponent( ): parentheses
An arithmetic expression can have the following common operators:
+: add-: subtract*: multiply (note that it's an asterisk, notx)/: divide%: modulus, which finds the remainder of a division**: exponent( ): parentheses
Predict the output of each expression below and then print it to check your prediction.
Note that for division, even when the result is a whole number, Python returns the result as a decimal number, as shown in the next Code cell.
1
12
1.3333333333333333
1
64
Note that for division, even when the result is a whole number, Python returns the result as a decimal number, as shown in the next Code cell.
5.0
Printing Expressions
To print the result of an arithmetic expression together with some text, we need to use the print function again.
The print function can be used to print multiple data values, by placing the data values inside (), in the order that they should be printed, and separate them by comma.
In the following examples, the print function has two inputs. Can you predict what the print output is?
In the example above, we see that the print function can print a number and a text string. By default, the two inputs are printed with a space in between them.
The print function can also print the result of an expression if we give the expression as an input to the print function.
7 is the number seven.
In the example above, we see that the print function can print a number and a text string. By default, the two inputs are printed with a space in between them.
The print function can also print the result of an expression if we give the expression as an input to the print function.
Can you predict the output of the print statement below?
How many lines of text are printed?
2 + 9 is 11
Can you predict the output of the print statement below?
How many lines of text are printed?
The result of 2 + 3 is 5
Right?
Evaluating Expressions
Computers evaluate arithmetic expressions, or do the calculation, in the same PEMDAS order of precedence that's defined in math:
Parentheses
Exponents
Multiplication and Division (left to right)
Addition and Subtraction (left to right)
This means parentheses are evaluated first, and Addition/Subtraction are evaluated last and in the order from left to right of the expression.
In the expression: 1 + (2 ** 3 + 4) / 5 * 2there are 7 operators. The order that they are evaluated is:
- Parentheses
(2 ** 3 + 4) - Exponent:
2 ** 3or 23 = 8 - Addition:
2 ** 3 + 4or 8 + 4 = 12 - Division:
(2 ** 3 + 4) / 5or 12 / 5 = 2.4 - Multiplication:
(2 ** 3 + 4) / 5 * 2or 2.4 * 2 = 4.8 - Addition:
(1 + (2 ** 3 + 4) / 5 * 2)or 1 + 4.8 = 5.8
5.8
Applying Expressions
In their data analysis work, data scientists often write multiple expressions so that the computer can run them to get results, which are then used for extracting insights from the data.
For example, given that a class has four exams, each with a possible score from 0 to 100 points. If the four exams are a major factor in determining the grade of students, then what is the most likely grade for a student who earned 84, 90, 94, 82 on the exams?
In the Code cells below:
- Write an expression to calculate the average exam score and run the cell to see the result.
- Observe the output of the cell and determine the most likely letter grade (A, B, C...) based on the average score. Then in the Code cell, write a statement to print the most likely grade that you think the student earned.
What you did in the example above is applying expressions to the data or the exam scores, so you can get the insight (the average score) and predict the likely grade for a student.
Comments in Code
In the two Code cells above, the lines of text in English is called a comment. It is a way for us to write a quick note to ourselves or to the reader, to explain what the code does or explain a result of a calculation.
A comment in a Code cell starts with a # symbol, and ends at the end of the line.
Variables
Many times the calculations that we need to do can take several steps, where each step produces an intermediate result, and the intermediate result is then used in the next step.
An example is to calculate the speed of two cars and then print the average of their speeds.
Suppose Car A takes 1.5 hours to travel 47 miles, and Car B takes 0.5 hours to travel 12 miles.
What is the average speed of the two cars?
Here is the order of the 3 steps that it takes to answer the question:
- Step 1: Find the speed of Car A
- Step 2: Find the speed of Car B
- Step 3: Find the average speed of the two cars
In order to do step 3, we need to save the results of steps 1 and 2, so we can tell the computer which two values to average. The results of steps 1 and 2 are the intermediate results, they help us to get to the final result which is the average speed.
In programming it is easy to create a temporary storage place for an intermediate data value: we use an assignment operator.
Assignment Operator
The assignment operator is the = symbol. Here is how to use the assignment operator to store an intermediate result:
variable_name = data value
The instruction or statement above uses the = or assignment operator to tell the computer to store data. Therefore the entire instruction is called the assignment statement.
Note that the = operator or assignment operator does not work like the = of math. In math, = means the two values on the left and right are the same value. In programming, = means saving data into storage.
- The right side of the
=operator is always for data. - The left side of the
=operator is always the name of the data storage location or the name of the variable.
Recall that an operator is a symbol that causes the computer to do some work. The = operator tells the computer to store the value on the right into a named storage location on the left.
Below is the Python code for the 3 steps to find the average speed of the two cars:
Car A speed: 31.3 mph
Car B speed: 24.0 mph
Average speed of the 2 cars: 27.7 mph
When there are multiple instructions that work together in a logical, step-by-step order to tell the computer to do some work, like the block of code above, then we have a computer program.
When there are multiple instructions that work together in a logical, step-by-step order to tell the computer to do some work, like the block of code above, then we have a computer program.
In the program above, note that:
-
A variable name should be descriptive: it should describe the data that is stored.
The variable namecarA_speedmakes it clear which data is being stored at that location. A variable name should not bexoryas is sometimes used in math equations, because a program typically has many variables to store intermediate data, and variable names likea,b,x,ymake it difficult to remember what results are stored at these locations. -
Variable names must be made of letters, numbers, and underscores, and the first character in the name cannot be a number.
If the variable name begins with a number, Python will not understand the name and the program will have errors. It's similar to misspelling a word or using the wrong word in an English sentence. The sentence has an error that makes it difficult for the human reader to understand it.
Ways to Assign Data
In the example to calculate the average car speed, we see one way to assign data:
carA_speed = 47 / 1.5
The data to be stored incarA_speedis the result of an expression.
There are two other common ways to assign data:
carA_speed = 42.5
The data to be stored is a literal value, or a value typed directly into the statement.
carA_speed = carB_speed
The data to be stored comes from a different variable.
This way is the most confusing when we first encounter it: do we set carA_speed to carB_speed? Or is it the other way around?
If we remember that it's always the data on the right being stored in the variable on the left, then it's not confusing. The assignment statement tells the computer to store the value of carB_speed into the variable carA_speed.
The last example carA_speed = carB_speed
clearly shows the difference between the math = operator and the programming = operator.
In math, carA_speed = carB_speed
can also be written as carB_speed = carA_speed
because the math = operator means equal to. Both versions say that carA_speed is the same as carB_speed, so the = operator is commutative, which means we can swap the variables on the left and right sides.
In programming, carA_speed = carB_speed
means store the speed of Car B into the variable carA_speed, so carA_speed is updated to a new value.
But carB_speed = carA_speed
means store the speed of Car A into the variable carB_speed, so carB_speed is updated to a new value.
The two expressions do completely different tasks.
Update a Variable
Within one program, a variable name refers to a specific data value that has been stored or assigned to it. This means:
- If we have four unique data values to save or store, then we need 4 variable names and four assignments to store the four data values.
- If we need to update a particular variable with new data, then we simply assign the new value to that variable name.
Note that after updating first_num, the value 10 that was originally in first_num is gone and we can't get to it anymore.
Original 3 numbers: 10 20 30
The 3 numbers after updating the first number: 40 20 30
Note that after updating first_num, the value 10 that was originally in first_num is gone and we can't get to it anymore.
The 2 scores are: 88
Summary
In this chapter we learn how to tell the computer to perform arithmetic calculations and print the results. We also saw that storing intermediate results in variables allows us to build programs that solve problems one step at a time.


