Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 6, collections!
- print("Welcome!")
- # NEW FILE
- # a list of 4 products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge"]
- # access the second element
- # first index starts from zero!
- p = products[1]
- # print it out
- print(p)
- # NEW FILE
- # a list of 4 products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge"]
- # ask the index from the user
- choice = input("Which product do you want to see?\n")
- choice = int(choice)
- # get the product with given index
- p = products[choice]
- print(p)
- # NEW FILE
- # a list of 4 products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge", "Oven"]
- # ask the index from the user
- choice = input("Which product do you want to see?\n")
- choice = int(choice)
- # get the amount of elements in the list (products)
- amount = len(products)
- # the given index has to be between 0 and amount of products
- if choice < amount and choice >= 0:
- # get the product with given index
- p = products[choice]
- print(p)
- else:
- print("That product does not exist! (bad index)")
- # NEW FILE
- # a list of 4 products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge", "Oven"]
- # loop through the items in list
- for p in products:
- print(p)
- # try also:
- # print(f"Product name: {p}")
- # NEW FILE
- # a list of 5 products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge", "Oven", "Clock"]
- amount = len(products)
- # loop through products and print a numbered list
- # index contains the index number
- # p contains the actual product
- for index in range(amount):
- p = products[index]
- print(f"{index + 1}. {p}")
- # NEW FILE
- # tuple uses normal parentheses
- weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
- # ask the number from user
- choice = input("Which weekday?\n")
- # collections start at 0, but user might
- # want to user the actual numbers, therefore - 1
- # for example, if user gives 3, we transform it to 2,
- # which is then, Wednesday
- choice = int(choice) - 1
- # print out the required weekday
- print(weekdays[choice])
- # NEW FILE
- # a list of 5 products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge", "Oven", "Clock"]
- # change the 3rd element to Television
- products[2] = "Television"
- # let's quickly see if this worked:
- # print(products)
- # ask user the index that we want to change
- choice = input("Which product do you want to change?\n")
- choice = int(choice)
- # ask user what is the replacement value
- new_product = input("What is the new product?\n")
- # change the actual product
- products[choice] = new_product
- # test quickly what is inside the list now
- # use print(products) only for testing, for final
- # code, always use indexes or print in a loop
- print(products)
- # NEW FILE
- # person-dictionary, consists of 3 different data: name, age and city
- person = {
- "name": "John Doe",
- "age": 33,
- "city": "Rovaniemi"
- }
- # print out only the person name
- print("Person name:")
- print(person["name"])
- print()
- # print out only the person age
- age = person['age']
- print("Person age:")
- print(f"{age} years old.")
- # NEW FILE
- day_1 = [0.5, 1.4, 2.5, 3.4]
- day_2 = [1.2, 1.1, 2.8, 3.9]
- day_3 = [0.2, 2.4, 1.1, 0.7]
- # list of lists, contains three days
- # each day contains 4 temperatures
- temperatures = [day_1, day_2, day_3]
- # loop through all days in list (3 days in total)
- for day in temperatures:
- print("\nNew day!")
- # loop through all temperatures in one day (4 temperatures in total)
- for t in day:
- print(t)
- print("All done!")
- # NEW FILE
- # try this version in Python Tutor to see what happens in the background!
- temperatures = [[0.5, 1.4, 2.5, 3.4], [1.2, 1.1, 2.8, 3.9], [0.2, 2.4, 1.1, 0.7]]
- # loop through all days in list (3 days in total)
- for day in temperatures:
- print("\nNew day!")
- # loop through all temperatures in one day (4 temperatures in total)
- for t in day:
- print(t)
- print("All done!")
- # NEW FILE
- book = {
- "name": "My Lady Jane",
- "year": 2016,
- "publisher": {
- "name": "HarperTeen",
- "organization": "HarperCollins Publishers",
- "location": "New York"
- }
- }
- # name and year are simple, just get the data
- name = book['name']
- print(name)
- year = book['year']
- print(year)
- # publisher is another dictionary, so we need to access it with chained
- # accessors
- # approach 1, use helper variables
- publisher = book["publisher"]
- publisher_location = publisher['location']
- print(publisher_location)
- # approach 2, get the directly
- publisher_location = book['publisher']['location']
- print(publisher_location)
- # NEW FILE
- text = "HOTEL"
- # a string is basically a list of characters in certain order!
- for character in text:
- print(character)
- # NEW FILE
- # try replacing text with "ORDER1412332_C156786_2022"
- # you'll notice the substring logic will break!
- text = "ORDER1432_C1786_2022"
- # get the pieces of order!
- order = text[0:9]
- print(order)
- customer = text[10:15]
- print(customer)
- year = text[-4:]
- print(year)
- # NEW FILE, BETTER WAY, USE SPLIT
- # try replacing text with "ORDER1412332_C156786_2022"
- # you'll notice the substring logic will break!
- text = "ORDER1423132_C17123286_2022"
- # remember, parts is a LIST of three elements
- # by using split(), it doesn't matter how long
- # different parts are! this works always!
- parts = text.split("_")
- # first part is the order code
- order = parts[0]
- print(order)
- # second part is the client id
- customer = parts[1]
- print(customer)
- # third part is the year
- year = parts[2]
- print(year)
- # NEW FILE
- # TRY THIS EXAMPLE IN PYTHON TUTOR!
- cities = ["rovaniemi", "oulu", "helsinki", "stockholm", "madrid", "london", "amsterdam"]
- # initialize two empty lists
- short_city_names = []
- long_city_names = []
- # loop through all cities
- for city in cities:
- # if city name is longer than 6 letters => add it to long city names
- if len(city) > 6:
- long_city_names.append(city)
- else:
- # otherwise add it to short city names
- short_city_names.append(city)
- # let's see what's inside now
- print(long_city_names)
- print(short_city_names)
- # NEW FILE
- cities = ["oulu", "helsinki", "stockholm", "rovaniemi", "madrid", "london", "amsterdam"]
- # loop through all cities
- for city in cities:
- # when the first long city name is found, break out of loop
- if len(city) > 8:
- print("The first long city name we found, was:")
- print(city)
- break
- # NEW FILE
- cities = ["oulu", "helsinki", "stockholm", "rovaniemi", "madrid", "london", "amsterdam"]
- # loop through all cities
- for city in cities:
- # if the city name is long, skip the cycle
- if len(city) > 8:
- continue
- print(city)
- # NEW FILE
- # combining lists is very easy in Python
- foods = ["banana", "apple", "cherry"]
- drinks = ["water", "tea", "coffee"]
- everything = foods + drinks
- print(everything)
- # NEW FILE
- grades = [1, 3, 5, 4, 3, 4, 3, 2, 5, 5, 4, 3, 5, 5, 5, 5, 5]
- # get the total sum and amount of values
- total = sum(grades)
- amount = len(grades)
- # average => total sum of values / number of values
- # if you use lists, you can do neat tricks like this:
- average = total / amount
- average = round(average, 1)
- print(average)
- # NEW FILE
- cities = ["Rovaniemi", "Helsinki", "Athens", "mikkeli", "Stockholm", "Madrid"]
- # note, sort(), you don't assign a variable
- cities.sort()
- # create a new version of the list, sorted()
- # sorted also works tuples and dictionaries
- cities = sorted(cities)
- # if you also want to take account lower and capital letters
- cities.sort(key=lambda v: v.upper())
- print(cities)
Advertisement
Add Comment
Please, Sign In to add comment