This page was generated from notebooks/L2/datatypes_fun.ipynb.
Binder badge
You can directly download the pdf-version of this page using the link below.
download

Fun with DataTypes#

1. String Manipulation: Physics Puns and Jokes#

  • Exercise: Write a Python program that stores physics jokes or puns in strings and then prints them out to the console. For example, “Why can’t you trust an atom? Because they make up everything!” This introduces into string data types and basic input/output operations.

[23]:
import numpy as np

jokes = [
    "Why can't you trust an atom? Because they make up everything!",
    "What is a physicist's favorite food? Fission chips.",
    "Why are quantum physicists bad lovers? Because when they find the position, they can't find the momentum, and when they have the momentum, they can't find the position.",
    "Why did the sun go to school? To get a little brighter!",
    "Why can't you take electricity to social events? Because it doesn't know how to conduct itself.",
    "Why is the first joke wrong? Because most of the space is vacuum!"
]

print(jokes[0].split(" ")[2])
you

2. Integers and Floats: Calculating Physics Constants#

  • Exercise: Create a program that calculates and prints the value of various physics constants, such as the speed of light in a vacuum, Planck’s constant, or the gravitational constant. This will help practice using integers and floats, as well as basic arithmetic operations in Python.

Speed of light

  • Definition: The speed at which light travels in vacuum, a fundamental physical constant denoted by c.

  • Value in Metric 299,792,458 metres per second

  • Upper Speed Limit: c is the maximum speed at which all conventional matter, energy, or any signal carrying information can travel.

  • Historical Measurement: First demonstrated to not be instantaneous by Ole Rømer in 1676 using Jupiter’s moon Io.

  • Relevance Beyond Light: Albert Einstein showed its significance outside of light in the theory of relativity, including in the equation

    \[E=mc^2\]

    .

  • Refractive Index: The speed of light in materials such as glass or air is less than c, affecting its speed based on the medium’s refractive index.

[26]:
speed_of_light = 299792458  # Speed of light in vacuum, in meters per second (m/s)
plancks_constant = 6.62607015e-34  # Planck's constant, in Joule seconds (J.s)
gravitational_constant = 6.67430e-11  # Gravitational constant, in Newton meter squared per kilogram squared (N m^2 / kg^2)
boltzmann_constant = 1.380649e-23  # Boltzmann constant, in Joules per Kelvin (J/K)


print("Speed of Light in Vacuum: {} m/s".format(speed_of_light))
print(f"Planck's Constant: {plancks_constant} J.s")
print(f"Gravitational Constant: {gravitational_constant} N m^2 / kg^2")
print(f"Boltzmann Constant: {boltzmann_constant} J/K")
Speed of Light in Vacuum: 299792458 m/s
Planck's Constant: 6.62607015e-34 J.s
Gravitational Constant: 6.6743e-11 N m^2 / kg^2
Boltzmann Constant: 1.380649e-23 J/K

3. Lists: Tracking Particles in an Accelerator#

  • Exercise: Create a list of particles (e.g., protons, neutrons, electrons) being accelerated in a hypothetical experiment. They should write functions to add, remove, and modify particles in the list, simulating real-world data manipulation. This introduces lists and list operations.

[28]:
particles = ['proton', 'neutron', 'electron', 'positron']

particles.append('muon')
print("Added 'muon' to the list.")
print("Current list of particles:", particles)


particles.remove('positron')
print("Removed 'positron' from the list.")

particles[particles.index('muon')]="tau"
#particles[index] = 'tau'
print("Replaced 'muon' with 'tau'.")

print("Current list of particles:", particles)
Added 'muon' to the list.
Current list of particles: ['proton', 'neutron', 'electron', 'positron', 'muon']
Removed 'positron' from the list.
Replaced 'muon' with 'tau'.
Current list of particles: ['proton', 'neutron', 'electron', 'tau']

4. Tuples: Storing Atomic Data#

  • Exercise: One can use tuples to store atomic data, such as atomic number, atomic mass, and electron configuration for different elements. Write a function to print this data in a formatted way. This exercise teaches the immutability of tuples and how they can be used to store related data.

[30]:
hydrogen = (1, 1.008, "1s1")
helium = (2, 4.002602, "1s2")
carbon = (6, 12.011, "[He] 2s2 2p2")
oxygen = (8, 15.999, "[He] 2s2 2p4")

elements = [hydrogen, helium, carbon, oxygen]
elements
[30]:
[(1, 1.008, '1s1'),
 (2, 4.002602, '1s2'),
 (6, 12.011, '[He] 2s2 2p2'),
 (8, 15.999, '[He] 2s2 2p4')]

5. Dictionaries: Cataloging the Periodic Table#

  • Exercise: Create a dictionary where each key-value pair consists of an element (key) and its properties (value) such as atomic number, atomic mass, and state at room temperature. This exercise introduces dictionaries and how to access and modify their data.

[32]:
elements = {
    'H': {'atomic_number': 1, 'atomic_mass': 1.008, 'state_at_room_temp': 'gas'},
    'He': {'atomic_number': 2, 'atomic_mass': 4.002602, 'state_at_room_temp': 'gas'},
    'C': {'atomic_number': 6, 'atomic_mass': 12.011, 'state_at_room_temp': 'solid'},
    'O': {'atomic_number': 8, 'atomic_mass': 15.999, 'state_at_room_temp': 'gas'},
    'N': {'atomic_number': 7, 'atomic_mass': 14.007, 'state_at_room_temp': 'gas'}
}

