# <ins>Lab #2: Basics + Loops, Conditionals & Functions </ins>

These exercises are meant to give you some practice with the concepts from Tutorials 2.1-2.3, as well as Tutorials 1.1/1.2 since we didn't get to the exercises last week. Be sure to use best practices, comment your code, and be mindful of your units.


```python
# Import any libraries here:
import math
import numpy as np
import matplotlib.pyplot as plt
```

***
## Arithmetic & variables

1. Use the quadratic equation, to find the roots of $5x^2 + 3x + 1$ by calculating the numerator and denominator separately. Round to 2 decimal places. (**Tip:** When parintheses in a big equation get a little hard to read, breaking it up like this is a good way to make code easier to read.)

$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$


```python
# Your code here:

import math
a,b,c = 5,3,-1

num_plus = -b + math.sqrt(b**2 - 4 * a * c)
num_minus = -b - math.sqrt(b**2 - 4 * a * c)
denom = 2*a

root_plus = num_plus/denom
root_minus = num_minus/denom

print(round(root_plus,2), round(root_minus,2))
```

    0.24 -0.84


2. Use the distance modulus, to find the distance to a star with apparent magnitude $m_v = 0.5$ and absolute magnitude $M_v = -5.85$.

$$m_v - M_v = 5log(d/10 \text{ pc})$$


```python
# Your code here:

m, M = 0.5, -5.85
d = 10**((m-M)/5)*10

print(d, 'pc')
```

    186.20871366628677 pc


***
## User input & data types

Prompt the user for their age and calculate the percent of their life they've completed assuming they live to 80 years old.


```python
# Your code here:

age = input('How old are you in years? ')

print((int(age)/80.0)*100.0, '%')
```

    How old are you in years? 21
    26.25 %


***
## Indexing

1. Print the strings "pneumono," "ultra," "volcano," and "coniosis" by slicing the word "pneumonoultramicroscopicsilicovolcanoconiosis".


```python
# Your code here:

string = "pneumonoultramicroscopicsilicovolcanoconiosis"

fourth,ninth,fifteenth = string[3], string[9], string[15]
index_20, index_3, index_12 = string[20], string[3], string[12]

print("Fourth letter:", fourth)
print("Ninth letter:", ninth)
print("Fifteenth letter:", fifteenth)

print("Third index:", index_3)
print("Twelfth index:", index_12)
print("Twentieth index:", index_20)
```

    Fourth letter: u
    Ninth letter: l
    Fifteenth letter: c
    Third index: u
    Twelfth index: a
    Twentieth index: o


2. Print the 4th, 9th, and 15th letter and the letter at the 20th, 3rd, and 12th indices of the word from part one by indexing.


```python
# Your code here:

string = "pneumonoultramicroscopicsilicovolcanoconiosis"

pneumono = string[:8]
ultra = string[8:13]
microscopic = string[13:24]
volcanoconiosis = string[-15:]

print(pneumono, ultra, microscopic, volcanoconiosis)
```

    pneumono ultra microscopic volcanoconiosis


***
## `numpy` arrays

Use the Wein displacement law to calculate the temperatures of blackbodies with 20 peak wavelengths between 300nm and 700nm using arrays.

\begin{equation}
    \lambda_{peak}T = 0.29 \text{ cm K}
\end{equation}


```python
# Your code here:

lambdas = np.linspace(300,700,20)
lambdas_cm = lambdas*1E-7

temps = 0.29 / lambdas_cm

print(temps)
```

    [9666.66666667 9032.78688525 8476.92307692 7985.50724638 7547.94520548
     7155.84415584 6802.4691358  6482.35294118 6191.01123596 5924.7311828
     5680.41237113 5455.44554455 5247.61904762 5055.04587156 4876.10619469
     4709.4017094  4553.71900826 4408.         4271.31782946 4142.85714286]


***
## Conditional statements

Write a program that has the user input a wavelength or frequency and returns (a) the photon energy, and (b) the part of the electromagnetic spectrum in which a photon of that energy falls.

$$E = h\nu \quad\text{&}\quad \lambda\nu = c$$


```python
# Your code here:

wav_or_freq = input("Would you like to enter a wavelength or a frequency? Enter w for wavelength, f for frequency: ")
val = float(input("Enter the value in centimeters for wavelength, in Hertz for frequency: "))

if wav_or_freq == 'w':
    val = val #cm
    energy = 4.13E-15*(3*10**10)/(val) #eV
elif wav_or_freq == 'f':
    energy = 4.13E-15*val #eV
    val = (3*10**10)/(val) #cm

if val < 1E-9:
    print("Gamma; energy = ", energy, "eV")
elif val < 1.0E-6 and val > 1.0E-9:
    print("X-ray; energy = ", energy, "eV")
elif val < 3.5E-5 and val > 1.0E-6:
    print("UV; energy = ", energy, "eV")
elif val < 7.5E-5 and val > 3.5E-5:
    print("Visible; energy = ", energy, "eV")
elif val < 0.5 and val > 7.5E-5:
    print("IR; energy = ", energy, "eV")
else:
    print("Radio; energy = ", energy, "eV")

```

    Would you like to enter a wavelength or a frequency? Enter w for wavelength, f for frequency: w
    Enter the value in centimeters for wavelength, in Hertz for frequency: 1
    Radio; energy =  0.0001239 eV


