1.2. Python Basics I: Variables, Strings, and Bugs#
Reference: Chapter 1 of Computational Nuclear Engineering and Radiological Science Using Python, R. McClarren (2018)
1.2.1. Learning Objectives#
After studying this notebook, completing the activities, and asking questions in class, you should be able to:
Print and concatenate strings
Add relevant comments to batches of code
Recognize and correct bugs in code
Differentiate between the different types of variables and know what output to expect
Understand how to import and utilize the math library
1.2.2. Hello World and Interactive Sessions#
In almost any computer language the first thing you do is create a program called “Hello world!”.
This notebook is an interactive session. We just type the command print("Hello World.")
and the press Shift+Enter to execute.
print("Hello World.")
Hello World.
Home Activity
Print the first two lines of your favorite poem or song.
Hint: Use \n
anywhere inside of the quotes to create a new line.
Unicode Characters
A way to express fancy letters, like emojis
Supported by Python
Copy-and-paste is the easiest way to write in code
Easy to find on website such as http://xahlee.info, https://www.compart.com/en/unicode/, and https://unicode-table.com/en/#control-character (top Google search results)
print("The temperature was 56 °F this morning.")
The temperature was 56 °F this morning.
Home Activity
Write a print statement using at least two unicode characters.
1.2.3. Command Line Mode#
Above, we used the interactive mode, which means the result of each line is displayed when I enter the line.
It is more common to put your code into a separate file and then execute it by typing
python codename.py
where codename.py
is the name of your file.
How to access a Python interpreter?
Mac or Linux: Open terminal and type
python
Mac, Linux, or Windows: Use an IDE.
Anaconda is the easiest free Python environment to install. It is already available in B19.
Optional Home Activity
Install Anaconda on your computer.
Hint: Start at https://www.anaconda.com/distribution/#download-section. Ask questions in tutorial if you get stuck.
1.2.5. Errors#
We call errors in computer programs bugs. Even experienced programmers write code with bugs. We will learn best practice procedures to try to rid a code of bugs, but even the most sophisticated software quality assurance techniques will not catch every one. Let’s look at a good bug and a bad bug.
1.2.6. “Good” Bugs#
Good bug: A syntax mistake that Python will catch and scream about.
Example
#This is a good bug because the python interpreter complains
9*9 +
Input In [16]
9*9 +
^
SyntaxError: invalid syntax
Home Activity
Create another example of a “good” bug. Share with a friend.
1.2.7. “Bad” Bugs#
Bad bug: A flaw in the logic of the computer program. These are much harder to catch.
Example: We want to compute
But we input:
3 + 5**2
#You don't get the correct answer, and no one tells you that you're wrong.
28
Home Activity
Copy the code below and then fix the bad bug.
# Add your solution here
This is an example of the power and feebleness of computers. A computer can do anything you tell it to, but it doesn’t necessarily do what you want it to. Always keep this in mind: just because the computer did something, that doesn’t mean it did what you wanted.
Later we will talk in more detail about bugs, finding bugs (called debugging), and testing of code.
1.2.8. Indentation#
Python is, by design, very picky about how you lay out your code. It requires that code blocks be properly indented. We’ll discuss what code blocks are later, but your code needs to be properly aligned to make this work.
#If I improperly indent, my code won't work
print("Not indented")
print("indented, but it shouldn't be")
Input In [20]
print("indented, but it shouldn't be")
^
IndentationError: unexpected indent
Notice that none of my code executed because of the indentation error. An indent tells the Python interpreter the indented code is part of a code block and needs to be executed in a special way. Only at certain times can one indent and it makes sense. We will revisit this in a few lectures.
Home Activity
Copy the code below and fix the indentation error.
#If I improperly indent, my code won't work
# Add your solution here
1.2.9. Input#
You can prompt the user for input using the input command:
user_value = input("Enter a number: ")
user_value = float(user_value)
print("2 *", user_value,"=", 2*user_value)
2 * 5.0 = 10.0
user_value = input("Enter a number (just type 7): ")
user_value = int(user_value)
if user_value == 7:
print("Correct, we have a winner")
print("Claim your prize")
else:
print("You guessed poorly.")
Correct, we have a winner
Claim your prize
Notice that in this example we used an if-else statement. The if-else statement is a way to execute different parts of the code based on some conditional expression. This type of execution is sometimes called branching or selection. We will discuss this in detail below.
Also notice the indentation in the if-else block.
Home Activity
Rerun the code above. Find input values that execute each part (a.k.a., branch, section) of the if statement. In other words, find one input value that causes the program to output “Claim your prize”. Then find a different input value that causes the program to output “You guessed poorly”. Record your answer below in the text (Markdown) cell:
Answer to Home Activity:
Input that printed “claim your prize”:
Input that printed “You guessed poorly”:
1.2.10. Variables#
Information, or data, is stored in variables. Common types of variables include floating point numbers (decimals), integer numbers, and text to name a few. For a complete list of the python data types, see https://docs.python.org/3.4/library/stdtypes.html
1.2.11. Integers#
Integers are whole numbers, including the negatives. They never have a fractional, or decimal, part and should only be used for data that is a count.
To assign an integer to a variable use the equals sign.
#assign the value 2 to x
x = 2
print(x*2.0)
#check that x is an integer
type(x)
4.0
int
Integers are useful for things that can be counted: perhaps that number of times we execute a loop, the number of elements of a vector, or the number of students in a class.
Home Activity
Copy the code from above and modify to multiple x by 2 instead of 2.0. What is the variable type now?
#assign the value 2 to x
# Add your solution here
#check that x is an integer
# Add your solution here
1.2.12. Floating Point Numbers#
Floating point numbers are numbers that do have a fractional part. Most numbers in engineering calculations are floating point types.
#Now make some others floating point variables
y = 4.2
print("y =",y)
print(type(y))
#note that exponentiation is **
z = (x / y)**3
print("(2 / 4.2)**3 =",z)
y = 4.2
<class 'float'>
(2 / 4.2)**3 = 0.10797969981643449
The way that floating point numbers are represented on a computer has only a finite precision. That means we cannot represent a number exactly in many cases. We’ll see later an example of how floating point accuracy can make a difference in a calculation.
Home Activity
Add 1E-10 to 1E-20. Is the answer what you expect?
Hint: 1E-20
is shorthand for \(1 \times 10^{-20}\), which is sometimes called scientific notation.
# Add your solution here
1.2.13. Built-in Mathematical Functions#
There are almost every common mathematical function you might need for python already built in. To use them you have to import that math functions using the command import. In the code below, I set it up so that to use a math function you use the syntax math.[function] where [function] is the name of the function you want to call.
See https://docs.python.org/3.4/library/math.html for the complete list of built-in mathematical functions.
import math as m
#take cosine of a number close to pi
theta = 3.14159
trig_variable = m.cos(theta)
print("cos(",theta,") =",trig_variable)
#use the exponential to give me e
e = m.exp(1)
print("The base of the natural logarithm is",e)
#python has a built-in pi as well
print("The value of pi is",m.pi)
cos( 3.14159 ) = -0.9999999999964793
The base of the natural logarithm is 2.718281828459045
The value of pi is 3.141592653589793
Notice how in the print statements, if I give it multiple arguments, it prints each with a space in between. The natural logarithm is just math.log and the base 10 logarithm is math.log10.
print("The natural log of 10 is",m.log(10))
print("The log base-10 of 10 is",m.log10(10))
The natural log of 10 is 2.302585092994046
The log base-10 of 10 is 1.0
There are two non-obvious mathematical operators, integer division: //, and the modulus (or remainder): %
# 7 / 3 is 2 remainder 1
print("7 divided by 3 is",7//3,"remainder",7%3)
print("851 divided by 13 is",851//13,"remainder",851%13)
7 divided by 3 is 2 remainder 1
851 divided by 13 is 65 remainder 6
Home Activity
Study and execute the code below. Then write a sentence to explain the different between integer and floating point division.
# integer division
print("7 // 3 = ",7//3)
# floating division
print("7 / 3 = ",7/3)
7 // 3 = 2
7 / 3 = 2.3333333333333335
Write a sentence to explain difference between integer and floating point division:
Let’s also look at how to generate a random number.
import random
print("A random number between 0 and 1: ",random.random())
A random number between 0 and 1: 0.9763983823355622
Home Activity
Generate a random whole number between 0 and 100 using random.random().
# Add your solution here
1.2.14. Strings and Overloading#
A string is a data type that is a collection of characters, and needs to be inside quotes:
#This is a string
aString = "Coffee is for closers."
print(aString)
print("aString")
Coffee is for closers.
aString
Anything inside the quotes is taken literally by python. That is why the second print statement above just printed aString.
You can also subset, that is get some of the characters in a string, using brackets. Putting a single number in a bracket gives you the character in that position. Note, python starts numbering at 0 so that 0 is the first character in a string.
aString[0]
'C'
aString[5]
'e'
You can also get a range of characters in a string using the colon. The colon operator is funny in a way in that [a:b] says give me the elements in the string from position a to position b-1.
aString[1:6]
'offee'
Python defines its ranges this way so that if the string is of length N, [0:N] returns the whole string.
Negative subsets start at the end of the string (i.e., -1 is the last character of the string).
aString[-1]
'.'
aString[-5:-2]
'ser'
Home Activity
Print “closers” by accessing elements of aString
# Add your solution here
With characters (and strings) the + operator is overloaded. What we mean by overloaded, is that it is defined so that the idea of what addition means is conferred to strings. Therefore,
'Negative Ghostrider: ' + 'the pattern is full'
'Negative Ghostrider: the pattern is full'
'a' + 'b' + 'c'
'abc'
The + operator concatenates (or smushes together) the strings/characters it operates on.
The multiplication operator is similarly overloaded, though it is not as general. It is simple to think about ‘The roof, ‘ * 3
'The roof, ' * 3
'The roof, The roof, The roof, '
However, ‘The roof, ‘ * 3.15 is not defined and will give an error:
'The roof, ' * 3.15
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [42], in <cell line: 1>()
----> 1 'The roof, ' * 3.15
TypeError: can't multiply sequence by non-int of type 'float'
The upshot is that only an integer times a character/string makes sense. The order of operations is respected
'The roof, ' * 3 + 'is on fire...'
Minus makes sense, but only sometimes, so it is not allowed.
Home Activity
Create the string “row row row your boat gently down the stream” using string multiplication and concatenation.
# Add your solution here
1.2.4. Comments#
Comments are your best friend. They can be time consuming to add, but never have I looked back at old code and regreted adding them.
A comment is a annotation in your code to
This is not to punish you, but to help you.
You use the pound (aka hashtag) to comment out the rest of a line: everything that follows the # is ignored by python. Therefore, you can put little notes to yourself or others about what is going on in the code.
There are also ways to make multiline comments by use a triple quote ‘’’
Home Activity
Add comments to the following calculation. At the top, write a sentence describing the program in the multiline comment block. Then fill in each empty single line comment with units.