#!/usr/bin/env python # coding: utf-8 # # Instructor Help (IH) - Simple Formatting # This example shows some simple formatting of numbers with python. We first need to pull in some data to work with. No need to use Pandas for this, it is just a simple text file with just one number per line. # # Let's start by reading the file. The following line opens the file for reading. You will either need to specify the path to the data file, like I did, or need to have it in your directory to run these examples. # In[1]: f=open('/home/flory/Development/R/scores.txt','r') # Next, read the complete file and store the values in the object, lines, and print the result. # In[2]: lines =f.readlines() # In[3]: print(lines) # Notice that the values were read in as character strings. This will cause a problem when we try and do any calculations on the values, so let's convert them to integers using a simple, single line loop. Once converted, the values are once again printed. # In[4]: tests = [int(i) for i in lines] print(tests) # There, that is much better. Now that the values are integers, we can do some simple calculations on them using simple, intrinsic numpy functions. # Now, it would be pretty cool to create a frequency histogram of the scores. # In[5]: import numpy as np average = np.mean(tests) std = np.std(tests) max = np.max(tests) min = np.min(tests) # Alright, here is the formatting piece. Note the these examples use what is referred to the "new" style of formatting in python. Like FORTRAN, the f decriptor can be used for floating point numbers. Unlike FORTRAN, d is used for integers. # In[6]: print ('Test Statistics') print ("Average = {:4.2f}.".format(average)) print ("Standard deviation = {:4.2f}.".format(std)) print ("The maximum scores was {:2d} and the minimum score was {:2d}.".format(max,min)) # I wish there was a nice reference page on this, but, unfortunately, I haven't been able to find one. If you come across one, please let me know. Also, if there is something else I haven't covered with respect to formatting, let me know and I will add it to this page. # In[ ]: