Learning Python Programming - Part 3 - Imports, modules, math, and functions

in #programming5 years ago (edited)

Welcome to the third part of the ongoing series Learning Python Programming!

In this lesson we will be learning all about math operations, imports, and functions, then writing a new math program!
You can see our previous lesson, learning variables, here.


source

Math

Most math operations are supported right off in Python. These operations are the most basic mathematical concepts. This is how we write them in Python:

#Addition
a = a+b
a += b
#Subtraction
a = a-b
a -= b
#Multiplication
a = a*b
a *= b
#Simple division
a = a/b
a /= b
#Integer division
a = a//b
a //= b
#Exponent
a = a**2
a **= 2

Note the different ways to do each operation. In the first of each math operation, we can see a variable assignment followed by a math operation; this sets that variable to the outcome of that math. A simple way to write this is in the second example on each mathematical operation. All we have to do to simplify our math, is add the operator to the front of the equal sign and put our second operand after the equal sign.

What's the difference between simple division and integer division?
The difference between simple division and integer division is a simple one. Our variable types affect our simple division where as they do not in integer division. If our first operand is a floating point number (has a decimal) the outcome of the math will have a decimal, otherwise the outcome will only be what's to the left of the decimal point. In integer division, the number's decimals are "chopped off" before they are divided, giving us only an integer as an outcome.

What if we want to do more complicated math?
To do more complicated math you will need to import the math module or download a third party module. Imports are covered below.

Imports and modules

Imports are used to bring external code into the program. For now, it will be importing modules, but you can write separate files and import them to another file. If we go into our IDLE console we can type in help(), followed by modules to see the giant list of what modules come with Python. I recommend that you do this now.

How do we import something into my code?
To import something you must write an "import statement" at the top of your code. This statement can look like any of the following:

import math
import math as Math
from math import sqrt
from math import pi as pie

The first line in that example is a simple import of the math module. This module contains intermediate level math that you would need a calculator to solve. The key word "as" renames what you are importing to the variable name given after it. The third line imports a single thing from a module. Importing a single thing from a module is very handy when you only need to use that one thing from the module.
To use something you import in your code you must use it's imported name. To use the math module with the first import statement, we must write out math.pi to use the constant pi. A very simple rule, but it can be forgotten easily! When you rename the imported content, that is the name you use in your code for what you are importing.

How do we know what each module has?
There are a couple ways to find out what makes up a module. One way is to go to your IDLE console and type in, import module, then dir(module), where module is the one you want to look up. The dir function will print you out a list of every name inside what you give it. Another way is to mess around in the files and find the big file of modules, I don't recommend this, but it can be fun to look at module code. The best way to understand a module in my opinion, is to just google it. My google search history is full of searches like "python this" and "python that."

Functions. What are they?

In the scope of computer programming, functions are sections of code that we can "call" or run as many times as we want. With this ability, we can make everything easier. The only thing about functions is that they must contain something, whether that something is a page of code or a single return statement. You can name a function any valid variable name; in my example below, I used func.

source
This is how we define a function:

def func():
    return

Our function can do many things including: taking in arguments and returning values. Arguments are simply a way to say variables that you feed a function. To take in these arguments, you must first tell the function to expect them. Python looks for the argument names inside the parenthesis, so that is where we must put our temporary variable name; with multiple we simply separate them by commas. This ends up looking a bit like this:

def func(arg0, arg1, arg2):
    return

Python does have a limit on how many arguments you can give a function, 255, but for most uses you will not need to give that many.

How do we call a function?
To call a function, you write it's name followed by a pair of parenthesis. Inside the parenthesis is where your list of arguments go. If your function is returning a value, you need to have a variable assignment before the function call or that return value will be lost forever.

Variable Scope

Variable Scope is a very important thing to remember when assigning new variables. If you assign a variable inside a function it will not work outside of that function.

source

x = 3
z  = 0
def newz():
    z = 10
print(x) # will print 3
newz()
print(z) # This line will print 0 even though we assigned it to 10 in the function right before

To fix the problem above, we can do a few things: take the assignment out of the function, move the print statement into the function, or put a new line inside the function declaring the variable as global. The first two options are pretty self-explanatory, but the global line is a new concept.
To declare a variable as global, it must first be already defined in the global scope, then in the function we write "global variable" where variable is the variable name that we are referencing. Our new example looks like this:

z = 10
def newz():
    global z
    z = 0
print(z) # will print 10
newz()
print(z) # will print 0

Just like that we fixed our variable scope.

Let's get back to programming!

Our second program will be all about math. We need a program to automate the formula for the area of a circle.
What is the formula for the area of a circle again?
area = pi * radius squared
First we will need a function that uses the variable radius, so we define our function like we just learned, with the argument r:

def CirArea(r):

Now we calculate the area of the circle, but Oh No! we need to use pi!
We need to import the math module to get the constant pi. (we could use 3.14, but we just learned to import)
We could write "import math" and use math.pi for the mathematical constant pi, or we could do one better! We're going to use "from math import pi" and use the variable name "pi" but we're going to go one more step further, let's rename pi to PI.
Now we have:

from math import pi as PI
def CirArea(r):
    area = PI*r**2

This program will work completely fine, but we can't do anything with it yet. We need a return statement in our function and we need to print out some examples!
A return statement is a pretty simple concept. At the end of the function, we need to add on a "return area" to make the function return the area variable.
Then to return our new area we can write after the function, a print statement with a function call inside.
Our code now looks a bit like this:

from math import pi as PI
def CirArea(r):
    area = PI*r**2
    return area
print(CirArea(5))

Now we have a working program that will tell us the area of any circle!

Sort:  

Upvoted and followed thanks Great post.

Great post! Thanks a lot!