Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 7, collections and loops, 7.11.2024
- print("Welcome!")
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge"]
- # use the raw format of the list printing
- # only to quickly see what is inside
- # in other words, only for debugging purposes
- # this is not the format the end-user / client wants to see
- # print(products)
- # get a single element from the list
- # first index is 0, second is 1 etc.
- # always -1 of what you're seeking
- text = products[2]
- print(text)
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge"]
- # ask the index from the user
- choice = input("Which product do you wish to see?\n")
- choice = int(choice)
- # we can also place a integer variable
- # as the index! notice how we don't have a single conditional
- # statement in this code this is one of the reasons why professionals
- # use collections all the time
- text = products[choice]
- print(text)
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer", "Fridge", "Toothbrush", "Microwave"]
- # ask the index from the user
- choice = input("Which product do you wish to see?\n")
- choice = int(choice)
- # get the amount of products into a variable
- # if you have 4 products, this will be 4
- amount = len(products)
- # let's check if user gave a possible index
- # in other words, 0 - 3 (if we have 4 products)
- # another common way is to use try-except
- if choice >= 0 and choice < amount:
- # get the product the user wants
- text = products[choice]
- print(text)
- else:
- print("No product with given index.")
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer",
- "Fridge", "Toothbrush", "Microwave", "Bookshelf",
- "Oven", "Monitor", "Mouse", "Table"]
- # loop through your products
- for single_product in products:
- print(single_product)
- # NEW FILE, VERSION 2
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer",
- "Fridge", "Toothbrush", "Microwave", "Bookshelf",
- "Oven", "Monitor", "Mouse", "Table"]
- # let's build a text variable in the loop
- text = ""
- # loop through your products
- # you can also do this with ,join() -function
- for p in products:
- text = text + p + ", "
- # show end result
- print(text)
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer",
- "Fridge", "Toothbrush", "Microwave", "Bookshelf",
- "Oven", "Monitor", "Mouse", "Table"]
- # always get the amount of products BEFOREHAND
- # into a variable this is because, most of the
- # programming languages will re-calculate the
- # amount of products on each iteration
- amount = len(products)
- # if you have 11 products,
- # this is the same for x in range(11) etc.
- for index in range(amount):
- product_name = products[index]
- print(f"{index + 1} - {product_name}")
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer",
- "Fridge", "Toothbrush", "Microwave", "Bookshelf",
- "Oven", "Monitor", "Mouse", "Table"]
- # always get the amount of products BEFOREHAND
- # into a variable this is because, most of the
- # programming languages will re-calculate the
- # amount of products on each iteration
- amount = len(products)
- # if you have 11 products,
- # this is the same for x in range(11) etc.
- # don't use len() straight in the range()
- # of the for-loop, (e.g. for index in range(len(products)):)
- # because this way the loop calculates the amount of data
- # after each cycle
- # so if you have 100 products => 100 recalculations
- for index in range(amount):
- product_name = products[index]
- print(f"{index + 1} - {product_name}")
- # NEW FILE
- # let's create a tuple for weekdays
- # remember normal parentheses in tuples
- weekdays = ("Monday", "Tuesday", "Wednesday",
- "Thursday", "Friday", "Saturday", "Sunday")
- # note: you can't change values in a tuple
- # e.g. weekdays[3] = "Someday" will not work
- # if you need to change something, re-create the whole tuple
- # or just use a list instead
- # remember to reduce 1 from the user's input
- # so it matches with the -1 logic of the collection index
- choice = input("Which weekday would you like to know?\n")
- choice = int(choice) - 1
- # print out the user's weekday
- print(weekdays[choice])
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer",
- "Fridge", "Toothbrush", "Microwave", "Bookshelf",
- "Oven", "Monitor", "Mouse", "Table"]
- # let's change the value of 4th product
- products[3] = "Pogo stick"
- # let's quickly see what's inside now
- # we can see now the 4th value
- # is now Pogo stick instead of Fridge
- print(products)
- # NEW FILE
- # create a list of products
- products = ["Washing machine", "Coffee maker", "Freezer",
- "Fridge", "Toothbrush", "Microwave", "Bookshelf",
- "Oven", "Monitor", "Mouse", "Table"]
- # ask the user WHICH product to replace
- choice = input("Which product would you like to change?\n")
- choice = int(choice)
- # new value for the chosen product
- new_product = input("What is the name of the replacement product?\n")
- # replace the product chosen by user
- # with the value given by user
- # remember to use if/else or try/except
- # if the user tries to modify a non-existing index
- products[choice] = new_product
- # let's quickly see what's inside now
- print(products)
- # NEW FILE
- # create a dictionary
- # containing all information regarding this
- # on person in one "variable"
- person = {
- "name": "Test Person",
- "age": 33,
- "city": "Rovaniemi"
- }
- # only print the whole dictionary
- # for testing purposes, because otherwise
- # you might print out sensitive information to the user
- # passwords, session data etc.
- # print(person)
- # print()
- # print the name of the person
- print("Person's name:")
- print(person['name'])
- # print the name of the person
- print("\nPerson's age:")
- print(person['age'])
- # NEW FILE
- products = ["ORDER143_A7685_2024", "ORDER254346564642_A68575465464643643_2023"]
- # don't use substring for splitting down a string like this, use split()
- # since it doesn't matter what length each section has, it always works
- for product in products:
- parts = product.split("_")
- order = parts[0]
- middle = parts[1]
- year = parts[2]
- print(order)
- print(middle)
- print(year)
- print()
- # NEW FILE
- # TRY THIS IN PYTHON TUTOR
- # list of cities
- cities = ["rovaniemi", "oulu", "helsinki", "stockholm", "madrid", "oslo"]
- # make two empty lists to reserve future data
- # one list for long city names, and one for short city names
- long_cities = []
- short_cities = []
- # loop through cities, and SORT THEM into
- # one of the lists above based on their length
- for city in cities:
- if len(city) < 6:
- short_cities.append(city)
- else:
- long_cities.append(city)
- # print the results for both lists
- print(short_cities)
- print(long_cities)
- # NEW FILE
- # combining lists
- foods = ["banana", "apple", "cherry"]
- drinks = ["water", "tea", "coffee"]
- # combine into one list
- everything = foods + drinks
- # print and see content
- print(everything)
- # NEW FILE
- # this is a very good example, why collections are super powerful
- # list of grades
- grades = [2, 5, 4, 3, 5, 4, 3, 2, 4, 5, 1, 3]
- # average = total / amount of data
- total = sum(grades)
- amount = len(grades)
- # calculate the average
- average = total / amount
- average = round(average, 1)
- print(f"Average grade: {average}")
- # NEW FILE
- # list of cities
- cities = ["Rovaniemi", "Helsinki", "Athens", "mikkeli", "Stockholm", "Madrid"]
- print("Original order:")
- print(cities)
- # sort the list
- # cities.sort()
- # sorted() might be more usable, since it doesn't
- # change the original list
- # sorted_cities = sorted(cities)
- # lambda here will transfrom each city name
- # into all CAPITALS, so when comparing
- # they are correctly place into alphabetical order
- # v here is the temporary variable created by lambda
- cities.sort(key=lambda v: v.upper())
- print("\nSorted order:")
- print(cities)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement