Lesson 3: Python Basics 1

#

This lesson is modified from A taste of Python from geo-python.

Binder

Objectives#

By the end of this lesson, you will be able to

  • Define and update python variables

  • Import a python module or library

  • Use and combine functions in python

  • Apply these concepts to write simple python code

1. Math operations#

We will start our Python lesson by learning a bit of the basic operations you can perform using Python.

Python can be used as a simple calculator. Remember, you can press Shift + Enter to execute the code in the cells below. Try it out by typing 1 + 1 or 5 * 7 and see what you get.

If you want to edit and re-run some code, simply make changes to the cell and press Shift + Enter to execute the modified code.

The list of basic arithmetic operations that can be done by default in Python is in the table below.

Operation

Symbol

Example syntax

Returned value

Addition

+

2 + 2

4

Subtraction

-

4 - 2

2

Multiplication

*

2 * 3

6

Division

/

4 / 2

2

Exponentiation

**

2**3

8

Try to do the following calcluation $\(9 - \frac{5^3}{5 \times 25}\)$ Ans: 8

For anything more advanced such as sin(30°), we need to use some functions in a module or library.

2. functions, modules and libraries#

2.1 Functions#

You can use Python for more advanced math by using a function.

Functions are pieces of code that perform a single action such as printing information to the screen (e.g., the print() function). Functions exist for a huge number of operations in Python.

For example, try out the print() function to display Hi on screen

Another example, try min() or max() function to return the minimum or maximum of this list [4, 1, 8]

Let’s try out a few simple examples using functions to find the sine or square root of a value.
You can type sin(3) or sqrt(4) into the cells below to test this out.

Wait, what? Python can’t calculate square roots or do basic trigonometry? Of course it can, but we need one more step.

For a specialized sin(30°), we need to load a specialized module or library.

2.2 Modules and libraries#

Alibrary is a collection of modules that can include a variety of related functions.
A module is a file or files(.py) that is imported by one import and used to perform a related block of tasks.
A function is a reusable piece of code that performs a single action. .

For example, to evaluate sin(90°), we need to load a specialized module or library.

For math operations, one module is called math and it can be loaded by typing import math. Try that below.

Now that we have access to functions in the math module, we can use it by typing the module name, a period (dot), and the the name of the function we want to use. For example, try to find out the square root of 4 using math.sqrt(4)

Try another example. the function math.sin(x) returns the sine of x radians.

Now find sin(1.5)

Note that modules may also contain constants such as math.pi.
Type this in the cell below to see the value of the contant math.pi.

Check your understanding#

