20 January 2015

Fun with Python

Python is a pretty basic language. In C++, to print a message to the console, we needed a whole bunch of lines of code, but in Python, that's not necessary. 

This was me just playing around with the shell. All you have to do to print in Python is type print, and then in quotations or double quotations, type your message. 

You can also do math easily too. Below, I asked to be shown all of the things I can do with the math module. 

These are a few examples of math operations you can do.

Notice that sqrt returns the square root of the number you put in the parenthesis.
And pi returns the first few digits of pi.
Similarly, e returns the first digits of e.
The pow function returns the first parameter to the power of the second parameter.
If you just want to square something, ** works for that.
Otherwise, addition, subtraction, and multiplication work in the ways you think they would. 

If I were to enter in 3 / 5, I would not get .6 out. The numbers 3 and 5 are integers. The decimal .6 is what we call a double. If you divide an integer by another integer, the value returned will be how many times you can put the second into the first, which in this case is zero. If I want to divide these numbers and get .6 out, I would need to type 3.0 / 5 or 3 / 5.0 or 3.0 / 5.0.

Notice how when I divided a decimal by a decimal, I got a whole number with a decimal. That's because those decimals are doubles, and if I divide with a double or multiple doubles, I will get back a double no matter what. 

Also in that picture, I used the % symbol. This is actually used a lot in coding, and is called modulo. Basically, it divides the first number by the second number and return the remainder, like when you did long division and had remainders instead of decimals. 

So, if you divide 3 / 5, we already know that that will equal 0, but the remainder is 3.
If you divide 5 / 3, you will get 1, but because we're using the mod, we get back the remainder still. So, 5 / 3 is 1 remainder 2, which is why the output there is 2. 

Another cool built-in function Python has is one that tells you how long a string or message is. 

Farewell pic :

The view of my campus from the top of South Table Mountain.

                                                                                           ~ Cici

No comments:

Post a Comment