element_symbol = 'C'
carbon_properties = elements[element_symbol]
print(f"Properties of Carbon (C):")
print(f"Atomic Number: {carbon_properties['atomic_number']}")
print(f"Atomic Mass: {carbon_properties['atomic_mass']}")
print(f"State at Room Temperature: {carbon_properties['state_at_room_temp']}")

elements['C']['state_at_room_temp'] = 'graphite (solid)'
print("\nUpdated properties of Carbon (C):")
print(f"State at Room Temperature: {elements['C']['state_at_room_temp']}")

elements['Ne'] = {'atomic_number': 10, 'atomic_mass': 20.1797, 'state_at_room_temp': 'gas'}
print("\nAdded properties of Neon (Ne):")
print(f"Atomic Number: {elements['Ne']['atomic_number']}")
print(f"Atomic Mass: {elements['Ne']['atomic_mass']}")
print(f"State at Room Temperature: {elements['Ne']['state_at_room_temp']}")
Properties of Carbon (C):
Atomic Number: 6
Atomic Mass: 12.011
State at Room Temperature: solid

Updated properties of Carbon (C):
State at Room Temperature: graphite (solid)

Added properties of Neon (Ne):
Atomic Number: 10
Atomic Mass: 20.1797
State at Room Temperature: gas

6. Boolean Logic: Evaluating Collision Outcomes#

  • Exercise: Write a program that uses Boolean logic to determine the outcome of particle collisions based on their properties (e.g., mass, velocity). For example, whether the particles will bounce off each other, merge, or disintegrate. This is about Boolean data types and conditional statements.

[34]:
# Particle properties
particle1_mass = 2
particle1_velocity = 3
particle1_hardness = 8

particle2_mass = 3
particle2_velocity = 1
particle2_hardness = 7

# Calculate relative velocity
relative_velocity = abs(particle1_velocity - particle2_velocity)

# Determine outcomes using boolean logic
bounce = (relative_velocity < 5 and particle1_hardness + particle2_hardness > 15) or (relative_velocity >= 5 and particle1_hardness + particle2_hardness >= 10)
merge = relative_velocity < 5 and particle1_hardness + particle2_hardness <= 15
disintegrate = relative_velocity >= 5 and particle1_hardness + particle2_hardness < 10

# Print the outcome
print("Outcome of the collision:")
print("Bounce:", bounce)
print("Merge:", merge)
print("Disintegrate:", disintegrate)
Outcome of the collision:
Bounce: False
Merge: True
Disintegrate: False

7. Sets: Unique Quantum States#

  • Exercise: Create a set of quantum states that a particle can occupy, then write functions to add and remove states, ensuring no duplicates are allowed. This can introduce the concept of sets and their properties, such as uniqueness and set operations.

[38]:
quantum_states = {'state1', 'state2', 'state3'}

print("Initial quantum states:", quantum_states)

quantum_states.add('state4')  # This will be added
quantum_states.add('state2')  # This will not be added as it's a duplicate
print("Quantum states after adding new states:", quantum_states)

quantum_states.remove('state1')  # This will remove 'state1'
quantum_states.discard('state5')  # This will not do anything as 'state5' does not exist
print("Quantum states after removal:", quantum_states)
Initial quantum states: {'state1', 'state2', 'state3'}
Quantum states after adding new states: {'state1', 'state4', 'state2', 'state3'}
Quantum states after removal: {'state4', 'state2', 'state3'}

8. Fun with Complex Numbers: Quantum Mechanics Basics#

  • Exercise: Since complex numbers are used in quantum mechanics, perform operations with complex numbers in Python (e.g., adding wave functions). This will help to get comfortable with complex data types and their applications in physics.

Indistinguishable particles

In quantum mechanics, indistinguishable particles are particles that cannot be distinguished from one another, even in principle.

  • Categories of particles: Bosons and fermions

  • Principle: Cannot be distinguished from each other even in principle

  • Examples of bosons: Photons, gluons, helium-4 nuclei

  • Examples of fermions: Electrons, neutrinos, protons

Indistinguishability has important consequences in quantum mechanics in the same way as it is of importance for probability theory.

[40]:
wave_function1 = 3 + 4j
wave_function2 = 1 - 2j

sum_wave_functions = wave_function1 + wave_function2

difference_wave_functions = wave_function1 - wave_function2

product_wave_functions = wave_function1 * wave_function2

quotient_wave_functions = wave_function1 / wave_function2

conjugate_wave_function1 = wave_function1.conjugate()

print(f"Wave Function 1: {wave_function1}")
print(f"Wave Function 2: {wave_function2}")
print(f"Sum of Wave Functions: {sum_wave_functions}")
print(f"Difference of Wave Functions: {difference_wave_functions}")
print(f"Product of Wave Functions: {product_wave_functions}")
print(f"Quotient of Wave Functions: {quotient_wave_functions}")
print(f"Conjugate of Wave Function 1: {conjugate_wave_function1}")


psi1 = 2 + 3j
psi2 = 4 - 5j

psi_resultant = psi1 + psi2

print(f"Resultant Wave Function (psi1 + psi2): {psi_resultant}")
Wave Function 1: (3+4j)
Wave Function 2: (1-2j)
Sum of Wave Functions: (4+2j)
Difference of Wave Functions: (2+6j)
Product of Wave Functions: (11-2j)
Quotient of Wave Functions: (-1+2j)
Conjugate of Wave Function 1: (3-4j)
Resultant Wave Function (psi1 + psi2): (6-2j)