DEV Community

bseker61
bseker61

Posted on • Edited on

Programing 101

Today we are going to learn some basic concepts to help you understand how Python works and how can you use it to complete some tasks.
The key terms we are going to discuss are:
• Loop for
• Files
• Numpy
• Math
These libraries will help us to develop a small program that can calculate the standard deviation for a set of 100 numbers. With this you will be able to create your own programs to solve some mathematical problems.
First of all, we have to import all the libraries that we will use:
Import numpy as np
Import math as mt

Now there is always a problem when we open a file in Python we have to close them but sometimes we don’t remember this that´s why I´ll show you a trick that will help you with this. Instead of writing.

data = open(FileName.txt,a)

We can use the function “With” and we put the following line:

With open(FileName.txt,a)  as data:
    #we have to put the all the code with an indentation.

As we all know the formula for the Standard Deviation is the one in the picture, we have to calculate the mean of our set and then get the residue of a particular value and the mean but, if you have a file with 100 numbers how are you going to do this for each one of them?

Alt Text

https://www.thoughtco.com/calculate-a-sample-standard-deviation-3126345

Here is the code that we are going to use for this example you can check it in GitHub also the file that I use.
https://github.com/bseker61/python

As we see in the code, we open the file using the “With” function.

Alt Text

Now we create a list call “ldata”, in this list we will store all the information we´ll take from the file.

Alt Text

We will use the loop for to repeat the same process of adding one element of the file into the list. After that we will use Numpy to transform the list into an array so we can use a function to get the mean of the set.

Alt Text

Now we will get the mean using the function “.mean”, next we will use another loop for to get the residue of a particular value and the mean and we´ll store it in another list call “qt”, now we will use the function “sum()” in which the argument of the function is a list. This will help us with a part of the equation for the standard deviation. At last we will use the library math to use the square root of a number and the function “len()” to get the total amount numbers in the list. Finally we print the result with the function “print()”.

Top comments (0)