tuomasvaltanen

Untitled

Nov 7th, 2023 (edited)
528
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.42 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. # UUSI TIEDOSTO
  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. # place all day data into a single list
  24. # => list of lists
  25. temperatures = [temp_day_1, temp_day_2, temp_day_3]
  26.  
  27. # let's loop through the temperatures
  28. # each day has 4 temperature values
  29. for day in temperatures:
  30.     print("Processing the next day!")
  31.  
  32.     # process each temperature in ONE ACTIVE DAY at a time
  33.     for temp in day:
  34.         print(temp)
  35.  
  36.     print()
  37.  
  38. # NEW FILE, another version of list of lists
  39. # our product categories
  40. books = ["Lord of the Rings", "Da Vinci Code", "Robinson Crusoe"]
  41. movies = ["Interstellar", "Forrest Gump", "Jurassic Park"]
  42.  
  43. # list of lists => all products splitted by categories
  44. products = [books, movies]
  45.  
  46. # since products is a list of lists
  47. # we need a for -loop with a for-loop
  48. for category in products:
  49.    
  50.     # for each item in this category:
  51.     for item in category:
  52.         print(item)
  53.  
  54. # NEW FILE
  55.  
  56. # dictionary inside another dictionary
  57. book = {
  58.     "name":  "My Lady Jane",
  59.     "year":  2016,
  60.     "publisher": {
  61.         "name": "HarperTeen",
  62.         "organization": "HarperCollins Publishers",
  63.         "location": "New York"
  64.     }
  65. }
  66.  
  67. # just printing the book with Python is not very readable
  68. # ok for debugging purposes
  69. # print(book)
  70.  
  71. # getting the name of the book is straight-forward
  72. print(book['name'])
  73.  
  74. # this is usually not enough, since publisher
  75. # is it's own dictionary
  76. # print(book['publisher'])
  77.  
  78. # let's save the publisher dictionary in its own variable
  79. publisher = book['publisher']
  80. print(publisher['location'])
  81.  
  82. # one-liner solutions are super common too:
  83. print(book['publisher']['location'])
  84.  
  85. # NEW FILE
  86.  
  87. # example, list inside a dictionary
  88. book = {
  89.     "name":  "My Lady Jane",
  90.     "year":  2016,
  91.     "authors": ["Cynthia Hand", "Brodi Ashton", "Jodi Meadows"]
  92. }
  93.  
  94. # get the first author
  95. # print(book['authors'][0])
  96.  
  97. for author in book['authors']:
  98.     print(author)
  99.  
  100. # NEW FILE
  101.  
  102. # list of dictionaries, the most common combination
  103. products = [
  104.     {"name": "Coffee maker", "price": 79},
  105.     {"name": "Dishwasher", "price": 299},
  106.     {"name": "Freezer", "price": 199},
  107. ]
  108.  
  109. # products is a list of dictionaries
  110. # => we need a loop => for each product (p) in products-list
  111. for p in products:
  112.     name = p['name']
  113.     price = p['price']
  114.  
  115.     print(f"{name} - {price} €")
  116.  
  117. print("All done!")
  118. print()
  119.  
  120. # you can still access by index, for example first product
  121. first_product = products[0]
  122. print(first_product['name'])
  123.  
  124. # NEW FILE
  125.  
  126. # remember to install var_dump first
  127. # see the materials 3.5 for instructions
  128. import var_dump as vd
  129.  
  130. # create first hotel
  131. hotel_1 = {
  132.  "name": "Snow Line Hotels",
  133.  "rating": 4.3,
  134.  "wifi": True,
  135.  "free_breakfast": True,
  136.  "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
  137.  "price_level": 4
  138. }
  139.  
  140. # create second hotel
  141. hotel_2 = {
  142.  "name": "North Ice Hostel",
  143.  "rating": 3.5,
  144.  "wifi": True,
  145.  "free_breakfast": False,
  146.  "services": ["sauna", "parking"],
  147.  "price_level": 2
  148. }
  149.  
  150. # place both hotels into one list
  151. hotels = [hotel_1, hotel_2]
  152.  
  153. #print(hotels)
  154. #print()
  155. #vd.var_dump(hotels)
  156.  
  157. # sometimes it's easier to inspect only the first element
  158. #first_hotel = hotels[0]
  159. #vd.var_dump(first_hotel)
  160.  
  161. for hotel in hotels:
  162.     # print the name of the hotel
  163.     print(hotel['name'])
  164.  
  165.     # traditional way: just loop through the service list
  166.     # because hotel services is a list, we can just loop:
  167.     # for service in hotel['services']:
  168.     #    print(service)
  169.  
  170.     # a nice trick that works with a list of strings (doesn't work
  171.     # with complex lists though)
  172.     services = ", ".join(hotel['services'])
  173.     print(services)
  174.  
  175.     print()
  176.  
  177. # NEW VERSION
  178.  
  179. import var_dump as vd
  180.  
  181. # create first hotel
  182. hotel_1 = {
  183.  "name": "Snow Line Hotels",
  184.  "rating": 4.3,
  185.  "wifi": True,
  186.  "free_breakfast": True,
  187.  "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
  188.  "price_level": 4
  189. }
  190.  
  191. # create second hotel
  192. hotel_2 = {
  193.  "name": "North Ice Hostel",
  194.  "rating": 3.5,
  195.  "wifi": True,
  196.  "free_breakfast": False,
  197.  "services": ["sauna", "parking"],
  198.  "price_level": 2
  199. }
  200.  
  201. # place both hotels into one list
  202. hotels = [hotel_1, hotel_2]
  203.  
  204. # loop through all hotels
  205. for hotel in hotels:
  206.     # print the name of the hotel
  207.     print(hotel['name'])
  208.  
  209.     # traditional way: loop through services and use if
  210.     # for service in hotel['services']:
  211.     #    if service == "restaurant":
  212.     #        print("This hotel has a restaurant.")
  213.  
  214.     # since services is just a list of strings
  215.     # we can use this approach too:
  216.     if "restaurant" in hotel['services']:
  217.         print("This hotel has a restaurant.")
  218.  
  219.     print()
  220.  
  221. # NEW VERSION
  222.  
  223. import var_dump as vd
  224.  
  225. # create first hotel
  226. hotel_1 = {
  227.  "name": "Snow Line Hotels",
  228.  "rating": 4.3,
  229.  "wifi": True,
  230.  "free_breakfast": True,
  231.  "services": ["sauna", "meetings", "restaurant", "parking", "safaris"],
  232.  "price_level": 4
  233. }
  234.  
  235. # create second hotel
  236. hotel_2 = {
  237.  "name": "North Ice Hostel",
  238.  "rating": 3.5,
  239.  "wifi": True,
  240.  "free_breakfast": False,
  241.  "services": ["sauna", "parking"],
  242.  "price_level": 2
  243. }
  244.  
  245. # place both hotels into one list
  246. hotels = [hotel_1, hotel_2]
  247.  
  248. # empty list in the beginning
  249. # to be filled with hotel names, that contain sauna
  250. sauna_hotels = []
  251.  
  252. # loop through all hotels
  253. for hotel in hotels:
  254.     # print the name of the hotel
  255.     print(hotel['name'])
  256.  
  257.     # filtering hotels into a separate list
  258.     # could be used somewhere else
  259.     if "sauna" in hotel['services']:
  260.         sauna_hotels.append(hotel['name'])
  261.  
  262.     print()
  263.  
  264.    
  265. print(sauna_hotels)
  266.  
  267. # NEW FILE, EVENT DATA
  268.  
  269. import urllib.request
  270. import json
  271.  
  272. # this module needs to be installed separately
  273. # in PyCharm you can install the package if its not found!
  274. import var_dump as vd
  275.  
  276. # get internet data
  277. url = 'https://edu.frostbit.fi/api/events/en'
  278. req = urllib.request.Request(url)
  279. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  280.  
  281. # the needed data from internet is now in the "data" -variable!
  282. data = json.loads(raw_data)
  283. #vd.var_dump(data)
  284.  
  285. # if you want to inspect only the first one:
  286. #test_event = data[0]
  287. #vd.var_dump(test_event)
  288.  
  289. # data is a list of dictionaries (as implied by var_dump)
  290. # loop through each event (exact amount varies every day)
  291. for event in data:
  292.     print(event['name'])
  293.  
  294. # NEW VERSION
  295.  
  296. import urllib.request
  297. import json
  298.  
  299. # this module needs to be installed separately
  300. # in PyCharm you can install the package if its not found!
  301. import var_dump as vd
  302.  
  303. # get internet data
  304. url = 'https://edu.frostbit.fi/api/events/en'
  305. req = urllib.request.Request(url)
  306. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  307.  
  308. # the needed data from internet is now in the "data" -variable!
  309. data = json.loads(raw_data)
  310. #vd.var_dump(data)
  311.  
  312. # if you want to inspect only the first one:
  313. #test_event = data[0]
  314. #vd.var_dump(test_event)
  315.  
  316. # data is a list of dictionaries (as implied by var_dump)
  317. # loop through each event (exact amount varies every day)
  318. for event in data:
  319.     print(event['name'])
  320.  
  321.     # if we have to take care that address exists before getting postal code:
  322.     # we have do something like this:
  323.     #if "address" in event:
  324.     #    postal_code = event['address']['postal_code']
  325.  
  326.     # if you want to skip the whole event, because of missing data:
  327.     #if "address" not in event:
  328.     #    continue
  329.  
  330.     # get the address information from the dictionary "address"
  331.     street_address = event['address']['street_address']
  332.     postal_code = event['address']['postal_code']
  333.  
  334.     # print address info
  335.     print(f"{postal_code} {street_address}")
  336.  
  337.     # combine categories into one string
  338.     categories = ", ".join(event['categories'])
  339.  
  340.     # only print categories if there are categories
  341.     # otherwise, inform the user
  342.     if categories != "":
  343.         print(categories)
  344.     else:
  345.         print("-- NO CATEGORIES --")
  346.  
  347.     print()
  348.  
  349. # NEW VERSION, A SIMPLE SEARCH FEATURE -> USER CAN SELECT A CATEGORY
  350. # ONLY SHOW THOSE EVENTS THAT MATCH THE CATEGORY
  351.  
  352. import urllib.request
  353. import json
  354.  
  355. # this module needs to be installed separately
  356. # in PyCharm you can install the package if its not found!
  357. import var_dump as vd
  358.  
  359. # get internet data
  360. url = 'https://edu.frostbit.fi/api/events/en'
  361. req = urllib.request.Request(url)
  362. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  363.  
  364. # the needed data from internet is now in the "data" -variable!
  365. data = json.loads(raw_data)
  366. #vd.var_dump(data)
  367.  
  368. # if you want to inspect only the first one:
  369. # test_event = data[0]
  370. # vd.var_dump(test_event)
  371.  
  372. # ask the user what kind of events they are looking for
  373. choice = input("Which event category are your searching for?\n")
  374.  
  375. # data is a list of dictionaries (as implied by var_dump)
  376. # loop through each event (exact amount varies every day)
  377. for event in data:
  378.  
  379.     # combine categories into one string
  380.     categories = ", ".join(event['categories'])
  381.  
  382.     # if the user's choice is not in categories -> skip this event
  383.     if choice not in categories:
  384.         continue
  385.  
  386.     print(event['name'])
  387.  
  388.     # get the address information from the dictionary "address"
  389.     street_address = event['address']['street_address']
  390.     postal_code = event['address']['postal_code']
  391.  
  392.     # print address info
  393.     print(f"{postal_code} {street_address}")
  394.  
  395.     # only print categories if there are categories
  396.     # otherwise, inform the user
  397.     if categories != "":
  398.         print(categories)
  399.     else:
  400.         print("-- NO CATEGORIES --")
  401.  
  402.     print()
  403.  
  404. # NEW VERSION, only look for the FIRST ENTRY that matches in the data
  405.  
  406. import urllib.request
  407. import json
  408.  
  409. # this module needs to be installed separately
  410. # in PyCharm you can install the package if its not found!
  411. import var_dump as vd
  412.  
  413. # get internet data
  414. url = 'https://edu.frostbit.fi/api/events/en'
  415. req = urllib.request.Request(url)
  416. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  417.  
  418. # the needed data from internet is now in the "data" -variable!
  419. data = json.loads(raw_data)
  420. #vd.var_dump(data)
  421.  
  422. # if you want to inspect only the first one:
  423. # test_event = data[0]
  424. # vd.var_dump(test_event)
  425.  
  426. # ask the user what kind of events they are looking for
  427. # only show the first match in data
  428. choice = input("Which event category are your searching for?\n")
  429.  
  430. # data is a list of dictionaries (as implied by var_dump)
  431. # loop through each event (exact amount varies every day)
  432. for event in data:
  433.  
  434.     # combine categories into one string
  435.     categories = ", ".join(event['categories'])
  436.  
  437.     # if user's choice is in the categories
  438.     if choice in categories:
  439.         print(event['name'])
  440.  
  441.         # get the address information from the dictionary "address"
  442.         street_address = event['address']['street_address']
  443.         postal_code = event['address']['postal_code']
  444.  
  445.         # print address info
  446.         print(f"{postal_code} {street_address}")
  447.  
  448.         # only print categories if there are categories
  449.         # otherwise, inform the user
  450.         if categories != "":
  451.             print(categories)
  452.         else:
  453.             print("-- NO CATEGORIES --")
  454.  
  455.         print()
  456.         break
  457.  
  458. # NEW FILE
  459.  
  460. import json
  461. import urllib.request
  462. url = "https://edu.frostbit.fi/api/weather/"
  463. req = urllib.request.Request(url)
  464. raw_data = urllib.request.urlopen(req).read().decode("UTF-8")
  465. weather = json.loads(raw_data)
  466.  
  467. # initialize variables needed in the loop
  468. strongest_wind = 0
  469. strongest_wind_city = ""
  470. weakest_wind = 0
  471. weakest_wind_city = ""
  472.  
  473. # because weather is a list of dictionaries:
  474. # remember: you only need one loop to process both weakest and strongest wind
  475. for city in weather:
  476.     print(city['location'])
  477.     print(city['wind'])
  478.     # if current city wind is bigger than previous wind (strongest_wind)
  479.     # set the current wind as the strongest_wind
  480.     # also save down the name of the city (strongest_wind_city)
  481.  
  482.     print()
Add Comment
Please, Sign In to add comment