Added code for lecture 2026-11-10
This commit is contained in:
parent
5b630435ae
commit
07b9e54bf0
52 changed files with 1248 additions and 1 deletions
21
lecture20261110/DictionariesAndTry/dictionary0.py
Normal file
21
lecture20261110/DictionariesAndTry/dictionary0.py
Normal file
|
|
@ -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'])
|
||||
17
lecture20261110/DictionariesAndTry/dictionary1.py
Normal file
17
lecture20261110/DictionariesAndTry/dictionary1.py
Normal file
|
|
@ -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'])
|
||||
|
||||
21
lecture20261110/DictionariesAndTry/dictionary2.py
Normal file
21
lecture20261110/DictionariesAndTry/dictionary2.py
Normal file
|
|
@ -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")
|
||||
|
||||
|
||||
15
lecture20261110/DictionariesAndTry/dictionary3.py
Normal file
15
lecture20261110/DictionariesAndTry/dictionary3.py
Normal file
|
|
@ -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")
|
||||
14
lecture20261110/DictionariesAndTry/dictionary3a.py
Normal file
14
lecture20261110/DictionariesAndTry/dictionary3a.py
Normal file
|
|
@ -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")
|
||||
|
||||
25
lecture20261110/DictionariesAndTry/dictionary4.py
Normal file
25
lecture20261110/DictionariesAndTry/dictionary4.py
Normal file
|
|
@ -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'])
|
||||
|
||||
|
||||
|
||||
23
lecture20261110/DictionariesAndTry/weather-data01.py
Normal file
23
lecture20261110/DictionariesAndTry/weather-data01.py
Normal file
|
|
@ -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)
|
||||
|
||||
31
lecture20261110/DictionariesAndTry/weather-data02.py
Normal file
31
lecture20261110/DictionariesAndTry/weather-data02.py
Normal file
|
|
@ -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'])
|
||||
|
||||
24
lecture20261110/DictionariesAndTry/weather-data03.py
Normal file
24
lecture20261110/DictionariesAndTry/weather-data03.py
Normal file
|
|
@ -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)
|
||||
|
||||
25
lecture20261110/DictionariesAndTry/weather-data04.py
Normal file
25
lecture20261110/DictionariesAndTry/weather-data04.py
Normal file
|
|
@ -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]} ")
|
||||
|
||||
|
||||
56
lecture20261110/List-Intro_0001.py
Normal file
56
lecture20261110/List-Intro_0001.py
Normal file
|
|
@ -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])
|
||||
52
lecture20261110/Tuples-Intro_0001.py
Normal file
52
lecture20261110/Tuples-Intro_0001.py
Normal file
|
|
@ -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])
|
||||
BIN
lecture20261110/contacts_directory/0 main page.png
Normal file
BIN
lecture20261110/contacts_directory/0 main page.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
BIN
lecture20261110/contacts_directory/1 Phone type.png
Normal file
BIN
lecture20261110/contacts_directory/1 Phone type.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
BIN
lecture20261110/contacts_directory/2 email address.png
Normal file
BIN
lecture20261110/contacts_directory/2 email address.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
BIN
lecture20261110/contacts_directory/3 Address.png
Normal file
BIN
lecture20261110/contacts_directory/3 Address.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
21
lecture20261110/contacts_directory/listvsdictionary.py
Normal file
21
lecture20261110/contacts_directory/listvsdictionary.py
Normal file
|
|
@ -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)
|
||||
32
lecture20261110/if/if01.py
Normal file
32
lecture20261110/if/if01.py
Normal file
|
|
@ -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}")
|
||||
print(f"a <= b {a<=b}")
|
||||
print(f"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}")
|
||||
print(f"c <= b {c<=b}")
|
||||
print(f"c > b {c>b}")
|
||||
print(f"c >= b {c>=b}")
|
||||
|
||||
27
lecture20261110/if/if02.py
Normal file
27
lecture20261110/if/if02.py
Normal file
|
|
@ -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")
|
||||
|
||||
16
lecture20261110/if/if03.py
Normal file
16
lecture20261110/if/if03.py
Normal file
|
|
@ -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")
|
||||
23
lecture20261110/if/if04.py
Normal file
23
lecture20261110/if/if04.py
Normal file
|
|
@ -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
|
||||
|
||||
25
lecture20261110/if/if05.py
Normal file
25
lecture20261110/if/if05.py
Normal file
|
|
@ -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
|
||||
|
||||
7
lecture20261110/if/if06.py
Normal file
7
lecture20261110/if/if06.py
Normal file
|
|
@ -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}")
|
||||
16
lecture20261110/if/if07.py
Normal file
16
lecture20261110/if/if07.py
Normal file
|
|
@ -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")
|
||||
|
||||
13
lecture20261110/listmethods/list01MethodAppend.py
Normal file
13
lecture20261110/listmethods/list01MethodAppend.py
Normal file
|
|
@ -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}")
|
||||
|
||||
15
lecture20261110/listmethods/list02MethodClear.py
Normal file
15
lecture20261110/listmethods/list02MethodClear.py
Normal file
|
|
@ -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}")
|
||||
|
||||
31
lecture20261110/listmethods/list03MethodShallowCopy.py
Normal file
31
lecture20261110/listmethods/list03MethodShallowCopy.py
Normal file
|
|
@ -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)}")
|
||||
|
||||
|
||||
33
lecture20261110/listmethods/list04MethodDeepCopy.py
Normal file
33
lecture20261110/listmethods/list04MethodDeepCopy.py
Normal file
|
|
@ -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)}")
|
||||
|
||||
|
||||
|
||||
33
lecture20261110/listmethods/list05MethodCount.py
Normal file
33
lecture20261110/listmethods/list05MethodCount.py
Normal file
|
|
@ -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}")
|
||||
|
||||
|
||||
|
||||
26
lecture20261110/listmethods/list06MethodExtend.py
Normal file
26
lecture20261110/listmethods/list06MethodExtend.py
Normal file
|
|
@ -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")
|
||||
38
lecture20261110/listmethods/list07MethodIndex.py
Normal file
38
lecture20261110/listmethods/list07MethodIndex.py
Normal file
|
|
@ -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}")
|
||||
|
||||
|
||||
51
lecture20261110/listmethods/list08MethodInsert.py
Normal file
51
lecture20261110/listmethods/list08MethodInsert.py
Normal file
|
|
@ -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}")
|
||||
|
||||
40
lecture20261110/listmethods/list09MethodPop.py
Normal file
40
lecture20261110/listmethods/list09MethodPop.py
Normal file
|
|
@ -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}")
|
||||
|
||||
24
lecture20261110/listmethods/list10MethodReverse.py
Normal file
24
lecture20261110/listmethods/list10MethodReverse.py
Normal file
|
|
@ -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)
|
||||
|
||||
|
||||
24
lecture20261110/listmethods/list11MethodSort.py
Normal file
24
lecture20261110/listmethods/list11MethodSort.py
Normal file
|
|
@ -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)
|
||||
|
||||
|
||||
77
lecture20261110/listmethods/list12MethodDemoMost.py
Normal file
77
lecture20261110/listmethods/list12MethodDemoMost.py
Normal file
|
|
@ -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}")
|
||||
|
||||
|
||||
|
||||
28
lecture20261110/lists/exciseTax01.py
Normal file
28
lecture20261110/lists/exciseTax01.py
Normal file
|
|
@ -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")
|
||||
|
||||
31
lecture20261110/lists/exciseTax02.py
Normal file
31
lecture20261110/lists/exciseTax02.py
Normal file
|
|
@ -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]}")
|
||||
30
lecture20261110/lists/exciseTax03.py
Normal file
30
lecture20261110/lists/exciseTax03.py
Normal file
|
|
@ -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
|
||||
|
||||
|
||||
|
||||
33
lecture20261110/lists/exciseTax04.py
Normal file
33
lecture20261110/lists/exciseTax04.py
Normal file
|
|
@ -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
|
||||
16
lecture20261110/lists/grades01.py
Normal file
16
lecture20261110/lists/grades01.py
Normal file
|
|
@ -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)
|
||||
15
lecture20261110/lists/grades02.py
Normal file
15
lecture20261110/lists/grades02.py
Normal file
|
|
@ -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}")
|
||||
23
lecture20261110/lists/grades03.py
Normal file
23
lecture20261110/lists/grades03.py
Normal file
|
|
@ -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}")
|
||||
17
lecture20261110/lists/list01.py
Normal file
17
lecture20261110/lists/list01.py
Normal file
|
|
@ -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))
|
||||
21
lecture20261110/lists/list02.py
Normal file
21
lecture20261110/lists/list02.py
Normal file
|
|
@ -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)
|
||||
11
lecture20261110/lists/list03.py
Normal file
11
lecture20261110/lists/list03.py
Normal file
|
|
@ -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)
|
||||
17
lecture20261110/lists/list04.py
Normal file
17
lecture20261110/lists/list04.py
Normal file
|
|
@ -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!")
|
||||
15
lecture20261110/lists/range01.py
Normal file
15
lecture20261110/lists/range01.py
Normal file
|
|
@ -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)
|
||||
|
||||
|
||||
21
lecture20261110/lists/range02.py
Normal file
21
lecture20261110/lists/range02.py
Normal file
|
|
@ -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)
|
||||
21
lecture20261110/lists/range03.py
Normal file
21
lecture20261110/lists/range03.py
Normal file
|
|
@ -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)
|
||||
Loading…
Add table
Add a link
Reference in a new issue