diff --git a/homework/homework04/results/autoloan02.py b/homework/homework04/results/autoloan02.py new file mode 100644 index 0000000..743fc6c --- /dev/null +++ b/homework/homework04/results/autoloan02.py @@ -0,0 +1,50 @@ + +''' +Auto Loan Payment Calculations +============================== + +https://www.wikihow.com/Calculate-Auto-Loan-Payments + Use the formula A = P ∗ ( r ( 1 + r ) n ) / ( ( 1 + r ) n − 1 ) + + A = the monthly payment. + P = the principal + r = the interest rate per month, which equals the annual interest rate divided by 12 + n = the total number of months + +Mass Sales Tax +============== + +The .0625 (6.25%) sales tax is paid in the first year only. + +https://www.mass.gov/guides/motor-vehicle-and-trailer-sales-and-use-tax + +Mass Excise Tax Fees +==================== + +The tax depends on the vehicle age. For this program we only calculate the +excise tax on the first year of purchase. +https://www.sec.state.ma.us/divisions/cis/tax/motor-excise.htm + +''' + +# ======================= Input Variables ================================== +principal = 15090. +rate = .07 +numberOfYears = 4 +# =========================================================================== + +rate = rate /100 +ratePerMonth = rate /12 +numberOfMonths = numberOfYears * 12 +salesTax = principal * .0625 # Mass sales tax rate +# https://www.sec.state.ma.us/divisions/cis/tax/motor-excise.htm +exciseTax = principal / 1000 * .9 * 25.00 + +monthlyPayment = principal * (ratePerMonth * (1+ratePerMonth)**(numberOfMonths))/((1+ratePerMonth)**(numberOfMonths)-1) + +print("The payment is ", monthlyPayment) +print(f"The payment is ${monthlyPayment:.2f}") +print("The sales tax is ", salesTax) +print("The excise tax is ", exciseTax) + +print("First years expense is ", monthlyPayment*12 + salesTax + exciseTax) diff --git a/lecture20261103/for01/for06.py b/lecture20261103/for01/for06.py index ae343fe..51d035e 100644 --- a/lecture20261103/for01/for06.py +++ b/lecture20261103/for01/for06.py @@ -1,6 +1,7 @@ # https://www.programiz.com/python-programming/for-loop -scores = [70, 91, 85, 90, 100] +scores = [70, 91, 85, 90, 100,67.3] +#scores = [100,100,100,100, 100] print(f"The length of this list of scores is {len(scores)}") @@ -10,3 +11,4 @@ for i in scores: scoreSum += i else: print("The average is ",scoreSum/len(scores)) + print(f"The average is {scoreSum/len(scores):.1f}") diff --git a/lecture20261110/DictionariesAndTry/dictionary0.py b/lecture20261110/DictionariesAndTry/dictionary0.py new file mode 100644 index 0000000..dd8d88f --- /dev/null +++ b/lecture20261110/DictionariesAndTry/dictionary0.py @@ -0,0 +1,21 @@ + + +nameList = ["John", "Smith"] +nameDictionary = {'firstName': "John", 'lastName': "Smith", 'age': 24} +nameDictionary1 = {'firstName': "Mary", 'lastName': "Smith"} + +namesList = [nameDictionary,nameDictionary1] + +print(nameList) +print(nameDictionary) +print(namesList) + +print(nameDictionary['firstName']) +print(nameDictionary['lastName']) +print(nameDictionary['age']) + +print(nameDictionary1['firstName']) +print(nameDictionary1['lastName']) + +# Uncomment this and it generates an error +#print(nameDictionary1['age']) diff --git a/lecture20261110/DictionariesAndTry/dictionary1.py b/lecture20261110/DictionariesAndTry/dictionary1.py new file mode 100644 index 0000000..b6da735 --- /dev/null +++ b/lecture20261110/DictionariesAndTry/dictionary1.py @@ -0,0 +1,17 @@ +#!/usr/bin/python + +#Tutorialspoint +# https://www.tutorialspoint.com/python/python_dictionary.htm +# Accessing Values in Dictionary +import pprint + + +person = {'Name': 'Zara', 'Age': 7, 'Class': 'First','Color':'Green','Phone': "413-781-7822",'Email': "bgates@microsoft.com"} + +pp = pprint.PrettyPrinter(indent=4) +pp.pprint(person) +print("\n") + +print("person['Name']: ", person['Name']) +print ("person['Age']: ", person['Age']) + diff --git a/lecture20261110/DictionariesAndTry/dictionary2.py b/lecture20261110/DictionariesAndTry/dictionary2.py new file mode 100644 index 0000000..67f9210 --- /dev/null +++ b/lecture20261110/DictionariesAndTry/dictionary2.py @@ -0,0 +1,21 @@ +#!/usr/bin/python +# An office directory example + +dict = {'fName': 'Robert', 'lName': 'Smith', 'Office': 620, 'Phone': '413-755-0000',"Email": "rsmith@example.com"} + +print("dict['fName'] dict['lName']: ", dict['fName']," ", dict['lName']) +print ("dict['Office']: ", dict['Office']) +print ("dict['Phone']: ", dict['Phone']) + +#Uncomment this next line and the program fails +#print ("dict['Mobile']: ", dict['Mobile']) + +try: + print("dict['fName'] dict['lName']: ", dict['fName']," ", dict['lName']) + print ("dict['Office']: ", dict['Office']) + print ("dict['Phone']: ", dict['Phone']) + print ("dict['Mobile']: ", dict['Mobile']) +except: + print("We are in the except block") + + diff --git a/lecture20261110/DictionariesAndTry/dictionary3.py b/lecture20261110/DictionariesAndTry/dictionary3.py new file mode 100644 index 0000000..cce449c --- /dev/null +++ b/lecture20261110/DictionariesAndTry/dictionary3.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# A directory example + +dict = {'fName': 'Edward', 'lName': 'Bigos', 'Office': 617, 'Phone': '413-755-4544'} + + +try: + print("dict['fName'] dict['lName']: ", dict['fName']," ", dict['lName']) + print ("dict['Office']: ", dict['Office']) + print ("dict['Phone']: ", dict['Phone']) + print ("dict['Mobile']: ", dict['Mobile']) +except KeyError: + print("\nInvalid key selected.") + print("Sorry, there is no mobile phone number in the directory.") + print("\n") diff --git a/lecture20261110/DictionariesAndTry/dictionary3a.py b/lecture20261110/DictionariesAndTry/dictionary3a.py new file mode 100644 index 0000000..e158e6b --- /dev/null +++ b/lecture20261110/DictionariesAndTry/dictionary3a.py @@ -0,0 +1,14 @@ +#!/usr/bin/python +# A directory example + +dict = {'fName': 'Edward', 'lName': 'Bigos', 'Office': 617, 'Phone': '413-755-4544'} +try: + print("dict['fName'] dict['lName']: ", dict['fName']," ", dict['lName']) + print ("dict['Office']: ", dict['Office']) + print ("dict['Phone']: ", dict['Phone']) +# print ("dict['Mobile']: ", dict['Mobile']) +except KeyError: + print("Invalid key selected.") + print("Sorry, there is no key with that name in the directory.") + print("\n") + diff --git a/lecture20261110/DictionariesAndTry/dictionary4.py b/lecture20261110/DictionariesAndTry/dictionary4.py new file mode 100644 index 0000000..c2fd2cf --- /dev/null +++ b/lecture20261110/DictionariesAndTry/dictionary4.py @@ -0,0 +1,25 @@ +#!/usr/bin/python + +# Create three dictionaries +dict1 = {'fName': 'Edward', 'lName': 'Bigos', 'Office': 617, 'Phone': '413-755-4544'} +dict2 = {'fName': 'Bill', 'lName': 'Gates', 'Office': 700, } +dict3 = {'fName': 'Harry', 'lName': 'Smith', 'Office': 677, 'Phone': '413-000-0000'} + +# Put the three dictionaries in a list +staff = [dict1,dict2, dict3] + +print(staff) +print("\n") + +print("=============================\n\t\tDirectory\n=============================") + +for person in staff: +# Person is a dictionary. Uncomment the next line to print the type. + #print(person, type(person)) + try: + print(person['lName'], person['fName'], person['Phone']) + except: + print(person['lName'], person['fName']) + + + diff --git a/lecture20261110/DictionariesAndTry/weather-data01.py b/lecture20261110/DictionariesAndTry/weather-data01.py new file mode 100644 index 0000000..45dc805 --- /dev/null +++ b/lecture20261110/DictionariesAndTry/weather-data01.py @@ -0,0 +1,23 @@ + +import pprint + +weatherData = {'coord': {'lon': -72.5949, 'lat': 42.1726}, + 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02n'}], + 'base': 'stations', + 'main': {'temp': 285.11, 'feels_like': 283.25, 'temp_min': 282.18, 'temp_max': 286.21, + 'pressure': 1015, 'humidity': 34}, + 'visibility': 10000, + 'wind': {'speed': 3.6, 'deg': 160}, + 'clouds': {'all': 20}, + 'dt': 1649723543, + 'sys': {'type': 1, 'id': 3598, 'country': 'US', 'sunrise': 1649672158, + 'sunset': 1649719584}, + 'timezone': -14400, + 'id': 4933002, + 'name': 'Chicopee', + 'cod': 200} + +pp = pprint.PrettyPrinter(indent=4) + +pp.pprint(weatherData) + diff --git a/lecture20261110/DictionariesAndTry/weather-data02.py b/lecture20261110/DictionariesAndTry/weather-data02.py new file mode 100644 index 0000000..cb38f43 --- /dev/null +++ b/lecture20261110/DictionariesAndTry/weather-data02.py @@ -0,0 +1,31 @@ + +import pprint + +weatherData = {'coord': {'lon': -72.5949, 'lat': 42.1726}, + 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02n'}], + 'base': 'stations', + 'main': {'temp': 285.11, 'feels_like': 283.25, 'temp_min': 282.18, 'temp_max': 286.21, + 'pressure': 1015, 'humidity': 34}, + 'visibility': 10000, + 'wind': {'speed': 3.6, 'deg': 160}, + 'clouds': {'all': 20}, + 'dt': 1649723543, + 'sys': {'type': 1, 'id': 3598, 'country': 'US', 'sunrise': 1649672158, + 'sunset': 1649719584}, + 'timezone': -14400, + 'id': 4933002, + 'name': 'Chicopee', + 'cod': 200} + +#pp = pprint.PrettyPrinter(indent=4) + +#pp.pprint(weatherData) + +#print("\n") + +print("coord",weatherData['coord']) +print("weather: ",weatherData['weather']) +print("base: ",weatherData['base']) +print("main: ",weatherData['main']) +print("wind: ",weatherData['wind']) + diff --git a/lecture20261110/DictionariesAndTry/weather-data03.py b/lecture20261110/DictionariesAndTry/weather-data03.py new file mode 100644 index 0000000..7ba1b80 --- /dev/null +++ b/lecture20261110/DictionariesAndTry/weather-data03.py @@ -0,0 +1,24 @@ + +import pprint + +weatherData = {'coord': {'lon': -72.5949, 'lat': 42.1726}, + 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02n'}], + 'base': 'stations', + 'main': {'temp': 285.11, 'feels_like': 283.25, 'temp_min': 282.18, 'temp_max': 286.21, + 'pressure': 1015, 'humidity': 34}, + 'visibility': 10000, + 'wind': {'speed': 3.6, 'deg': 160}, + 'clouds': {'all': 20}, + 'dt': 1649723543, + 'sys': {'type': 1, 'id': 3598, 'country': 'US', 'sunrise': 1649672158, + 'sunset': 1649719584}, + 'timezone': -14400, + 'id': 4933002, + 'name': 'Chicopee', + 'cod': 200} + + +print("\n\n======== Keys ===============") +for key in weatherData.keys(): + print(key) + diff --git a/lecture20261110/DictionariesAndTry/weather-data04.py b/lecture20261110/DictionariesAndTry/weather-data04.py new file mode 100644 index 0000000..9d46783 --- /dev/null +++ b/lecture20261110/DictionariesAndTry/weather-data04.py @@ -0,0 +1,25 @@ + +import pprint + +weatherData = {'coord': {'lon': -72.5949, 'lat': 42.1726}, + 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02n'}], + 'base': 'stations', + 'main': {'temp': 285.11, 'feels_like': 283.25, 'temp_min': 282.18, 'temp_max': 286.21, + 'pressure': 1015, 'humidity': 34}, + 'visibility': 10000, + 'wind': {'speed': 3.6, 'deg': 160}, + 'clouds': {'all': 20}, + 'dt': 1649723543, + 'sys': {'type': 1, 'id': 3598, 'country': 'US', 'sunrise': 1649672158, + 'sunset': 1649719584}, + 'timezone': -14400, + 'id': 4933002, + 'name': 'Chicopee', + 'cod': 200} + + +print("\n\n======== Keys and Data ===============") +for key in weatherData.keys(): + print(f" {key:12} {weatherData[key]} ") + + diff --git a/lecture20261110/List-Intro_0001.py b/lecture20261110/List-Intro_0001.py new file mode 100644 index 0000000..eeabcc7 --- /dev/null +++ b/lecture20261110/List-Intro_0001.py @@ -0,0 +1,56 @@ +# List-Intro_0001.py +# +# A Python List is a type of variable which may contain +# zero or more values (could be numbers, strings, etc.) +# in an ordered manner. Each value can be accessed using +# an index. Here are some examples of python list variables: +# +myList1 = [] # an empty list +myList2 = [16, 8, 4, 2, 1] # a typical list +myList3 = ["Boston", 23.5, "Pantera", "Los Lobos"] +myList4 = [1, 10, 100, 1000, 10000, 100000, 1000000] +myList5 = [5, 6, myList4, 8, 10] +myList6 = ["item0", "item1", "item2", "item3", "item4"] + +print(myList1, "\n", myList2, "\n", myList3, "\n", myList4, "\n", myList5, "\n", myList6) + +# Finding the length of a list len(list variable name): +print("Length of myList1 = ", len(myList1)) +print("Length of myList3 = ", len(myList3)) +print("Length of myList4 = ", len(myList4)) +print("Length of myList6 = ", len(myList6)) + +# List indices begin at 0 and end with len(list variable name) - 1 +print(myList4[0], "\n", myList4[3], "\n", myList6[4]) + +# Grabbing more than one list item is called slicing: +print(myList2[0], "\n", myList4[2:5], "\n", myList4[3:]) +print(myList6[-3:]) + +print("Adding and removing list items ...") +# How does one add or remove items from a list? +# append() Adds an item to the end of the list: +print(len(myList2), " : ", myList2) +myList2.append(0) +print(len(myList2), " : ", myList2) + +# insert() Adds an item at a specific index +print(len(myList3), " : ", myList3) +myList3.insert(2, "Jeff Beck") +print(len(myList3), " : ", myList3) + +print("Other list operations include: extend(), remove(), pop(), & del()") + +print("You can also sort lists") +# You can also sort lists: +print(myList2) +myList2.sort() +print(myList2) +myList2.sort(reverse = True) +print(myList2) + +print("Indexing a list of lists ...") +# You can have multi-dimensional lists (i.e. list of lists): +print(myList5) +print(myList5[2]) +print(myList5[2][5]) diff --git a/lecture20261110/Tuples-Intro_0001.py b/lecture20261110/Tuples-Intro_0001.py new file mode 100644 index 0000000..74ae76c --- /dev/null +++ b/lecture20261110/Tuples-Intro_0001.py @@ -0,0 +1,52 @@ +# CSE-160-D01_2024FA_Intro-to-Python-Tuples +# ----------------------------------------- +# Tuple-Intro_0001.py +# +# A tuple is type of Python variable that can hold an ordered collection +# of multiple values of possibly differing data type, possibly duplicated +# values and are used for information that should not be changed. +# +# We have talked about Python list variables. Tuples have some +# similarities to Python lists. +# lists and tuples similarities: +# both are ordered collections of multiple values +# both can contain multiple data types (e.g. integers, floats, strings, etc.) +# both can contain duplicate values +# length of both can be determined using the len() function +# lists and tuples differences: +# tuples are described using parentheses +# tuples are "immutable" (i.e. they can't be changed) +# +# What are tuples used for in Python? +# Do a Google (or other fine) search on the exact question in the line above. +# +############################################################################################# +# +# Example tuples: +# Latitude and Longitude of STCC Building 19: +STCC_Bldg19_Loc = (42.10998017567259, -72.58147247672) +# Atomic symbol, atomic number, and atomic weight of aluminum: +aluminumData = ("Al", 13, 26.982) +# A single item tuple is described like so: +avgDiameterOfEarthInMiles = (7926,) +# +lockCombination = ("right24", "left31", "right10") +# +print("STCC_Bldg19_Loc = ", STCC_Bldg19_Loc) +print("STCC_Bldg19_Loc type and length: ", type(STCC_Bldg19_Loc), len(STCC_Bldg19_Loc), "\n") +print("aluminumData = ", aluminumData) +print("aluminumData type and length: ", type(aluminumData), len(aluminumData), "\n") +print("avgDiameterOfEarthInMiles: ", avgDiameterOfEarthInMiles) +print("avgDiameterOfEarthInMiles type and length: ", type(avgDiameterOfEarthInMiles), len(avgDiameterOfEarthInMiles), "\n") +print("lockCombination = ", lockCombination) +print("lockCombination type and length: ", type(lockCombination), len(lockCombination)) +print() +# +############################################################################################# +# +# Tuples are indexed just like list variables (yeah, they even used square brackets on the indices): +print("STCC Blg 19 Latitude = ", STCC_Bldg19_Loc[0]) +print("STCC Blg 19 Longitude = ", STCC_Bldg19_Loc[1], "\n") +print("Atomic weight of ", aluminumData[0], " = ", aluminumData[2], "\n") +print("Average diameter of earth (in miles) is = ", avgDiameterOfEarthInMiles[0], "\n") +print("2nd lock combination move is: ", lockCombination[1]) diff --git a/lecture20261110/contacts_directory/0 main page.png b/lecture20261110/contacts_directory/0 main page.png new file mode 100644 index 0000000..d5ad4c1 Binary files /dev/null and b/lecture20261110/contacts_directory/0 main page.png differ diff --git a/lecture20261110/contacts_directory/1 Phone type.png b/lecture20261110/contacts_directory/1 Phone type.png new file mode 100644 index 0000000..6e206d6 Binary files /dev/null and b/lecture20261110/contacts_directory/1 Phone type.png differ diff --git a/lecture20261110/contacts_directory/2 email address.png b/lecture20261110/contacts_directory/2 email address.png new file mode 100644 index 0000000..c44aa2f Binary files /dev/null and b/lecture20261110/contacts_directory/2 email address.png differ diff --git a/lecture20261110/contacts_directory/3 Address.png b/lecture20261110/contacts_directory/3 Address.png new file mode 100644 index 0000000..6336a2d Binary files /dev/null and b/lecture20261110/contacts_directory/3 Address.png differ diff --git a/lecture20261110/contacts_directory/listvsdictionary.py b/lecture20261110/contacts_directory/listvsdictionary.py new file mode 100644 index 0000000..3020cef --- /dev/null +++ b/lecture20261110/contacts_directory/listvsdictionary.py @@ -0,0 +1,21 @@ + +from pprint import pprint + +addressList = ["John Smith", "1 Main St", "Anycity", "Ma", "01102"] + +print(addressList) + +print(sorted(addressList)) + +addressDictionary = {'Name':"John Smith", 'Address':"1 Main St", 'City': "Anycity", + 'State':"Ma", 'ZipCode': "01102"} + +print(addressDictionary) + +print(addressDictionary.keys()) +print(addressDictionary.values()) + +for Item in addressDictionary.keys(): + print(f"{Item:10s} {addressDictionary[Item]}") + +pprint(addressDictionary) \ No newline at end of file diff --git a/lecture20261110/if/if01.py b/lecture20261110/if/if01.py new file mode 100644 index 0000000..f3d834f --- /dev/null +++ b/lecture20261110/if/if01.py @@ -0,0 +1,32 @@ + +program01 = ''' + +Program: if01 +This program demonstrates the conditional tests used in Python. + +''' + +print(program01) + +a = 4 +b = 7 +c = 7 + +print(f"a = {a}\nb = {b}\nc = {c}\n") + +print(f"a == b {a==b}") +print(f"a != b {a!=b}") +print(f"a < b {a b {a>b}") +print(f"a >= b {a>=b}") + +print("\n") + +print(f"c == b {c==b}") +print(f"c != b {c!=b}") +print(f"c < b {c b {c>b}") +print(f"c >= b {c>=b}") + diff --git a/lecture20261110/if/if02.py b/lecture20261110/if/if02.py new file mode 100644 index 0000000..37d13de --- /dev/null +++ b/lecture20261110/if/if02.py @@ -0,0 +1,27 @@ + +# if statement example +if 22 > 7: + print("22 is greater than 7") + +print("A better method to define the code ...") + +# Use variables in the if statement and print +data1 = 22 + + +if data1 > 7: + print(f"{data1} is greater than 7") + + +# Or this form +print("And another method to define the code ...") + + +data1 = 22 +data2 = 7 + +if data1 > data2: + print(f"{data1} is greater than {data2}") + +print("Program ended") + diff --git a/lecture20261110/if/if03.py b/lecture20261110/if/if03.py new file mode 100644 index 0000000..577511b --- /dev/null +++ b/lecture20261110/if/if03.py @@ -0,0 +1,16 @@ + +# if..else statement example +x = 7 +print(f"{x} is equal to 7?") +if x == 7: + print("Yes") +else: + print("No") + +# if..else statement example +x = 5 +print(f"{x} is equal to 7?") +if x == 7: + print("Yes") +else: + print("No") diff --git a/lecture20261110/if/if04.py b/lecture20261110/if/if04.py new file mode 100644 index 0000000..8956a55 --- /dev/null +++ b/lecture20261110/if/if04.py @@ -0,0 +1,23 @@ +#!/usr/bin/python3 +# Program: if02 + +# Lists of numbers. These could be integers or floats. +intList = [7, 2, 16, 18, 12, 21] + +# Print the list and the length +print(intList," length = ",len(intList)) + +print(f"Print each value in the list") +counter = 0 +for item in intList: + print(f"intList[{counter}] = {item:2d}") + counter += 1 + +cutoff = 13 +print(f"Print each value in the list >= {cutoff}") +counter = 0 +for item in intList: + if(item >= cutoff): + print(f"intList[{counter}] = {item:2d}") + counter += 1 + diff --git a/lecture20261110/if/if05.py b/lecture20261110/if/if05.py new file mode 100644 index 0000000..fc31f8a --- /dev/null +++ b/lecture20261110/if/if05.py @@ -0,0 +1,25 @@ +#!/usr/bin/python3 +# Program: if03 + +# Lists of numbers. These could be integers or floats. +intList = [7, 2, 16, 18, 12, 21] + +# Print the list and the length +print(intList," length = ",len(intList)) + +print(f"Print each value in the list") +counter = 0 +for item in intList: + print(f"intList[{counter}] = {item:2d}") + counter += 1 + +cutoff = 13 +print(f"Print each value in the list >= {cutoff}") +counter = 0 +for item in intList: + if(item >= cutoff): + print(f"intList[{counter}] = {item:2d}") + else: + print(f"========> intList[{counter}] = {item:2d} is less than {cutoff}") + counter += 1 + diff --git a/lecture20261110/if/if06.py b/lecture20261110/if/if06.py new file mode 100644 index 0000000..bf9b1f5 --- /dev/null +++ b/lecture20261110/if/if06.py @@ -0,0 +1,7 @@ + +# consider the following line from the autoloan program: + +principal = float(input("Enter a value for the principal: ")) + + +print(f"You entered the value {principal}") \ No newline at end of file diff --git a/lecture20261110/if/if07.py b/lecture20261110/if/if07.py new file mode 100644 index 0000000..8ce43f5 --- /dev/null +++ b/lecture20261110/if/if07.py @@ -0,0 +1,16 @@ + +# consider the following line from the autoloan program: + +principal = float(input("Enter a value for the principal: ")) +if(principal < 5000.) or (principal >120000.00): + print(f"The loan value {principal} is outside the allowed limits.") + exit(-1) + +rate = float(input("Enter a value for the interest rate (7 for 7%): ")) + +numberOfYears = float(input("Enter the number of years for the loan: ")) + +print(f"You entered the principal value {principal}") +print(f"You entered the rate value {rate}%") +print(f"You entered the loan term value {numberOfYears} years") + diff --git a/lecture20261110/listmethods/list01MethodAppend.py b/lecture20261110/listmethods/list01MethodAppend.py new file mode 100644 index 0000000..745e026 --- /dev/null +++ b/lecture20261110/listmethods/list01MethodAppend.py @@ -0,0 +1,13 @@ +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm + +programMessage = ''' +This program appends a value to a list. +''' +print(programMessage) + +basicList = [1, 34, 99, 87, 14] +print(f"Before append {basicList}") +basicList.append(104) +print(f"After append {basicList}") + diff --git a/lecture20261110/listmethods/list02MethodClear.py b/lecture20261110/listmethods/list02MethodClear.py new file mode 100644 index 0000000..3d890e6 --- /dev/null +++ b/lecture20261110/listmethods/list02MethodClear.py @@ -0,0 +1,15 @@ + +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm + +programMessage = ''' +This program clears all values from a list. +''' +print(programMessage) + + +basicList = [1, 34, 99, 87, 14] +print(f"Before clear {basicList}") +basicList.clear() +print(f"After clear {basicList}") + diff --git a/lecture20261110/listmethods/list03MethodShallowCopy.py b/lecture20261110/listmethods/list03MethodShallowCopy.py new file mode 100644 index 0000000..a644c10 --- /dev/null +++ b/lecture20261110/listmethods/list03MethodShallowCopy.py @@ -0,0 +1,31 @@ + +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm +programMessage = ''' +A shallow copy is a new name for an existing object. This copy demonstrates +this principle. +1.) Create a list. +2.) Create a new name and set it equal to the original list. +3.) Show the id's of the objects are the same. +4.) Append a value to one then show the other name shows the same list. +''' + +print(programMessage) + +basicList = [1, 34, 99, 87, 14] +print(f"Before copy {basicList}") +myList = basicList +print(f"After copy {basicList} ==> {myList}") +print(f"After copy {id(basicList)} <= Same ID => {id(myList)}") + +print("\n") +print("Append a value to basicList. Examine the change to myList\n") +#basicList = [1, 34, 99, 87, 14] +myList = basicList +print(f"Before append to basicList {basicList}") +basicList.append(777) +print(f"basicList - After append {basicList}") +print(f"myList - After append {myList}") +print(f"After append {id(basicList)} <= Same ID => {id(myList)}") + + diff --git a/lecture20261110/listmethods/list04MethodDeepCopy.py b/lecture20261110/listmethods/list04MethodDeepCopy.py new file mode 100644 index 0000000..a0ab9cb --- /dev/null +++ b/lecture20261110/listmethods/list04MethodDeepCopy.py @@ -0,0 +1,33 @@ + +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm +programMessage = ''' +A deep copy is a new copy of an existing object. This copy demonstrates +this principle. +1.) Create a list. +2.) Create a new copy from the original list. +3.) Show the id's of the objects are the different. +4.) Append a value to basicList then show the copy in myList has not changed. +''' + +print(programMessage) + +basicList = [1, 34, 99, 87, 14] +print(f"Before copy {basicList}") +myList = basicList.copy() +print(f"After copy {basicList} ==> {myList}") +print(f"After copy {id(basicList)} <= Not Equal => {id(myList)}") + + +print("\n") +print("Append a value to basicList. Examine any changes to myList\n") +#basicList = [1, 34, 99, 87, 14] +#myList = basicList.copy() +print(f"Before append to basicList {basicList}") +basicList.append(777) +print(f"basicList - After append {basicList}") +print(f"myList - After append {myList}") +print(f"After append {id(basicList)} <= Not Equal => {id(myList)}") + + + diff --git a/lecture20261110/listmethods/list05MethodCount.py b/lecture20261110/listmethods/list05MethodCount.py new file mode 100644 index 0000000..c241676 --- /dev/null +++ b/lecture20261110/listmethods/list05MethodCount.py @@ -0,0 +1,33 @@ + +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm + +programMessage = ''' +The count() method counts the number of elements in a list. + +''' + +print(programMessage) + + +basicList = [1, 34, 99, 87, 14, 1, 34, 1,87 ] +print(f"Example list {basicList}") + +myValue = 1 +counter = basicList.count(myValue) +print(f"The number of '{myValue}' items is {counter}") + +myValue = 34 +counter = basicList.count(myValue) +print(f"The number of '{myValue}' items is {counter}") + +myValue = 87 +counter = basicList.count(myValue) +print(f"The number of '{myValue}' items is {counter}") + +myValue = 314 +counter = basicList.count(myValue) +print(f"The number of '{myValue}' items is {counter}") + + + diff --git a/lecture20261110/listmethods/list06MethodExtend.py b/lecture20261110/listmethods/list06MethodExtend.py new file mode 100644 index 0000000..2c8740d --- /dev/null +++ b/lecture20261110/listmethods/list06MethodExtend.py @@ -0,0 +1,26 @@ + +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm + +programMessage = ''' +The extend() method appends one list to another list. + +''' + +print(programMessage) + + +basicList = [1, 34, 99, 87, 14] +print(f"basicList = {basicList}") + +myList = [111, 399, 1234] +print(f"myList = {myList}") + +print("\nExtending basicList with myList\n") + +basicList.extend(myList) + +print(f"basicList = {basicList}") +print(f"myList = {myList}") + +print("\n") diff --git a/lecture20261110/listmethods/list07MethodIndex.py b/lecture20261110/listmethods/list07MethodIndex.py new file mode 100644 index 0000000..c333a3a --- /dev/null +++ b/lecture20261110/listmethods/list07MethodIndex.py @@ -0,0 +1,38 @@ + +# https://www.w3schools.com/python/python_ref_list.asp +# https://www.quackit.com/python/reference/python_3_list_methods.cfm + +programMessage = ''' +The index() method locates the first element in a list. + +''' + +print(programMessage) + + +basicList = [1, 34, 99, 87, 14, 1, 34, 1,87 ] +print(f"Example list {basicList}") + +myValue = 1 +index = basicList.index(myValue) +print(f"The location of '{myValue}' item is at position {index}") + + + +myValue = 1 +index = basicList.index(myValue,index+1) +print(f"The next location of '{myValue}' item is at position {index}") + + +myValue = 1 +index = basicList.index(myValue,index+1) +print(f"The next location of '{myValue}' item is at position {index}") + + +print("This last search generates an error.") + +myValue = 1 +index = basicList.index(myValue,index+1) +print(f"The next location of '{myValue}' item is at position {index}") + + diff --git a/lecture20261110/listmethods/list08MethodInsert.py b/lecture20261110/listmethods/list08MethodInsert.py new file mode 100644 index 0000000..91d7e65 --- /dev/null +++ b/lecture20261110/listmethods/list08MethodInsert.py @@ -0,0 +1,51 @@ +#!/usr/bin/python3 +# Program: list04 + +programMessage = ''' +This program inserts a value into a list. +''' +print(programMessage) + + +# Lists of text values +#dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] +dogNames = [ "Harry","Katrina","Tanner", "Colorado","Mandy"] + +# Print the list and the length +print("Print the length and type of the list.") +print (dogNames," length = ",len(dogNames),"Type =",type(dogNames)) +print("\nPrint each element of the list and it's index") + +index = 0 +for item in dogNames: + print(f"dogNames[{index}] = {item}") + index = index + 1 + +# Insert a new dog at position 1. Lists begin indexing at 0 +newDogName = "Shenanigans" +print("Insert at position 1") +dogNames.insert(1,newDogName) +print(f"The modified list {dogNames}") + +print(f"\nInsert a new dog at position 4. Lists begin indexing at 0.") +newDogName = "Yukon Jack" +print("Insert at position 4 after Tanner") +dogNames.insert(4,newDogName) +print(f"The modified list {dogNames}") + +print(f"\nLocate a dog name, then insert a new dog after the dog we located.") +message1 =''' +Note: This program is created so the search succeeds. +If the search fails the program will generate an error and stop. This can be +remedied with a try - except block. +''' +print(message1) +searchDog = "Katrina" +newDogName = "Gimli" +print(f"Locate the dog named {searchDog}") +searchDogIndex = dogNames.index(searchDog) +print(f"Found dog {searchDog} at index {searchDogIndex}") +print(f"Insert new dog name = {newDogName} before {searchDog}") +dogNames.insert(searchDogIndex,newDogName) +print(f"The new list = {dogNames}") + diff --git a/lecture20261110/listmethods/list09MethodPop.py b/lecture20261110/listmethods/list09MethodPop.py new file mode 100644 index 0000000..b8d837f --- /dev/null +++ b/lecture20261110/listmethods/list09MethodPop.py @@ -0,0 +1,40 @@ +#!/usr/bin/python3 +# Program: list09MethodPop.py + +programMessage = ''' +This program popss a value from a list. The value is removed from +the end of the list or at the position specified by an optional index. +''' +print(programMessage) + + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] + + +# Print the list and the length +print("Print the length and type of the list.") +print (dogNames," length = ",len(dogNames),"Type =",type(dogNames)) +print("\nPrint each element of the list and it's index") + +index = 0 +for item in dogNames: + print(f"dogNames[{index}] = {item}") + index = index + 1 + +print(f"Pop last element") +dog = dogNames.pop() +print(f"Removed {dog} from {dogNames}") + +print(f"Pop last element") +dog = dogNames.pop() +print(f"Removed {dog} from {dogNames}") + +print(f"Pop last element") +dog = dogNames.pop() +print(f"Removed {dog} from {dogNames}") + +print(f"Pop element at position 1") +dog = dogNames.pop(1) +print(f"Removed {dog} from {dogNames}") + diff --git a/lecture20261110/listmethods/list10MethodReverse.py b/lecture20261110/listmethods/list10MethodReverse.py new file mode 100644 index 0000000..080d9f3 --- /dev/null +++ b/lecture20261110/listmethods/list10MethodReverse.py @@ -0,0 +1,24 @@ +#!/usr/bin/python3 +# Program: list09MethodReverse.py + +programMessage = ''' +This program reverses a list. +''' +print(programMessage) + + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] + + +# Print the list and the length +print("Print the length and type of the list.") +print (dogNames," length = ",len(dogNames),"Type =",type(dogNames)) + +print("\nReverse the list") + +dogNames.reverse() +print("Print the length of the reversed list.") +print (dogNames) + + diff --git a/lecture20261110/listmethods/list11MethodSort.py b/lecture20261110/listmethods/list11MethodSort.py new file mode 100644 index 0000000..2af52d4 --- /dev/null +++ b/lecture20261110/listmethods/list11MethodSort.py @@ -0,0 +1,24 @@ +#!/usr/bin/python3 +# Program: list11MethodSort.py + +programMessage = ''' +This program sorts a list. +''' +print(programMessage) + + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] + + +# Print the list and the length +print("Print the length and type of the list.") +print (dogNames," length = ",len(dogNames),"Type =",type(dogNames)) + +print("\nSort the list") + +dogNames.sort() +print("Print the length of the sorted list.") +print (dogNames) + + diff --git a/lecture20261110/listmethods/list12MethodDemoMost.py b/lecture20261110/listmethods/list12MethodDemoMost.py new file mode 100644 index 0000000..032116d --- /dev/null +++ b/lecture20261110/listmethods/list12MethodDemoMost.py @@ -0,0 +1,77 @@ + + +programMessage = ''' +This program demonstrates many of the methods in a single program. + +''' +print(programMessage) + +# Create some lists +cars01 = ["Tundra", "Accord", "Ridgeline", "Stingray"] +moreCars = ["Elantra", "Tacoma", "Silverado", "Denali"] + +print(f"cars01 = {cars01}") +print(f"morecars = {moreCars}") +print("\n") + +# demonstrate append +newCar = "f150" +print(f"Append {newCar} to cars01") +cars01.append(newCar) +print(f"cars01 = {cars01}\n") + +# demonstrate count +targetCar = "f150" +print(f"count values of {targetCar} in cars01 = {cars01.count(targetCar)}\n") + +targetCar = "Corvette" +print(f"count values of {targetCar} in cars01 = {cars01.count(targetCar)}\n") + +print("Demonstrate extend the list\n== Original lists:" ) + +cars01 = ["Tundra", "Accord", "Ridgeline", "Stingray"] +moreCars = ["Elantra", "Tacoma", "Silverado", "Denali"] +print(f"cars01 = {cars01}") +print(f"morecars = {moreCars}") + +print("== Extend cars01 with moreCars") +cars01.extend(moreCars) +print(f"cars01 = {cars01}") +print(f"morecars = {moreCars}") + +# Restore the original lists +cars01 = ["Tundra", "Accord", "Ridgeline", "Stingray"] +moreCars = ["Elantra", "Tacoma", "Silverado", "Denali"] + +# demonstrate index +print("\nDemonstrate the Index (find) method") + +print(f"cars01 = {cars01}") +myValue = "Accord" +index = cars01.index(myValue) +print(f"The location of '{myValue}' item is at position {index}") + +# Uncomment the following lines below to demonstrate a failure +#myValue = "Tacoma" +#index = cars01.index(myValue) +#print(f"The location of '{myValue}' item is at position {index}") + +print("\n") + +# Demonstrate sort +cars01 = ["Tundra", "Accord", "Ridgeline", "Stingray"] +print(f"cars01 = {cars01}") + +cars01.sort() +print(f"Sorted cars01 = {cars01}") +print("\n") + +# Demonstrate reverse +cars01 = ["Tundra", "Accord", "Ridgeline", "Stingray"] +print(f"cars01 = {cars01}") + +cars01.reverse() +print(f"Reversed cars01 = {cars01}") + + + diff --git a/lecture20261110/lists/exciseTax01.py b/lecture20261110/lists/exciseTax01.py new file mode 100644 index 0000000..1e055fd --- /dev/null +++ b/lecture20261110/lists/exciseTax01.py @@ -0,0 +1,28 @@ + +message01 = ''' +Mass Excise Tax Fees +==================== + +The tax depends on the vehicle age. For this program we only calculate the +excise tax on the first year of purchase. +https://www.sec.state.ma.us/divisions/cis/tax/motor-excise.htm + +Vehicle Age Percentage of List Price +In the year preceding the model year +(brand new car released before model year) 50% +In the model year 90% +In the second year 60% +In the third year 40% +In the fourth year 25% +In the fifth and succeeding years 10% +''' +print(message01) +# Tax table for excise tax by year. +exciseTaxRateTable = [.5, .9, .6, .4, .25, .10, .10, .10, .10, .10] +year = -1 # Indicates a date prior to the model year; i.e you bought a model year 2024 in year 2023. +for exciseTaxRate in exciseTaxRateTable: + print(f"{year:2d} {exciseTaxRate:.2f} {exciseTaxRate:.0%}") + year += 1 # Shorthand for year = year + 1 + +print("Access excise tax rate by index") + diff --git a/lecture20261110/lists/exciseTax02.py b/lecture20261110/lists/exciseTax02.py new file mode 100644 index 0000000..fdd0b67 --- /dev/null +++ b/lecture20261110/lists/exciseTax02.py @@ -0,0 +1,31 @@ + +message01 = ''' +Mass Excise Tax Fees +==================== + +The tax depends on the vehicle age. For this program we only calculate the +excise tax on the first year of purchase. +https://www.sec.state.ma.us/divisions/cis/tax/motor-excise.htm + +Vehicle Age Percentage of List Price +In the year preceding the model year +(brand new car released before model year) 50% +In the model year 90% +In the second year 60% +In the third year 40% +In the fourth year 25% +In the fifth and succeeding years 10% +''' +print(message01) +# Tax table for excise tax by year. +exciseTaxRateTable = [.5, .9, .6, .4, .25, .10, .10, .10, .10, .10] + +print("Access excise tax rate by index") +yearIndex = 2 +print(f"year = {yearIndex} rate = {exciseTaxRateTable[yearIndex]}") + +yearIndex = 4 +print(f"year = {yearIndex} rate = {exciseTaxRateTable[yearIndex]}") + +yearIndex = 7 # set to 9 or more and the program will fault +print(f"year = {yearIndex} rate = {exciseTaxRateTable[yearIndex]}") diff --git a/lecture20261110/lists/exciseTax03.py b/lecture20261110/lists/exciseTax03.py new file mode 100644 index 0000000..41ca8e8 --- /dev/null +++ b/lecture20261110/lists/exciseTax03.py @@ -0,0 +1,30 @@ + +message01 = ''' +Mass Excise Tax Fees +==================== + +The tax depends on the vehicle age. For this program we only calculate the +excise tax on the first year of purchase. +https://www.sec.state.ma.us/divisions/cis/tax/motor-excise.htm + +Vehicle Age Percentage of List Price +In the year preceding the model year +(brand new car released before model year) 50% +In the model year 90% +In the second year 60% +In the third year 40% +In the fourth year 25% +In the fifth and succeeding years 10% +''' +print(message01) +# Tax table for excise tax by year. +exciseTaxRateTable = [.5, .9, .6, .4, .25, .10, .10, .10, .10, .10] +yearIndex = -1 # Indicates a date prior to the model year; i.e you bought a model year 2024 in year 2023. + +# Change the 8 to 10. The program will fault. +while yearIndex <= 8: + print(f"{yearIndex:2d} {exciseTaxRateTable[yearIndex]}") + yearIndex += 1 # Shorthand for yearIndex = yearIndex + 1 + + + diff --git a/lecture20261110/lists/exciseTax04.py b/lecture20261110/lists/exciseTax04.py new file mode 100644 index 0000000..a1be8e3 --- /dev/null +++ b/lecture20261110/lists/exciseTax04.py @@ -0,0 +1,33 @@ + +message01 = ''' +Mass Excise Tax Fees +==================== + +The tax depends on the vehicle age. For this program we only calculate the +excise tax on the first year of purchase. +https://www.sec.state.ma.us/divisions/cis/tax/motor-excise.htm + +Vehicle Age Percentage of List Price +In the year preceding the model year +(brand new car released before model year) 50% +In the model year 90% +In the second year 60% +In the third year 40% +In the fourth year 25% +In the fifth and succeeding years 10% +''' +print(message01) +# Tax table for excise tax by year. +exciseTaxRateTable = [.5, .9, .6, .4, .25, .10] + +print("Length of tax table is ",len(exciseTaxRateTable)) +yearIndex = 0 +year = 2025 + +# +while year >= 2001: + if yearIndex > 5: + yearIndex = 5 + print(f"{year:4d} {yearIndex:2d} {exciseTaxRateTable[yearIndex]}") + yearIndex += 1 # Shorthand for yearIndex = yearIndex + 1 + year = year - 1 diff --git a/lecture20261110/lists/grades01.py b/lecture20261110/lists/grades01.py new file mode 100644 index 0000000..27de1d3 --- /dev/null +++ b/lecture20261110/lists/grades01.py @@ -0,0 +1,16 @@ +#!/usr/bin/python3 +# grades01 +# List element manipulation. + +scores = [75, 95, 90, 87, 99, 100, 97] + +# This is unnecessary and just here for debugging. +print(scores) + +# We will sum the scores. Initialize sum value to zero then add each value to the sum. +sum = 0 +for score in scores: + sum = sum + score + +print("The sum of the seven scores is ",sum) +print("The average of the seven scores is ",sum/7) diff --git a/lecture20261110/lists/grades02.py b/lecture20261110/lists/grades02.py new file mode 100644 index 0000000..996e014 --- /dev/null +++ b/lecture20261110/lists/grades02.py @@ -0,0 +1,15 @@ +#!/usr/bin/python3 +# grades02 +# List element manipulation. + +scores = [75, 95, 90, 87, 99, 100, 97, 100] + +numberOfScores = len(scores) + +# We will sum the scores. Initialize sum value to zero then add each value to the sum. +sum = 0 +for score in scores: + sum = sum + score + +print(f"The sum of the {numberOfScores} scores is {sum:.2f}") +print(f"The average of the {numberOfScores} scores is {sum/numberOfScores:.2f}") diff --git a/lecture20261110/lists/grades03.py b/lecture20261110/lists/grades03.py new file mode 100644 index 0000000..bc248f0 --- /dev/null +++ b/lecture20261110/lists/grades03.py @@ -0,0 +1,23 @@ +#!/usr/bin/python3 +# grades03 +# List element manipulation. + +numberOfScores = int(input("How many scores do you want to enter? ")) +counter = 0 # Start counter at 0 +scores = [] # Create an empty list +while(counter < numberOfScores): + nextScore = float(input("Enter the next value: ")) + scores.append(nextScore) + counter += 1 + +# This is unnecessary and just here for debugging. +print(scores) + +# We will sum the scores. Initialize sum value to zero then add each value to the sum. + +sum = 0 +for score in scores: + sum = sum + score + +print(f"The sum of the {numberOfScores} scores is {sum:.2f}") +print(f"The average of the {numberOfScores} scores is {sum/numberOfScores:.2f}") diff --git a/lecture20261110/lists/list01.py b/lecture20261110/lists/list01.py new file mode 100644 index 0000000..c520fe2 --- /dev/null +++ b/lecture20261110/lists/list01.py @@ -0,0 +1,17 @@ +#!/usr/bin/python3 +# Program: list01 + +# Defining and printing list lengths. + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] + +# Lists of numbers. These could be integers or floats. +intList = [7, 2, 12, 18, 16, 21] + + + +# Print the list and the length +print("Print the length of the lists.") +print (dogNames," length = ",len(dogNames)) +print(intList," length = ",len(intList)) diff --git a/lecture20261110/lists/list02.py b/lecture20261110/lists/list02.py new file mode 100644 index 0000000..3e5c18b --- /dev/null +++ b/lecture20261110/lists/list02.py @@ -0,0 +1,21 @@ +#!/usr/bin/python3 +# Program: list02 + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] +firstNames = ["edward","david", "Bob","mary","alice"] + + +# Print the list and the length +print("Print the length of the lists.") +print (dogNames," length = ",len(dogNames)) +print(firstNames," length = ",len(firstNames)) +print("\n") + +# Another way to think of the for loop is to read it as +# "Select the next element from the list, put it into the variable +# item, the do whatever you like with that one value in item". +# The for loop ends when the entire list has been processed. + +for item in dogNames: + print(item) diff --git a/lecture20261110/lists/list03.py b/lecture20261110/lists/list03.py new file mode 100644 index 0000000..cd9443b --- /dev/null +++ b/lecture20261110/lists/list03.py @@ -0,0 +1,11 @@ +#!/usr/bin/python3 +# Program: list03 + +# Run this code in the visualizer in a web browser at +# https://pythontutor.com/visualize.html#mode=edit + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"] + +for dogName in dogNames: + print(dogName) diff --git a/lecture20261110/lists/list04.py b/lecture20261110/lists/list04.py new file mode 100644 index 0000000..5394f4a --- /dev/null +++ b/lecture20261110/lists/list04.py @@ -0,0 +1,17 @@ +#!/usr/bin/python3 +# Program: list04 + +# Lists of text values +dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy",7] + +# Print the list and the length +print("Print the length of the list.") +print (dogNames," length = ",len(dogNames),"Type =",type(dogNames)) +print("\n") + +for item in dogNames: +# print(f"{item:14s} {type(item)}") + print(f"{item} {type(item)}") + + +print("\nDone!") diff --git a/lecture20261110/lists/range01.py b/lecture20261110/lists/range01.py new file mode 100644 index 0000000..11039f1 --- /dev/null +++ b/lecture20261110/lists/range01.py @@ -0,0 +1,15 @@ + +# This code is based on: https://www.w3schools.com/python/ref_func_range.asp + +x = range(3, 6) +print(f"x = {x}, type = {type(x)}") + +# Another way to think of the for loop is to read it as +# "Select the next element from the list or range, put it into the variable +# item, the do whatever you like with that one value in item". +# The for loop ends when the entire list has been processed. + +for item in x: + print(item) + + diff --git a/lecture20261110/lists/range02.py b/lecture20261110/lists/range02.py new file mode 100644 index 0000000..5e89e6b --- /dev/null +++ b/lecture20261110/lists/range02.py @@ -0,0 +1,21 @@ + +# This code is based on: https://www.w3schools.com/python/ref_func_range.asp + +x = range(3, 6) + +# A range can be converted to a list. +y = list(x) + +# Note: +# What is the difference betweeen using range() and an explicit list? +# The main difference is that range calculates the value on the fly. This saves memory +# at the expense of processing speed. The list has each object stored in memory. This saves +# the processing time at the expense of memory usage. + +print(f"x = {x}, type = {type(x)}") +for item in x: + print(item) + +print(f"y = {y}, type = {type(y)}") +for item in y: + print(item) diff --git a/lecture20261110/lists/range03.py b/lecture20261110/lists/range03.py new file mode 100644 index 0000000..a77cef5 --- /dev/null +++ b/lecture20261110/lists/range03.py @@ -0,0 +1,21 @@ + +# This code is based on: https://www.w3schools.com/python/ref_func_range.asp + +# Create a range from 2 to 10 with steps of two +x = range(2, 10, 2) +y = list(x) + +# Note: +# What is the difference betweeen using range() and an explicit list? +# The main difference is that range calculates the value on the fly. This saves memory +# at the expense of processing speed. The list has each object stored in memory. This saves +# the processing time at the expense of memory usage. + +print(f"x = {x}, type = {type(x)}, length = {len(x)}") + +for item in x: + print(item) + +print(f"y = {y}, type = {type(y)}, length = {len(y)}") +for item in y: + print(item)