Use the empty Python cell below to calculate the sine of pi `sin(π)

Now, how to find sin(90°) ?

You need to not only the sin() function, but also a function that converts from degrees to radians.

Check the documentation of the math module to find the function the converts from degrees to radians.

2.3 Combining functions#

Functions can also be combined. You have done this already above.

The print() function displays values within the parentheses as text on the screen. Below, try printing the value of the square root of four.

You can also combine text with other calculated values using the print() function.

For example, print('Two plus two is', 2+2)

Check your understanding#

Combine the print() function with the math.sqrt() function to produce text that reads ‘The square root of 4 is 2.0’.

3. Variables#

3.1 Define a variable#

A variable can be used to store values calculated in expressions and used for other calculations.
To assign a value, you simply type variable_name = value

In the cell below, define a variable called temp_celsius, assign it a value of ‘10.0’.
Then print that variable value using the print() function.
Note that you should do this on two separate lines.

Print out the value of temp_celsius in degrees Fahrenheit.

Note: tempFahrenheit = (temp_celsius * 9/5) + 32

The output should read ‘Temperature in Fahrenheit: 50.0’.

Check your understanding#

Define any two variables that you like with text or numeric values.
Print the two variables using print function

3.2 Updating variables#

Values stored in variables can also be updated. Let’s redefine the value of temp_celsius to be equal to 15.0 and print its value in the cells below.

Warning

If you try to run some code that accesses a variable that has not yet been defined you will get a NameError message. Try printing out the value of the variable tempFahrenheit using the print() function in the cell below.

Define the variable:
tempFahrenheit = 9 / 5 * temp_celsius + 32

Now try again

Check your understanding#

Write a code the converts temperature in celsius to Fahrenheit and prints to screen the temperature in both celsius and fahrenheit. Here is the an example of the output “20 degrees celsius is 68 degree Fahrenheit”

3.3 Variable Names#

Following good coding practices is essential, not just for keeping the code organized but also for making it readable and easy to follow. When writing a program, it’s likely that others will need to reference it later. Therefore, you should write your code in a way that is easy to understand and follow at all times.

An important factor in this is using “good” variable names. A good variable name should be short, concise, and descriptive. For instance, if you need a variable to store the number of students in a class, the variable name should be clear enough for others reading the code to understand its purpose. Instead of using a vague name like n or num, a better example would be student_count. Below there are some rules you should follow when selecting a “good” variable name.

Selecting “good” variable names#

A good variable name should:

  1. Be clear and concise.

  2. Be written in English.

  3. Not contain special characters. Stick to the standard printable ASCII character set to be safe.

  4. Not conflict with any Python keywords, such as for, True, False, and, if, or else. These are reserved for speical operations in Python and cannot be used as variable names.

With this in mind, let’s now look at a few better options for variable names.

Formatting “good” variable names#

There are several possibilities for “good” variable name formats, of which we’ll consider two:

Recommendation 1: pothole_case_naming#

pothole_case_naming uses lowercase words separated by underscores _. This is our suggested format as the underscores make it easy to read the variable, and don’t add too much to the length of the variable name. As an example, consider the variable temp_celsius.

fawn_station_id = "440"

Here, our new variable name conveys all of the essential information we need, while remaining easy to read.

Recommendation 2: camelCase naming#

camelCase or CamelCase uses capitalization of the first letter of words in a variable name to make it easier to read. In some cases the first letter of the variable may be capitalized. The variable tempFahrenheit was one example of camelCase.

fawnStationID = "440"

Again, this variable name is clear and easy to read.

Note:#

pothole_case_naming is the easiest to read and seems to be most common amongst Python programmers. For your homework, project, and exam, you can use either option, as long as you are consistent in the use.

Some “not-so-good” variable names#

To illustrate the point, consider a few not-so-good examples below.

s = "440"

sid = "440"

Any idea what these variables are for?

Let’s look at another example.

floridaautomatedweathernetworkobservationstationidentificationnumber = "440"

The above variable provides more information but in a format not easy to read, nor something you want to type more than once.

4. Data types#

A data type determines the characteristics of data in a program. There are 4 basic data types in Python as shown in the table below.

Data type name

Data type

Example

int

Whole integer values

4

float

Decimal values

3.1415

str

Character strings

'Hot'

bool

True/false values

True

The data type can be found using the type() function. As you will see, the data types are important because some are not compatible with one another.

Let’s define a variable weatherForecast and assign it the value 'Hot'. After this, we can check its data type using the type() function.

Let’s also check the type of tempFahrenheit. What happens if you try to combine tempFahrenheit and weatherForecast in a single math equation such as tempFahrenheit = tempFahrenheit + 5.0 * weatherForecast?

In this case we get at TypeError because we are trying to execute a math operation with data types that are not compatible. There is no way in Python to multpily decimal numbers with a character string.

Check your understanding#

As it turns out, you can do some math with character strings in Python. Define two variables and assign them character string values in the Python cell below.

Hide code cell content
# Here is an example solution

What happens if you try to add two character strings together print(first_variable + second_variable)?

Can we subtract them print(first_variable - second_variable) ?

Which other math operations work for character strings? Check multiplication 5*first_variable

5. Character input (optional)#

Python and Jupyter notebooks also let us interact in another way with our code! The built-in input() function reads a line from input and returns it as a string.

Let’s try for example

place = input("Where are you from? ")
print(place, "is a nice place!")
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[6], line 1
----> 1 place = input("Where are you from? ")
      2 print(place, "is a nice place!")

File ~\AppData\Local\miniconda3\Lib\site-packages\ipykernel\kernelbase.py:1281, in Kernel.raw_input(self, prompt)
   1279 if not self._allow_stdin:
   1280     msg = "raw_input was called, but this frontend does not support input requests."
-> 1281     raise StdinNotImplementedError(msg)
   1282 return self._input_request(
   1283     str(prompt),
   1284     self._parent_ident["shell"],
   1285     self.get_parent("shell"),
   1286     password=False,
   1287 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Warning

Jupyter Notebooks might sometimes get stuck when using the input() function. If this happens, restart the kernel.

Let’s try another example in the cell below using the similar approach. Ask the user for a temperature in Celsius using the input() function and print the input value to the screen.

tempCelsius = input("How cold can it be in Fort Myers (in degrees Celsius)? ")
print(tempCelsius, "degrees Celsius is quite cold!")
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[7], line 1
----> 1 tempCelsius = input("How cold can it be in Fort Myers (in degrees Celsius)? ")
      2 print(tempCelsius, "degrees Celsius is quite cold!")

File ~\AppData\Local\miniconda3\Lib\site-packages\ipykernel\kernelbase.py:1281, in Kernel.raw_input(self, prompt)
   1279 if not self._allow_stdin:
   1280     msg = "raw_input was called, but this frontend does not support input requests."
-> 1281     raise StdinNotImplementedError(msg)
   1282 return self._input_request(
   1283     str(prompt),
   1284     self._parent_ident["shell"],
   1285     self.get_parent("shell"),
   1286     password=False,
   1287 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

What is the data type of variable place? What about the other variable you defined? Check their data types using the cell below.

print(type(place))
print(type(temp_celsius))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 1
----> 1 print(type(place))
      2 print(type(temp_celsius))

NameError: name 'place' is not defined

What happens when you try to convert your Celsius temperature value to Fahrenheit using the equation from earlier in the lesson?

tempFahrenheit = 9 / 5 * temp_celsius + 32
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 tempFahrenheit = 9 / 5 * temp_celsius + 32

NameError: name 'temp_celsius' is not defined

How to solve this problem?
Check online how to convert str to float.

tempCelsius=float(temp_celsius)
tempFahrenheit = 9 / 5 * temp_celsius + 32
print(tempFahrenheit)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 tempCelsius=float(temp_celsius)
      2 tempFahrenheit = 9 / 5 * temp_celsius + 32
      3 print(tempFahrenheit)

NameError: name 'temp_celsius' is not defined

6. Problem - A low-effort way to become a millionaire#

According to New Trader U: 3 Low-Effort Ways To Become A Millionaire, Standard and Poor’s 500 index fund (S&P 500) tracks the stock performance of 500 of the largest companies listed on stock exchanges in the US. The average historical rate an investor can expect long-term on S&P 500 is 8% annual compounded growth. The formula is: $\( FV = PM * \frac{[(1 + r)^{nt} – 1]}{r} \)\( Where: FV: Future value of the investment (e.g., \\\)1,000,000)
PM: Monthly investment amount (e.g., \$300)
r: Monthly interest rate (i.e., annual interest rate divided by 12)
n: Number of times the interest is compounded per year (i.e., 12 for monthly compounding)
t: Number of years (e.g., 20 years)

To convert annual interest rate of 8% to monthly interest rate you can use this formula \( r = (1 + 0.08)^{1/n} – 1 \)

For example, for FV= \\(1,000,000 and t = 40 years, then PM ≈ \\\)310.5. Note while there is wide variance in monthly and annual returns, long-term destination will likely lead to being a millionaire based on historical performance of past 100 years.

Exercise 1#

Write a code to check that if you invisted about \(310.5 you will be a millionaire in 40 years. Display your answer as "For a monthly invistment of \\\) 310.5 for 40 years, the future value will be \\( 1.0 million" Note that \\\) 1.0 is rounded and the actual value is 1.0001451368328833.
How to round a number in python? Check online

#Calculate monthly interest rate (r)

# Given PM of $310.5 and t of 40 years find FV

Exercise 2#

(2) Write a code to check how much do you need to invest monthly to become a millionaire in 25 years?
Display your answer as “For a future value of \\( 1.0 million in 25 years, you need to invist \\\) 1100.0 per month”
Note that \\( 1100.0 is rounded and the actual value is 1100.120953605599. \)\( FV = PM * \frac{[(1 + r)^{nt} – 1]}{r} \)$

#Calculate monthly interest rate (r)

# Find PM given t of 25 years and FV of $1,000,000

Exercise 3#

Write a code to find out that if you will invest \(1000 per month, after how many years will you become a millionaire? Display your answer as "If you invisited \\\) 1000.0 per month, you will become a milloire in 25.5 years”

Note you need to import math module to solve the exponential equation using logarithms.
We did not learn logarithms, but we learned how to find functions in the documentation of the math module $\( FV = PM * \frac{[(1 + r)^{nt} – 1]}{r} \)$

import math
#Calculate monthly interest rate (r)


# Find PM given t of 25 years and FV of $1,000,000