Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # TRY THIS IN THE BEGINNING OF LECTURE AND SEE IF IT WORKS:
- # If you get an SSL-error, see Moodle for the "SSL-errors with internet data, HOW TO FIX"
- # If it works okay, you'll see data in raw format in console window
- # If you get an SSL-error, the code is not working as expected
- import urllib.request
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- print(raw_data)
- # NEW FILE
- # collections inside a collection
- temp_day_1 = [13.5, 16.4, 11.6, 11.3]
- temp_day_2 = [12.1, 15.2, 11.9, 10.4]
- temp_day_3 = [15.3, 17.6, 12.5, 11.6]
- # temperatures has measurements from 3 days
- # each day has 4 temperature values
- temperatures = [temp_day_1, temp_day_2, temp_day_3]
- # process each day, one at a time
- for day in temperatures:
- print("Processing new day!")
- # process each temperature in ONE DAY at a time
- for t in day:
- print(t)
- # NEW FILE
- movies = ["Interstellar", "Forrest Gump", "Jurassic Park"]
- books = ["Lord of the Rings", "Da Vinci Code", "Robinson Crusoe"]
- # all data is in list of lists, each sublist is a category of products
- products = [movies, books]
- # process all data, each category at a time
- for category in products:
- # process each item in each category
- for item in category:
- print(item)
- # NEW FILE
- # dictionary inside another dictionary
- book = {
- "name": "My Lady Jane",
- "year": 2016,
- "publisher": {
- "name": "HarperTeen",
- "organization": "HarperCollins Publishers",
- "location": "New York"
- }
- }
- # just getting name, fairly straightforward
- print(book['name'])
- # if the dictionary is simple, you can chain the keys
- # publisher -> location
- print(book['publisher']['location'])
- # using a helper variable is also okay!
- publisher = book['publisher']
- print(publisher['location'])
- # NEW FILE
- # example, list inside a dictionary
- book = {
- "name": "My Lady Jane",
- "year": 2016,
- "authors": ["Cynthia Hand", "Brodi Ashton", "Jodi Meadows"]
- }
- # get second author
- print(book['authors'][1])
- print()
- # you can also loop through the authors
- # because book['authors'] is a LIST
- for author in book['authors']:
- print(author)
- # NEW FILE
- # our products, list of dicts
- products = [
- {"name": "Coffee maker", "price": 79},
- {"name": "Dishwasher", "price": 299},
- {"name": "Freezer", "price": 199},
- ]
- # process one product at a time
- for product in products:
- name = product['name']
- price = product['price']
- # print name and price of one product
- print(f"{name}, {price} €")
- # NEW FILE , HOTELS
- # install this first!
- import var_dump as vd
- # create first hotel
- hotel_1 = {
- "name": "Snow Line Hotels",
- "rating": 4.3,
- "wifi": True,
- "free_breakfast": True,
- "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
- "price_level": 4
- }
- # create second hotel
- hotel_2 = {
- "name": "North Ice Hostel",
- "rating": 3.5,
- "wifi": True,
- "free_breakfast": False,
- "services": ["sauna", "parking"],
- "price_level": 2
- }
- # place both hotels into one list
- hotels = [hotel_1, hotel_2]
- # vd.var_dump(hotels)
- # sometimes it's easier to inspect only one piece of data
- # at a time (one hotel)
- # test_hotel = hotels[0]
- # vd.var_dump(test_hotel)
- # print(test_hotel['name'])
- # print(test_hotel['services'])
- for hotel in hotels:
- print(hotel['name'])
- # traditional way: use a for loop for the services -list
- # print all services in a loop one by one
- # because hotel['services'] is a LIST
- # for service in hotel['services']:
- # print(service)
- # another way: use join() -function
- # ONLY WORKS WITH TEXT OR NUMBER LISTS, DOESN'T WORK
- # WITH LIST OF DICTIONARIES!
- services = "\n".join(hotel['services'])
- print(services)
- print()
- # NEW FILE
- # place both hotels into one list
- hotels = [hotel_1, hotel_2]
- for hotel in hotels:
- print(hotel['name'])
- if "restaurant" in hotel['services']:
- print("Hotel has a restaurant!")
- print()
- # NEW FILE
- # place both hotels into one list
- hotels = [hotel_1, hotel_2]
- # empty list for having sauna hotels later on
- sauna_hotels = []
- for hotel in hotels:
- print(hotel['name'])
- # if sauna in services, add hotel name to the sauna hotels list
- if "sauna" in hotel['services']:
- sauna_hotels.append(hotel['name'])
- print()
- print(sauna_hotels)
- # NEW FILE
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- # vd.var_dump(data)
- # if you want to see only the first event at first
- # to understand the data better:
- # test_event = data[0]
- # vd.var_dump(test_event)
- # print(test_event['name'])
- # print(test_event['categories'])
- # go through all events in data, regardless
- # how many events we have this time
- for event in data:
- print(event['name'])
- # build the address from dictionary (address)
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- print(f"{postal_code} {street_address}")
- # combine categories -list into a text separated by commas
- categories = ", ".join(event['categories'])
- # only print categories if they exist
- if categories != "":
- print(categories)
- else:
- print("No categories.")
- print()
- # NEW FILE
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- # ask user for a search term
- choice = input("What are you looking for?\n")
- # go through all events in data, regardless
- # how many events we have this time
- for event in data:
- # combine categories -list into a text separated by commas
- categories = ", ".join(event['categories'])
- # if user's search word wasn't in the categories
- # skip this event completely and continue with next one!
- if choice not in categories:
- continue
- print(event['name'])
- # build the address from dictionary (address)
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- print(f"{postal_code} {street_address}")
- # only print categories if they exist
- if categories != "":
- print(categories)
- else:
- print("No categories.")
- print()
- # NEW FILE
- import urllib.request
- import json
- # this module needs to be installed separately
- # in PyCharm you can install the package if its not found!
- import var_dump as vd
- # get internet data
- url = 'https://edu.frostbit.fi/api/events/en'
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- # the needed data from internet is now in the "data" -variable!
- data = json.loads(raw_data)
- # ask user for a search term
- choice = input("What are you looking for?\n")
- # go through all events in data, regardless
- # how many events we have this time
- for event in data:
- # combine categories -list into a text separated by commas
- categories = ", ".join(event['categories'])
- # if we found a matching event
- # print all details and call BREAK to
- # end this loop (because no point in looking further
- # because we already found what we were looking for)
- if choice in categories:
- print("Found a matching event!")
- print(event['name'])
- # build the address from dictionary (address)
- street_address = event['address']['street_address']
- postal_code = event['address']['postal_code']
- print(f"{postal_code} {street_address}")
- # only print categories if they exist
- if categories != "":
- print(categories)
- else:
- print("No categories.")
- break
- # NEW FILE
- import json
- import urllib.request
- url = "https://edu.frostbit.fi/api/weather/"
- req = urllib.request.Request(url)
- raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
- weather = json.loads(raw_data)
- # initialize variables needed in loop
- strongest_wind = 0
- strongest_city = ""
- weakest_wind = 0
- weakest_city = ""
- for city in weather:
- print(city['location'])
- print(city['wind'])
- print()
- # if-statement, if current wind is bigger than previous
- # biggest wind => this wind is now the biggest
- # also savet the city name!
Add Comment
Please, Sign In to add comment