## Python Programming Basics

This tutorial is an introduction to Python basics such as how to assign a variable value and change that value. There is also a list of reserved keywords although use of these keywords is explained later.

#### Python Variable Names

Valid variable names are those that start with a letter (upper or lower case) or underscore. Valid variable names include:

myVar myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable

Invalid variable names include those that start with a number, have a space in the name, or contain special characters such as:

my Variable 4myVariable myVariable!

#### Python Reserved Keywords

There are reserved keywords in Python that control the flow of the program and cause unique behavior. Built-in constants include:

True # True logical condition False # False logical condition None # Absense of a value

Note that True, False, and None are capitalized. Common reserved keywords include:

and # logical 'and' (both conditions True) as # aliasing (e.g. with open(file) as f:) assert # internal self-check (e.g. assert x=y) break # break out of a loop class # define a new class (variables and functions) continue # advance to next 'for' or 'while' loop def # define a function del # set a variable to 'None' elif # 'else if' condition of 'if' statement else # 'else' condition of 'if' statement except # catch errors finally # 'try' exit code for # 'for' loop from # specify package element for loading global # create a global variable if # 'if' statement import # load package in # membership operator (e.g. x in y) is # test for equal identification numbers lambda # create anonymous function nonlocal # expand variable scope outside function not # logical 'not' or # logical 'or' pass # null operator when statement is required print # create display output line raise # error notification (e.g. raise Exception('Error')) return # return from function try # 'try'...'except' code structure for error catching while # loop until condition is not True with # flow control for automatic clean-up yield # intermediate return from function

There are also many built-in functions that should also be avoided when creating variable names. Some common functions are listed below.

float # convert number to floating point type id # identification number int # convert number to integer type len # number of elements in a collection max # maximum value min # minimum value pow # power (e.g. pow(x,2) or use x**2) range # sequence generator round # nearest integer value str # convert to string type type # object type

These reserved keywords should be avoided when creating variable names. Most Integrated Development Environments (IDEs) for Python and text editors for Python scripts will automatically highlight the reserved keywords such as the example below where reserved keywords are highlighted in orange and green.

answer = randint(0,10)

correct = False

while not(correct):

guess = int(input("Guess a number (0-10): "))

if guess < answer:

print("Too low")

elif guess > answer:

print("Too high")

else:

print("Correct!")

correct = True

Guess a number (0-10): 5 Too high Guess a number (0-10): 3 Too high Guess a number (0-10): 1 Too low Guess a number (0-10): 2 Correct!

#### Python Objects

Python is an object-oriented programming language. Each Python object has defining properties including the **Identity** (a memory address), **Type** (e.g. string, integer, floating point number), and **Value**. Below is an example of assigning 'x' as an Integer and printing the object properties.

print(x) # print value => 2

print(id(x)) # print id number => 1737348944

print(type(x)) # print type => <class 'int'>

#### Python Data Types

Data can be stored a variety of formats. Fundamental Data Types include **Numbers** (e.g. *int* and *float*), Sequences (e.g. *str*, *list*, and *tuple*), and Mappings (*dict*). Below are a few examples:

y=2.02 # float

z='3' # string

print(str(x)+z) # 23

print(x+int(z)) # 5

a=[x,y,z] # list

print(a[1]) # 2.02

b=(x,y) # tuple

print(b[1]) # 2.02

c={'m':7,'n':8} # dictionary

print(c['m']) # 7

#### Python Math Expressions

Python has addition (+), subtraction (-), multiplication (*), division (/), and power (**) as standard mathematical operators. The Math module is available by importing the math package. The math module provides a number of common mathematical operators such as shown in the example below.

x=3.1415

print(math.sin(x)) # 9.265e-05

The Numpy module also has many of the mathematical operators. This course uses many NumPy and SciPy built-in values and functions for scientific computing. Below is an example of using a built-in value and a trigonometric function (sine). In this case, the NumPy package is renamed as *np* to shorten the future references (numpy.pi => np.pi).

x=np.pi

print(math.sin(x)) # 1.225e-16

The result of mathematical expressions may be slightly off the expected value such as the example above that should equal to zero for sin(pi). This is due to finite machine precision (32-bit or 64-bit) calculations that have some round-off error at the last stored digit.

#### Python Strings

Strings are a list of characters. Strings are combined with the addition (+) symbol and either the single or double quotes are used.

last = "Smith"

name = first + ' ' + last

print(name) # Tom Smith

Comments can are added to Python scripts with the hash (#) symbol. When included inside a string, the comment character becomes part of the text and is no longer a comment.

print(hashtag) # prints: #learnpython

There are also special escape sequences such as newline (\n), tab indent (\t), double quote (\"), single quote (\'), and backslash (\\).

print(flight)

# prints:

# Landing at

# O'Hare International Airport

To avoid using special escape sequences such as newline, a raw string identifier (r) can be used before the string definition.

print(flight)

# prints:

# Landing at\n O\'Hare International Airport

The easiest way to convert a number to a string is with the built-in function **str**. However, this method may produce a number that has too many decimal places. Numbers can be customized in floating point (f), scientific notation (e), or percentage (%) form with **format** such as:

import numpy as np

x = np.pi

# format pi

print(str(x)) # 3.141592653589793

print('{:.2f}'.format(x)) # 3.14

print('{:.10f}'.format(x)) # 3.1415926536

print('{:.5e}'.format(x)) # 3.14159e+00

print('{:.3%}'.format(x)) # 314.159%