2.2. Python Syntax - Basics #2#
In this section we’ll cover setting a variable types, mathematical operations and calculations, and subsetting strings. A good resource for additional information about the Python programming language in the atmospheric sciences is “Python Programming and Visualization for Scientists, 2nd Ed.” by Alex DeCaria.
Variable Types#
Since Python is a dynamically typed language, each variable will assume a type based on what the variable is assigned.
integer
a = 1
floating point (real)
b = 5.0
string
c = 'Valpo'
boolean
d = True e = False
You can check the variable type with the type()
function.
a = 1
print(type(a))
<class 'int'>
Mathematical Calculations#
Operators#
Addition (+)
Subtraction (-)
Division (/)
Multiplication (*)
Exponentiation (**)
Floor division (//)
Modulus/remainder (%)
Order of operations the same as well
Floats and Integers work as Reals and Integers in Fortran
NOTE: In Python, integer division will yield a real in return
5/9 = 0.5555555555555556
To get the integer of division, use floor division
5//9 = 0
print(5+5)
10
Converting Types#
If you read something from a file it will be input as a string
May need to convert to integers and floats (real)
str(temp) makes temp a string
int(temp) makes temp an integer
float(temp) makes temp a real (float32)
Integer to float
new_a = float(a)
Not all conversions will work
a string that is not a number can’t be converted to an integer for float value
# Demonstrate changing the variable type
tempf = '24'
print(type(tempf))
itmpf = int(tempf)
print(type(itmpf))
<class 'str'>
<class 'int'>
Variables and Math#
TMPC = 24
TMPF = (9./5.)*TMPC + 32
# Output to the screen
print(TMPF)
print(f'The temperature in Fahrenheit is {TMPF}')
NOTE: We can also format the variable (TMPF) that we are printing out. Formats go after the variable and start with a colon. (e.g., {TMPF:.2f})
TMPC = 24
TMPK = TMPC + 273.15
print(f'The temperature in Kelvin is {TMPK}')
The temperature in Kelvin is 297.15
Subsetting Strings#
Each character within a string (including spaces) are one position. You can subset a string for a single or set of characters (positions) via its index value (address). One very important note is that Python uses a zero-based indexing scheme, so the first index value is zero (0), the second is one (1), and do on. You can also index from the end going backwards using negative numbers starting with -1, which will give you the last character.
dept = 'Geography'
print(dept[0])
print(dept[5])
print(dept[-2])
Output
G
a
h
You can also subset for a range of indecies by using the construct of start:stop:step
, where the subsetting is inclusive of the start value, but exclusive of the stop value.
print(dept[0:3])
Output
Geo
So we only get the values from the variable dept
from the index values of 0
, 1
, and 2
.
name = 'Valparaiso'
print(name[0:4]+name[-1])
Valpo