This webpage is a static view of an interactive Jupyter Notebook tutorial. To get the full interactive experience where you can run Python code, modify examples and complete exercises, click the "Open in Colab" button. This will access the Google Colab notebook from a GitHub repository github.com/dchappell2/Computational-Physics and open it in Google Colab. You will need a Google account if you want to open it in Colab.
Note: You can download a pdf of the lecture slides for this chapter here: Chapter 0-3 slides
Objectives:
j as the complex unit, so c = 2 + 3j is a complex number (assuming you haven't redefined j as a variable).if statements that will be discussed later.Let's define a few variables and examine their data types.
x = 4 # integer
y = 4.2 # float
c = 1 + 2j # complex
a = 'dog' # string
happy = True # boolean
Notice that in Jupyter Notebooks, number values are colored dark green, strings are red and Boolean values are blue.
We can check the data type of a variable in two ways:
type function (hard way)Here's an example of how to display the data type of our 4 variables using the print() and type() functions (run it to see the results):
print('data type of x is',type(x))
print('data type of y is',type(y))
print('data type of c is',type(c))
print('data type of a is',type(a))
print('data type of happy is',type(happy))
The next section shows how to use the Variable Inspector.
The Variable Inspector icon may be found on the bottom left corner of this window and it is labeled {} Variables. Click this icon to display the variable inspector. You should see a list of all the variables you have used in this tutorial, their values, and their data types. While the Variable Inspector can be very helpful in debugging your code, be aware that it can slow down execution of complex code while it is open. Thus, you may want to only open it when it is needed.
The Variable Inspector can be very useful for debugging code, especially when you start writing complex programs.
The + operator has different effects on numbers and strings. Run the following code, for example:
x = 3
y = 4
print(x+y) # the + operator adds number
a = 'Marie ' # notice we added a space at the end of 'Marie'
b = 'Curie'
print(a+b) # the + operator concatenates strings
We see that the + operator:
See what effect the * operator has on strings
my_string)10*my_string.A common situation when you might want to convert a string to an integer is when the input() statement is used to prompt the user for a number. Run the following:
result = input('Enter an integer: ')
print('the data type of ',result,'is',type(result))
print('4 *',result,'=',4*result)
input statement is a string.result shows its value to be 4, we can't do any math with it yet because it is a string and not an integer or float.result by 4 to get a surprising result!!int():n = int(result)
print('the data type of ',n,'is',type(n))
print('4 *',n,'=',4*n)
The float() function converts strings to floats:
a = '9.8'
g = float(a)
print('the data type of ',a,'is',type(a))
print('the data type of ',g,'is',type(g))
The simplest way to convert a number (either an integer or float) to a string is the str() function:
a = str(3.14)
print('the data type of ',a,'is',type(a))
The method described in the next section describes how to have more control over the appearance of string representations of numbers.
If we want to remove the digits to the right of the decimal point, we can just use the int() command like this:
p = int(2.999)
print(p)
However, if you want to round your float to the nearest integer, you can use round():
r = round(2.999)
print(r)
Both of these methods convert floats to ints. You can verify this in the Variable Inspector or by using the type() command.
We can convert an iteger to a float by using the float() command:
q = float(3)
print("The data type of",q,"is",type(q))
What happens when you add or multiply a float by an integer? Is the resulting data type float or int? Write some code to show an example of each. Create a code cell to try out your examples and create a text cell to explain your answer.
Let's suppose we are given the a number with more significant digits than we care about. We want to display our number keeping only two decimal places to the right of decimal place. We can do this with a formatted "f" string like this:
x = 316.227766 # float number showing 6 decimal places
x_str = f'{x:.2f}' # string representation of x keeping 2 decimal places
print(x_str) # display the truncated value
A formatted string has text inside a pair of quotes, but with the letter "f" out in front. We place a variable that we want to format inside curly braces followed by a formatting string. In the above example, the :.2f means we want to format the number as a float and keep 2 digits to the right of the decimal point.
If we just want to print the formatted number, we can just include the formatted string directly in the print function without the x_str variable:
print(f'{x:.2f}') # simplified formatted print
Here are more examples for formatting floats:
print(f'1st example {x:.2f}') # displays float with 2 decimal places
print(f'2nd example {x:.4f}') # displays float with 4 decimal places
print(f'3rd example {x:12.5f}') # displays float with 5 decimal places and reserves total of 12 places
print(f'4th example {x:.2e}') # scientific notation with 2 digits after the decimal
For integers you can specify the number of spaces set aside for columns of numbers. The formatting symbol for integers is "d". Heres's an example showing what happens when you print a set of numbers with different numbers of digits both with and without formatting. Since our biggest number has 5 digits, we'll reserve 5 digits for each data column using the format {my_var:5d}, where you would replace "my_var" with your variable name.
a = 2; b = 21043; c = 77; d =764
print(f"{a:5d} {a:5d} {a} {a}")
print(f"{b:5d} {b:5d} {b} {b}")
print(f"{c:5d} {c:5d} {c} {c}")
print(f"{d:5d} {d:5d} {d} {d}")
Notice how the first two columns that are formated are nicely lined up (and right-justified), while the last two columns aren't. As we'll see later, formatted print statements are particularly useful when saving data to text files.
You can get fancy and include text and multiple formatted variables in the same print statement like this:
x = 4.334565 # x measurement
y = 12.4848 # y measurement
print(f'My measurements are x = {x:.2f} and y = {y:.2f}')
Remember, the variables go inside curly braces with the formatting.
Write some code to prompt the user to enter a floating-point number. Break the number into its integer part (numbers to the left of the decimal) and the fractional part (numbers to the right of the decimal). Use a single print statement to display the original number, the whole part and the decimal part. Your print statement should produce a result that is easy to understand to the user.
The following code block defines the x and y coordinates of an object. In the same code cell create a formatted print statement that uses these variables to display the position as a coordinate pair, where each position is displayed with 2 digits to the right of the decimal. Use the print statement to place the numbers inside parentheses and separated by a comma. Your final result should look like "(2.33, 5.95)". Hint: you can print the parentheses and comma by placing them in quotes, i.e. "(" and ",".
x = 2.33456 # x position in meters
y = 5.94843 # y position in meters
a = "3"
b = "2"
c = a-b
In this example, we try converting the string "cat" to an integer (which doesn't make sense). You can only convert string representations of numbers to integers or floats.
int("cat")
This tutorial is a modified adaptation of link text "Python for Physicists"