Advertisement
tuomasvaltanen

Untitled

Nov 14th, 2024 (edited)
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.06 KB | None | 0 0
  1. # TRY THIS IN THE BEGINNING OF LECTURE AND SEE IF IT WORKS:
  2. # If you get an SSL-error, see Moodle for the "SSL-errors with internet data, HOW TO FIX"
  3.  
  4. # If it works okay, you'll see data in raw format in console window
  5. # If you get an SSL-error, the code is not working as expected
  6.  
  7. import urllib.request
  8.  
  9. # get internet data
  10. url = 'https://edu.frostbit.fi/api/events/en'
  11. req = urllib.request.Request(url)
  12. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  13.  
  14. print(raw_data)
  15.  
  16. # NEW FILE
  17.  
  18. # collections inside a collection
  19. temp_day_1 = [13.5, 16.4, 11.6, 11.3]
  20. temp_day_2 = [12.1, 15.2, 11.9, 10.4]
  21. temp_day_3 = [15.3, 17.6, 12.5, 11.6]
  22.  
  23. # combine all days into a separate "main" list
  24. temperatures = [temp_day_1, temp_day_2, temp_day_3]
  25.  
  26. # raw printing format is mostly used in working life
  27. # just to quickly check if there's any data at all
  28. # for any other purpose, it's not usable
  29. # (because nobody understands what's going on)
  30. # print(temperatures)
  31.  
  32. # loop through each day in the temperatures list
  33. for day in temperatures:
  34.     print("NEW DAY!")
  35.     # for the current active day,
  36.     # loop through each individual temperature measurement
  37.     # the data as x amount of days, a single day has an y amount of temperatures
  38.     for t in day:
  39.         print(f"{t} ℃")
  40.  
  41.     print()
  42.  
  43. # NEW VERSION OF LIST OF LISTS
  44.  
  45. # another version of list of lists
  46. # product categories in a webstore
  47. books = ["Lord of the Rings", "Da Vinci Code", "Robinson Crusoe"]
  48. movies = ["Interstellar", "Forrest Gump", "Jurassic Park"]
  49.  
  50. # list of lists => all products split by the categories
  51. products = [books, movies]
  52.  
  53. # since products is a list of lists
  54. # we need a for loop with another for loop
  55. for category in products:
  56.     # for each product item in current active category
  57.     for item in category:
  58.         print(item)
  59.  
  60. # NEW FILE
  61.  
  62. # dictionary inside another dictionary
  63. book = {
  64.     "name":  "My Lady Jane",
  65.     "year":  2016,
  66.     "publisher": {
  67.         "name": "HarperTeen",
  68.         "organization": "HarperCollins Publishers",
  69.         "location": "New York"
  70.     }
  71. }
  72.  
  73. # printing the whole dictionary is usually a bit too rough
  74. # to understand what's going on, use indexes instead
  75.  
  76. # NOTE! We don't usually need loops with dictionaries
  77. # Dictionaries are just collections of variables, and they are not
  78. # # super difficult to use
  79. # but if you always try to use loops with dictionaries, it's very difficult
  80. # print(book)
  81.  
  82. print(book["name"])
  83. print()
  84.  
  85. # how to use nested dictionaries, in this case, publisher
  86. # approach 1: save the nested dictionary into a helper variable
  87. publisher = book['publisher']
  88. print(publisher['organization'])
  89.  
  90. # approach 2: direct chaining also ok
  91. print(book['publisher']['organization'])
  92.  
  93. # NEW FILE
  94.  
  95. # our list of dictionaries, products
  96. products = [
  97.     {"name": "Coffee maker", "price": 79},
  98.     {"name": "Dishwasher", "price": 299},
  99.     {"name": "Freezer", "price": 199},
  100.     {"name": "Toothbrush", "price": 3}
  101. ]
  102.  
  103. # loop through the list of products
  104. # each product (item) is one dictionary
  105. # containing name and price
  106. for item in products:
  107.     print(f"{item['name']} - {item['price']} €")
  108.  
  109. # NEW FILE, HOTEL DATA
  110.  
  111. import var_dump as vd
  112.  
  113. # create first hotel
  114. hotel_1 = {
  115.     "name": "Snow Line Hotels",
  116.     "rating": 4.3,
  117.     "wifi": True,
  118.     "free_breakfast": True,
  119.     "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
  120.     "price_level": 4
  121. }
  122.  
  123. # create second hotel
  124. hotel_2 = {
  125.     "name": "North Ice Hostel",
  126.     "rating": 3.5,
  127.     "wifi": True,
  128.     "free_breakfast": False,
  129.     "services": ["sauna", "parking"],
  130.     "price_level": 2
  131. }
  132.  
  133. # place both hotels into one list
  134. hotels = [hotel_1, hotel_2]
  135.  
  136. # just printing hotels the basic way, very hard to see the structure. try var_dump instead
  137. # print(hotels)
  138. # vd.var_dump(hotels)
  139.  
  140. # first_hotel = hotels[0]
  141. # vd.var_dump(first_hotel)
  142.  
  143. # NEW VERSION
  144.  
  145. # use console/terminal and:
  146. # pip install var_dump
  147. import var_dump as vd
  148.  
  149. # create first hotel
  150. hotel_1 = {
  151.     "name": "Snow Line Hotels",
  152.     "rating": 4.3,
  153.     "wifi": True,
  154.     "free_breakfast": True,
  155.     "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
  156.     "price_level": 4
  157. }
  158.  
  159. # create second hotel
  160. hotel_2 = {
  161.     "name": "North Ice Hostel",
  162.     "rating": 3.5,
  163.     "wifi": True,
  164.     "free_breakfast": False,
  165.     "services": ["sauna", "parking"],
  166.     "price_level": 2
  167. }
  168.  
  169. # place both hotels into one list
  170. hotels = [hotel_1, hotel_2]
  171.  
  172. # print(hotels)
  173. # vd.var_dump(hotels)
  174.  
  175. # first_hotel = hotels[0]
  176. # vd.var_dump(first_hotel)
  177.  
  178. # many coders make a comment that helps remembering
  179. # the data structure FOR A SINGLE ITEM (hotel)
  180. # [0] => dict(6)
  181. #     ['name'] => str(16) "Snow Line Hotels"
  182. #     ['rating'] => float(4.3)
  183. #     ['wifi'] => bool(True)
  184. #     ['free_breakfast'] => bool(True)
  185. #     ['services'] => list(5)
  186. #         [0] => str(5) "sauna"
  187. #         [1] => str(8) "meetings"
  188. #         [2] => str(10) "restaurant"
  189. #         [3] => str(7) "parking"
  190. #         [4] => str(7) "safaris"
  191. #     ['price_level'] => int(4)
  192.  
  193. for hotel in hotels:
  194.     # the structure of each single hotel is described above
  195.     # name of the hotel is easy to get, just print out the variable
  196.     print(hotel['name'])
  197.  
  198. # NEW VERSION
  199.  
  200. # use the same hotel data is before
  201.  
  202. for hotel in hotels:
  203.     # the structure of each single hotel is described above
  204.     # name of the hotel is easy to get, just print out the variable
  205.     print(hotel['name'])
  206.     print("--------------------")
  207.  
  208.     # services is another list inside a hotel, we need a loop
  209.     # for service in hotel['services']:
  210.     #    print(service)
  211.  
  212.     # since services is just a text list, we have an option -> join() -function
  213.     # this is considered a good practice => it's easy to understand and we avoid
  214.     # one level of for loops
  215.     services = "\n".join(hotel['services'])
  216.     print(services)
  217.  
  218.     print()
  219.  
  220. # NEW VERSION, filtering hotels
  221.  
  222. # hotel data same as before
  223.  
  224. # create an empty list to catch all matching hotels later in the loop
  225. restaurant_hotels = []
  226.  
  227. for hotel in hotels:
  228.     # the structure of each single hotel is described above
  229.     # name of the hotel is easy to get, just print out the variable
  230.     print(hotel['name'])
  231.     print("--------------------")
  232.  
  233.     # filter out into a separate list: only hotels that have a restaurant
  234.     if "restaurant" in hotel['services']:
  235.         restaurant_hotels.append(hotel['name'])
  236.  
  237.     print()
  238.  
  239. # just test print the whole list to see if our filtering worked
  240. print(restaurant_hotels)
  241.  
  242. # NEW FILE, actual internet API address, events data
  243.  
  244. import urllib.request
  245. import var_dump as vd
  246. import json
  247.  
  248. # get internet data
  249. url = 'https://edu.frostbit.fi/api/events/en'
  250. req = urllib.request.Request(url)
  251. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  252.  
  253. # convert the raw JSON (text) into Python data format
  254. data = json.loads(raw_data)
  255.  
  256. # vd.var_dump(data)
  257.  
  258. # example of a single event:
  259. # [0] => dict(4)
  260. #     ['name'] => str(17) "Hub Karaoke Night"
  261. #     ['date'] => str(9) "22.6.2025"
  262. #     ['categories'] => list(3)
  263. #         [0] => str(7) "karaoke"
  264. #         [1] => str(5) "music"
  265. #         [2] => str(13) "participation"
  266. #     ['address'] => dict(2)
  267. #         ['street_address'] => str(16) "Lönnrotinkatu 21"
  268. #         ['postal_code'] => str(5) "00120"
  269.  
  270. # all set, let's loop through our events
  271. for event in data:
  272.     print(event['name'])
  273.  
  274. # NEW VERSION
  275.  
  276. # use the event data as previously
  277.  
  278. # all set, let's loop through our events
  279. for event in data:
  280.     # print the name of the event
  281.     print(event['name'])
  282.  
  283.     # get address info into separate variables
  284.     street_address = event['address']['street_address']
  285.     postal_code = event['address']['postal_code']
  286.  
  287.     # finally print the address info for the user
  288.     print(f"{postal_code} {street_address}")
  289.  
  290.     # print the categories also
  291.     categories = ", ".join(event['categories'])
  292.  
  293.     # since we can't trust this data to always have
  294.     # categories, we have catch this situation
  295.     if len(event['categories']) > 0:
  296.         print(f"CATEGORIES: {categories}")
  297.     else:
  298.         print("-- NO CATEGORIES! --")
  299.  
  300.     print()
  301.  
  302. # VERSION 2, simple search engine: filter only those that match user's choice
  303.  
  304. # VERSION 2: simple search engine feature by a category name
  305. # ONLY SHOW THOSE EVENTS THAT MATCH THE CATEGORY THAT USER SELECTS
  306.  
  307. import urllib.request
  308. import json
  309.  
  310. # get internet data
  311. url = 'https://edu.frostbit.fi/api/events/en'
  312. req = urllib.request.Request(url)
  313. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  314.  
  315. # convert the raw JSON (text) into Python data format
  316. data = json.loads(raw_data)
  317.  
  318. # user's search term for category
  319. choice = input("What kind of events are you looking for?\n")
  320.  
  321. # all set, let's loop through our events
  322. for event in data:
  323.     # print the categories also
  324.     categories = ", ".join(event['categories'])
  325.  
  326.     # if the user's choice is not in the categories => SKIP THIS EVENT
  327.     if choice not in categories:
  328.         continue
  329.  
  330.     # print the name of the event
  331.     print(event['name'])
  332.  
  333.     # get address info into separate variables
  334.     street_address = event['address']['street_address']
  335.     postal_code = event['address']['postal_code']
  336.  
  337.     # finally print the address info for the user
  338.     print(f"{postal_code} {street_address}")
  339.  
  340.  
  341.     # since we can't trust this data to always have
  342.     # categories, we have catch this situation
  343.     if len(event['categories']) > 0:
  344.         print(f"CATEGORIES: {categories}")
  345.     else:
  346.         print("-- NO CATEGORIES! --")
  347.  
  348.     print()
  349.  
  350. # NEW VERSION
  351.  
  352. # VERSION 3: simple search engine feature by a category name
  353. # ONLY SHOW THE FIRST EVENT THAT MATCHES UP, forget the rest
  354. # find one / match one -logic
  355. # use break-command here!
  356.  
  357. import urllib.request
  358. import json
  359.  
  360. # get internet data
  361. url = 'https://edu.frostbit.fi/api/events/en'
  362. req = urllib.request.Request(url)
  363. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  364.  
  365. # convert the raw JSON (text) into Python data format
  366. data = json.loads(raw_data)
  367.  
  368. # user's search term for category
  369. choice = input("What kind of events are you looking for?\n")
  370.  
  371. # all set, let's loop through our events
  372. for event in data:
  373.     # print the categories also
  374.     categories = ", ".join(event['categories'])
  375.  
  376.     # if the user's choice is not in the categories => SKIP THIS EVENT
  377.     if choice in categories:
  378.         # print the name of the event
  379.         print(event['name'])
  380.  
  381.         # get address info into separate variables
  382.         street_address = event['address']['street_address']
  383.         postal_code = event['address']['postal_code']
  384.  
  385.         # finally print the address info for the user
  386.         print(f"{postal_code} {street_address}")
  387.  
  388.  
  389.         # since we can't trust this data to always have
  390.         # categories, we have catch this situation
  391.         if len(event['categories']) > 0:
  392.             print(f"CATEGORIES: {categories}")
  393.         else:
  394.             print("-- NO CATEGORIES! --")
  395.  
  396.         print()
  397.  
  398.         # since we found the matching event, stop searching ->
  399.         # break stops the loop instead of processing all the data
  400.         # this adds to better performance for your application
  401.         # (imagine having 200k events, and matching event is found on
  402.         # cycle 254)
  403.         break
  404.  
  405. # NEW FILE , exercise 7.5
  406.  
  407. import json
  408. import urllib.request
  409. url = "https://edu.frostbit.fi/api/weather/"
  410. req = urllib.request.Request(url)
  411. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  412. weather = json.loads(raw_data)
  413.  
  414. # you need to find the weakest and strongest winds
  415. # and their respective cities
  416. strongest_wind = 0
  417. strongest_wind_city = ""
  418. weakest_wind = 0
  419. weakest_wind_city = ""
  420.  
  421. for city in weather:
  422.     print(city['location'])
  423.  
  424.     # get also the wind value
  425.     wind = city['wind']
  426.     print(wind)
  427.     print()
  428.    
  429.     # place needed if-statements here to determine
  430.     # strongest and weakest wind
  431.    
  432.     # NOTE! you can check both weakest and strongest
  433.     # winds in the same for -loop, no need for two!
  434.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement