In this lecture, you will learn:
Dictionaries are denoted by curly brackets { } (similar to sets). Dictionaries are somewhat like lists, but denoted by alphanumeric keys rather than integer indices. Here's what a dictionary data structure looks like:
solar_planets = {'Mercury': 2440.0, 'Venus': 6052.1, 'Earth': 6371.5, 'Mars': 3389.2, 'Jupiter': 69911.0, 'Saturn': 58232.2}
print(type(solar_planets), solar_planets)
Each element in a dictionary has two aspects: key and value. To access a value, use the key with square brackets [ ]:
print(solar_planets['Venus'])
Unlike standard dictionaries, you can change a key's value, add a new key, or remove keys using the del function:
solar_planets['Uranus'] = 25362.0 # add Uranus to the dict del solar_planets['Earth'] # remove the key 'Earth' print(solar_planets.keys()) # return the keys in a dictionary
Python uses INDENTATIONS to define the code blocks and make the code readable. This is one of the most distinctive features of Python.
food = input("What's your favorite food? ") if food == 'garlic': print('I think', food, 'is super yucky') else: print('I think', food, 'is super yummy')
Common logic operators used for program control:
== : equals!= : does not equal<, <=, >, >= : comparisonand / or : combine multiple testsThe code-block is executed if the condition is true. elif (else if) and else handle additional conditions.
exam = 82.0 if exam >= 90.0: Grade = 'A' elif exam >= 80.0: Grade = 'B' else: Grade = 'Fail' print('Your final grade is', Grade)
A while loop executes a block as long as a condition is True.
N = 100 threshold = 90 while (N > threshold): print(N) N = N - 1 print('and the final value is: ', N)
A for loop steps through a list and does something at each step.
mylist = ['jane', 'josh', 'sid', 'geoff'] for name in mylist: print(name)
Below is an example of an if statement inside a for loop to identify habitable planets:
solar_planets = {'Mercury':440.0, 'Venus':737.1, 'Earth':288.5, 'Mars':210.2}
for key in solar_planets.keys():
temperature = solar_planets[key] - 273.1 # Convert Kelvin to Celsius
if (temperature <= 100) and (temperature >= -100):
print('Planet', key, 'is habitable at', round(temperature, 1), '°C')