***
## Loops and plotting

1. Add together every third number in the list [155,2,54,34,5,16,7,38,26,10] and print the result.


```python
# Your code here:

lst = [155,2,54,34,5,16,7,38,26,10]

summation = 0
for n,x in enumerate(lst):
    if n % 3 == 0:
        summation += x
        
print(summation)
```

    206


2. Plot the sine and cosine functions on separate sides of the y-axis.


```python
# Your code here:

x = np.linspace(-2*np.pi,2*np.pi)
sine = np.sin(x)
cosine = np.cos(x)

plt.plot(x,sine)
plt.plot(x,cosine)
```

3. The rules for Pin-Pon are as follows:

    - Start counting numbers, starting from 1. 
    - Whenever the next number's a multiple of 3 (3, 6, 9,…), replace the actual number with, "Pin." 
    - Whenever the next number's a multiple of 5, replace it with the word, "Pon."
    - Whenever the number's a multiple of both 3 and 5, say, "Pin Pon."
    - Keep going until someone messes up.

Write a program that prints the results of the game for 1 through 100.


```python
# Your code here:

for n in range(1,101):
    if (n % 3 == 0) and (n % 5 == 0):
        print("Pin Pon")
    elif n % 5 == 0:
        print("Pin")
    elif n % 3 == 0:
        print("Pon")
    else:
        print(n)
```

***
## Putting it all together

These are meant to use all of your new skills at once. That being said, you may have notice that there's no "Functions" section above --- once you've completed each of the tasks below, please turn them into functions, comment them well, and add them to a Python script which will serve as a library for the future. 

1. (From Lab 1): While DMS (degrees, minutes, seconds) and HMS (hours, minutes, seconds) formats for celestial coordinates have their place (e.g. in every database ever), having them in decimal degrees is often more convenient for calculations. Write two scripts: one that allows the user to enter in a DMS coordinate and prints it in decimal degrees, and another for HMS coordinates.


```python
# Your code here:

# DMS
dms = input("Enter D:M:S coordinates, separated by colons: ")
dms = dms.split(":")
degs, mins, secs = dms
decdeg = float(degs) + float(mins)/60.0 + float(secs)/3600.0

print("Decimal degrees:", decdeg)

# HMS
hms = input("Enter H:M:S coordinates, separated by colons: ")
hms = hms.split(":")
hrs, mins, secs = hms
decdeg = (float(hrs) + float(mins)/60.0 + float(secs)/3600.0) * 15

print("Decimal degrees:", decdeg)
```

2. In my research on X-ray binaries, I utilize the Novikov-Thorne thin accretion disk approximation for black holes, which relates the temperature of the accertion disk to the mass of the accretor. Typical disk temperatures range between 0.5 and 1.0 keV. Using this relationship, calculate the mass of black holes (a) within this range, (b) in the "interesting" regime of 1.0 to 5.0 keV, and (c) in the "crazy" range of >5.0 keV. Plot your results, making sure the three regimes are clearly labeled in your plot. (P.S. -- X-ray astronomers often talk about temperatures in terms of energy rather than Kelvin, so keep that in mind with this equation.)

$$T_{eff} \text{ [keV]} \sim \Bigg(\frac{10M_\odot}{M}\Bigg)^{1/4} \text{ keV}$$


```python
# Your code here:

temps_normal = np.linspace(0.5,1.0,100)
temps_interesting = np.linspace(1.0,5.0,100)
temps_crazy = np.linspace(5.0,6.0,100)

'''
Input: temp -- keV
Output: mass -- solar masses
'''
def mass(temp):
    return (10.0/temp**4)**(-1.0)

mass_normal = mass(temps_normal)
mass_interesting = mass(temps_interesting)
mass_crazy = mass(temps_crazy)

plt.plot(temps_normal,mass_normal,label="Normal")
plt.plot(temps_interesting,mass_interesting,label="Interesting")
plt.plot(temps_crazy,mass_crazy,label="Crazy")
plt.xlabel("Disk temperature [keV]")
plt.ylabel(r"Mass of black hole $M_\odot$")
plt.title("Novikov-Thorne Thin Accretion Disk Relationship")
plt.legend()
plt.show()
plt.close()
```


```python

```

18fd83b848cf55b3a5aa61bf1cb942bd72bfae4e
ipynb
Jupyter Notebook
files/astr211_lab2-exercises-KEY.ipynb
mvtea/mvtea.github.io
91cb2558e570bba35e2f0718c4c658cd7317bd5d
MIT
files/astr211_lab2-exercises-KEY.ipynb
mvtea/mvtea.github.io
91cb2558e570bba35e2f0718c4c658cd7317bd5d
MIT
files/astr211_lab2-exercises-KEY.ipynb
mvtea/mvtea.github.io
91cb2558e570bba35e2f0718c4c658cd7317bd5d
MIT
Qwen/Qwen-72B
1. YES
2. YES