Strings and Control Flow


In [ ]:
import numpy as np

from astropy.table import QTable
from astropy import units as u

Strings

Strings are just arrays of characters


In [ ]:
s = 'spam'

s,len(s),s[0],s[0:2]

In [ ]:
s[::-1]

Arithmetic with Strings


In [ ]:
e = "eggs"

s + e

In [ ]:
s + " " + e

In [ ]:
4 * (s + " ") + e

In [ ]:
print(4 * (s + " ") + s + " and\n" + e)     # use \n to get a newline with the print function

You can compare strings


In [ ]:
"spam" == "good"

In [ ]:
"spam" != "good"

In [ ]:
"spam" == "spam"

In [ ]:
"sp" < "spam"

In [ ]:
"spam" < "eggs"

Python supports Unicode characters

You can enter unicode characters directly from the keyboard (depends on your operating system), or you can use the ASCII encoding.

A list of ASCII encoding can be found here.

For example the ASCII ecoding for the greek capital omega is U+03A9, so you can create the character with \U000003A9


In [ ]:
print("This resistor has a value of 100 k\U000003A9")

In [ ]:
Ω = 1e3

Ω + np.pi

Emoji are unicode characters, so you can use them a well


In [ ]:
pumpkin = "\U0001F383"
radio_telescope = "\U0001F4E1"

print(pumpkin + radio_telescope)

Emoji can not be used as variable names (at least not yet ...)


In [ ]:
🐯 = 2.345

🐯 ** 2

Watch out for variable types!


In [ ]:
n = 4

print("I would like " + n + " orders of spam")

In [ ]:
print("I would like " + str(n) + " orders of spam")

Use explicit formatting to avoid these errors

Python string formatting has the form:

{Variable Index: Format Type} .format(Variable)

Format Types d = Integer decimal g = Floating point format (Uses exponential format if exponent is less than -4) f = Floating point decimal x = hex s = String o = octal e = Floating point exponential b = binary

In [ ]:
A = 42
B = 1.23456
C = 1.23456e10
D = 'Forty Two'

In [ ]:
"I like the number {0:d}".format(A)

In [ ]:
"I like the number {0:s}".format(D)

In [ ]:
"The number {0:f} is fine, but not a cool as {1:d}".format(B,A)

In [ ]:
"The number {0:.3f} is fine, but not a cool as {1:d}".format(C,A)       # 3 places after decimal

In [ ]:
"The number {0:.3e} is fine, but not a cool as {1:d}".format(C,A)       # sci notation

In [ ]:
"{0:g} and {1:g} are the same format but different results".format(B,C)

Nice trick to convert number to a different base


In [ ]:
"Representation of the number {1:s} - dec: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(A,D)

Formatting works with units


In [ ]:
NH_D = 34.47 * u.AU

In [ ]:
"The New Horizons spacecraft is {0:.1f} from the Sun".format(NH_D)

In [ ]:
"The New Horizons spacecraft is at a distance of {0.value:.1f} in the units of {0.unit:s} from the Sun".format(NH_D)

Working with strings


In [ ]:
line = "My hovercraft is full of eels"

Find and Replace


In [ ]:
line.replace('eels', 'wheels')

Justification and Cleaning


In [ ]:
line.center(100)

In [ ]:
line.ljust(100)

In [ ]:
line.rjust(100, "*")

In [ ]:
line2 = "            My hovercraft is full of eels      "

In [ ]:
line2.strip()

In [ ]:
line3 = "*$*$*$*$*$*$*$*$My hovercraft is full of eels*$*$*$*$"

In [ ]:
line3.strip('*$')

In [ ]:
line3.lstrip('*$'), line3.rstrip('*$')

Splitting and Joining


In [ ]:
line.split()

In [ ]:
'_*_'.join(line.split())

In [ ]:
' '.join(line.split()[::-1])

Line Formatting


In [ ]:
anotherline = "mY hoVErCRaft iS fUlL oF eEELS"

In [ ]:
anotherline.upper()

In [ ]:
anotherline.lower()

In [ ]:
anotherline.title()

In [ ]:
anotherline.capitalize()

In [ ]:
anotherline.swapcase()

Control Flow

Like all computer languages, Python supports the standard types of control flows including:

  • IF statements
  • WHILE loops
  • FOR loops

In [ ]:
x = -1

if x > 0:
    print("{0} is a positive number".format(x))
else:
    print("{0} is not a positive number".format(x))

In [ ]:
x = 0

if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

In [ ]:
y = 0

while y < 12:
    print(s, end=" ")      # specify what charater to print at the end of output
    if y > 6:
        print(e, end=" * ")
    y += 1

For loops are different in python.

You do not need to specify the beginning and end values of the loop


In [ ]:
T = QTable.read('Planets.csv', format='ascii.csv')
T[0:2]

In [ ]:
for Value in T['Name']:
    print(Value)

In [ ]:
for Idx,Val in enumerate(T['Name']):
    print(Idx,Val)

In [ ]:
for Idx,Val in enumerate(T['Name']):
    
    a = T['a'][Idx] * u.AU
    
    if (a < 3.0 * u.AU):
        Place = "Inner"
        
    else:
        Place = "Outer"
    
    S = "The planet {0:s}, at a distance of {1:.1f}, is in the {2:s} solar system".format(Val,a,Place)
   
    print(S)

Loops are slow in Python. Do not use them if you do not have to!


In [ ]:
np.random.seed(42)
BigZ = np.random.random(10000)    # 10,000 value array
BigZ[:10]

In [ ]:
# This is slow!

for Idx,Val in enumerate(BigZ):
    if (Val > 0.5):
        BigZ[Idx] = 0

BigZ[:10]

In [ ]:
%%timeit

for Idx,Val in enumerate(BigZ):
    if (Val > 0.5):
        BigZ[Idx] = 0

In [ ]:
# Masks are MUCH faster

mask = np.where(BigZ>0.5)
BigZ[mask] = 0

BigZ[:10]

In [ ]:
%%timeit -o

mask = np.where(BigZ>0.5)
BigZ[mask] = 0

Bonus Topic - Symbolic Mathematics (SymPy)


In [ ]:
import sympy as sp

sp.init_printing()     # Turns on pretty printing

In [ ]:
np.sqrt(8)

In [ ]:
sp.sqrt(8)

You have to explicitly tell SymPy what symbols you want to use


In [ ]:
x, y, z = sp.symbols('x y z')

SymPy will now manipulate x, y, and z as symbols and not variables with values


In [ ]:
E = 2*x + y
E

In [ ]:
E + 3

In [ ]:
E - x

In [ ]:
E/x

SymPy has all sorts of ways to manipulates symbolic equations


In [ ]:
sp.simplify(E/x)

In [ ]:
F = (x + 2)*(x - 3)
F

In [ ]:
sp.expand(F)

In [ ]:
G = 2*x**2 + 5*x + 3
sp.factor(G)

In [ ]:
sp.solve(G,x)

In [ ]:
H = 2*y*x**3 + 12*x**2 - x + 3 - 8*x**2 + 4*x + x**3 + 5 + 2*y*x**2 + x*y
H

In [ ]:
sp.collect(H,x)

In [ ]:
sp.collect(H,y)

SymPy can do your calculus homework.


In [ ]:
G

In [ ]:
sp.diff(G,x)

In [ ]:
sp.diff(G,x,2)

In [ ]:
sp.integrate(G,x)

In [ ]:
sp.integrate(G,(x,0,5))   # limits x = 0 to 5

SymPy can do so much more. It really is magic. Complete documentation can be found here