From 5f244937ae08d4d38b6f1840928a6039cf206858 Mon Sep 17 00:00:00 2001 From: "vignesh.nagaraju" Date: Tue, 16 Jun 2026 18:44:27 -0500 Subject: [PATCH] Update with my code --- Start/1. PythonFeatures/assignment.py | 19 ++++++---- Start/1. PythonFeatures/doc_strings.py | 9 +++++ Start/1. PythonFeatures/print_pprint.py | 11 ++++-- Start/1. PythonFeatures/pyscope.py | 35 +++++++++++++++---- Start/1. PythonFeatures/specialnames.py | 12 ++++--- Start/2. Iterators/basic_iterators.py | 12 +++++-- Start/2. Iterators/for_else.py | 23 ++++++++++--- Start/2. Iterators/itertools1.py | 17 +++++++-- Start/2. Iterators/itertools2.py | 9 ++++- Start/2. Iterators/itertools3.py | 15 ++++---- Start/2. Iterators/itertools4.py | 16 ++++++++- Start/2. Iterators/more_iterators.py | 24 +++++++++---- Start/3. Strings/Author_solution | 37 ++++++++++++++++++++ Start/3. Strings/builtin_constants.py | 42 ++++++++++++++--------- Start/3. Strings/string_format.py | 33 ++++++++++++++---- Start/3. Strings/string_manipulation.py | 16 +++++++-- Start/3. Strings/string_search.py | 28 +++++++-------- Start/3. Strings/test | 41 ++++++++++++++++++++++ Start/4. Sequences/dict_comprehensions.py | 7 ++-- Start/4. Sequences/list_comprehensions.py | 9 +++-- Start/4. Sequences/sequence_compare.py | 16 ++++----- Start/4. Sequences/sequence_slicing.py | 22 ++++++++---- Start/4. Sequences/set_comprehensions.py | 7 +++- Start/4. Sequences/test.py | 14 ++++++++ Start/5. Exceptions/basic_exceptions.py | 19 +++++++--- Start/5. Exceptions/challenge.py | 12 ++++++- Start/5. Exceptions/common_exceptions.py | 11 ++++-- Start/5. Exceptions/custom_exceptions.py | 9 +++++ Start/5. Exceptions/myfile.txt | 0 printoutput.txt | 1 + 30 files changed, 413 insertions(+), 113 deletions(-) create mode 100644 Start/3. Strings/Author_solution create mode 100644 Start/3. Strings/test create mode 100644 Start/4. Sequences/test.py create mode 100644 Start/5. Exceptions/myfile.txt create mode 100644 printoutput.txt diff --git a/Start/1. PythonFeatures/assignment.py b/Start/1. PythonFeatures/assignment.py index 6df771f..ba6a74e 100644 --- a/Start/1. PythonFeatures/assignment.py +++ b/Start/1. PythonFeatures/assignment.py @@ -7,19 +7,26 @@ # regular assignment statements assign a value x = 5 print(x) - # the assignment operator is part of an expression - +(x:= 10) +print(x) # The assignment expression is useful for writing concise code +# thestr = input("Value? ") +# while thestr != "exit": +# print(thestr) +# thestr = input("Value? ") +# while (thestr := input("Value? ")) != "exit": +# print(thestr) # The walrus operator can help reduce redundant function calls values = [12, 0, 10, 5, 9, 18, 41, 23, 30, 16, 18, 9, 18, 22] -l = len(values) -s = sum(values) +# l = len(values) +# s = sum(values) val_data = { - "length": l, - "total": s, + "length": (l := len(values)), + "total": (s := sum(values)), "average": s/l } +pprint.pp(val_data) \ No newline at end of file diff --git a/Start/1. PythonFeatures/doc_strings.py b/Start/1. PythonFeatures/doc_strings.py index 60d40a5..c250bba 100644 --- a/Start/1. PythonFeatures/doc_strings.py +++ b/Start/1. PythonFeatures/doc_strings.py @@ -3,6 +3,15 @@ def myFunction(arg1, arg2=None): + """myFunction(arg1, arg2=None)--> Doesn't do anything but print the arguments + + Parameters + ---------- + arg1 : any + The first argument.Whatever you want it to be. + arg2 : any, optional + The second argument (default is None).Do what you like. + """ print(arg1, arg2) diff --git a/Start/1. PythonFeatures/print_pprint.py b/Start/1. PythonFeatures/print_pprint.py index fe40a6f..4339b4d 100644 --- a/Start/1. PythonFeatures/print_pprint.py +++ b/Start/1. PythonFeatures/print_pprint.py @@ -8,16 +8,20 @@ # output for increased readability # basic print() function values=["one", "two", "three", "four", "five"] -print(*values) +# print(*values) # use the 'sep' argument to control the separator between values: +# print(*values, sep=" -- ") # use the 'end' argument to control the line ending characters # let's auto-print the current line number along with each item - +# for i in range(0, len(values)): +# print(values[i], end=f" [line: {str(i+1)}]\n") # you can even redirect print() output to a file: +# newfile = open("printoutput.txt", "w") +# print(*values, sep=" -- ", file=newfile, flush=True) # pprint() can be used to print more complex data @@ -28,6 +32,7 @@ { "game": "Semifinal", "Attendance" : 68294, "France" : 2, "Morocco" : 0}, { "game": "Semifinal", "Attendance" : 88966, "Argentina" : 3, "Croatia" : 0} ] +#pprint.pp(worldcupdata, indent=3, width=40, underscore_numbers=True) # pprint also works on newer complex structures, like dataclasses! @@ -45,3 +50,5 @@ class wcdata: wcdata("Semifinal", 68294, "France" , "Morocco" , "2 -- 0" ), wcdata("Semifinal", 88966, "Argentina" , "Croatia" , "3 -- 0" ), ] + +pprint.pp(worldcupdata2) diff --git a/Start/1. PythonFeatures/pyscope.py b/Start/1. PythonFeatures/pyscope.py index 0326cd8..9d64010 100644 --- a/Start/1. PythonFeatures/pyscope.py +++ b/Start/1. PythonFeatures/pyscope.py @@ -1,14 +1,37 @@ -# Example file for Advanced Python by Joe Marini -# Understanding Python scope +# # Example file for Advanced Python by Joe Marini +# # Understanding Python scope -# declare a variable within the global scope +# # declare a variable within the global scope +# x=1 +# # define a local function with a variable "x" +# def test(): +# global x +# x=10 +# print(f"x inside function is: {x}") -# define a local function with a variable "x" +# # Run the test function and observe the two results +# test() +# print(x) +# x=x+5 +# print(x) +# test() -# Run the test function and observe the two results +# Nested functions create inner scopes. These are called closures: +def multipler_maker(factor): + def multiplier(number): + return number * factor + return multiplier +# Create a multiplier function that multiplies by 2 +doubler = multipler_maker(2) +# Create a multiplier function that multiplies by 3 +tripler = multipler_maker(3) + +print(doubler(10)) +print(doubler(15)) +print(tripler(10)) +print(tripler(15)) -# Nested functions create inner scopes. These are called closures: diff --git a/Start/1. PythonFeatures/specialnames.py b/Start/1. PythonFeatures/specialnames.py index 9e677ef..16cf31f 100644 --- a/Start/1. PythonFeatures/specialnames.py +++ b/Start/1. PythonFeatures/specialnames.py @@ -1,11 +1,15 @@ # Example file for Advanced Python by Joe Marini # Using special module names - - # __name__ is the name of the module - +import collections +print("Module name is: " + __name__) # __file__ contains the path to the file from which the module was loaded - +print("File path is: " + __file__) # __package__ indicates the package that the module belongs to. +print("Package is: " + str(__package__)) +print("Collections package is: " + str(collections.__package__)) + +if __name__ == "__main__": + print("This is the main module") \ No newline at end of file diff --git a/Start/2. Iterators/basic_iterators.py b/Start/2. Iterators/basic_iterators.py index 36a73fe..6114269 100644 --- a/Start/2. Iterators/basic_iterators.py +++ b/Start/2. Iterators/basic_iterators.py @@ -6,11 +6,17 @@ daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"] # use regular interation over the days -for d in days: - print(d) +# for d in days: +# print(d) # use iter() to create an iterator over a collection # the next() function retrieves the next value from an iterator - +# i = iter(days) +# print(next(i)) +# print(next(i)) +# print(next(i)) # iterate using a function and a sentinel +with open("testfile.txt", "r") as f: + for line in iter(f.readline, ""): + print(line) diff --git a/Start/2. Iterators/for_else.py b/Start/2. Iterators/for_else.py index 861171c..2e8736b 100644 --- a/Start/2. Iterators/for_else.py +++ b/Start/2. Iterators/for_else.py @@ -9,11 +9,24 @@ def findname(target): if name == target: print("Name found"); return True - - print("Name not found") - return False + else: + print("Name not found") + return False -print(findname("Creed")) -print(findname("Tom")) +# print(findname("Creed")) +# print(findname("Tom")) # Check if a number is prime +def is_prime(num): + if num < 2: + return False + for i in range(2, num): + if num % i == 0: + print(f"{num} is not a prime number because it is divisible by {i}") + return False + else: + print(f"{num} is a prime number") + return True + +print(is_prime(17)) +print(is_prime(18)) diff --git a/Start/2. Iterators/itertools1.py b/Start/2. Iterators/itertools1.py index 87a5a43..4a311cf 100644 --- a/Start/2. Iterators/itertools1.py +++ b/Start/2. Iterators/itertools1.py @@ -7,14 +7,27 @@ names = ["Joe", "Jane", "Jim"] # cycle iterator can be used to cycle over a collection infinitely - +# cycler = itertools.cycle(names) +# print(next(cycler)) +# print(next(cycler)) +# print(next(cycler)) +# print(next(cycler)) # use count to create a simple counter +counter = itertools.count(100,10) +# print(next(counter)) +# print(next(counter)) +# print(next(counter)) # accumulate creates an iterator that accumulates values vals = [10,20,30,40,50,40,30] - +acc = itertools.accumulate(vals) +#print(list(acc)) # amortize a loan over a set number of payments for a 2000 loan at 4% payments = [100, 125, 200, 105, 100, 120, 110, 130, 150, 100, 110, 120] +update = lambda balance,payment: round(balance * 1.04) - payment +balances = itertools.accumulate(payments, update, initial=2_000) +print(list(balances)) + diff --git a/Start/2. Iterators/itertools2.py b/Start/2. Iterators/itertools2.py index 9647b3a..c3344c3 100644 --- a/Start/2. Iterators/itertools2.py +++ b/Start/2. Iterators/itertools2.py @@ -5,12 +5,19 @@ # chain() creates a single iterable from multiple - +x = itertools.chain('ABCDEFG', [1,2,3,4,5], ['$','%','@','&']) +#print(list(x)) # make a prepend function +def prepend(value, iterator): + # use chain to prepend the value to the front of the iterator + return itertools.chain([value], iterator) +#print(list(prepend(0, [1,2,3,4,5]))) # chain.from_iterable is an alternate usage of chain s1 = "ABCDEFG" s2 = [1,2,3,4,5] s3 = ['$','%','@','&'] +result = itertools.chain.from_iterable([s1, s2, s3]) +print(list(result)) \ No newline at end of file diff --git a/Start/2. Iterators/itertools3.py b/Start/2. Iterators/itertools3.py index 3e886d9..70ac559 100644 --- a/Start/2. Iterators/itertools3.py +++ b/Start/2. Iterators/itertools3.py @@ -10,19 +10,19 @@ # dropwhile and takewhile will return values until # a certain condition is met that stops them - - +def testFunction(x): + return x < 40 # dropwhile() drops values until the predicate expression is True - +#print(list(itertools.dropwhile(testFunction, vals))) # takewhile() is the opposite of dropwhile() - it returns values from # the iterable while the predicate is True, then stops - +#print(list(itertools.takewhile(testFunction, vals))) # filterfalse() returns elements from the iterable for which the predicate # function returns False. - - +result = itertools.filterfalse(lambda x: x % 2 != 0, vals) +#print(list(result)) # These functions can work on complex objects @dataclass class wcdata: @@ -31,10 +31,11 @@ class wcdata: team1: str team2: str score: str - worldcupdata = [ wcdata("Final", 88966, "Argentina" , "France" , "3 (4) -- 3 (2)" ), wcdata("3rd Place", 44137, "Croatia" , "Morocco" , "2 -- 1" ), wcdata("Semifinal", 68294, "France" , "Morocco" , "2 -- 0" ), wcdata("Semifinal", 88966, "Argentina" , "Croatia" , "3 -- 0" ), ] +result = itertools.filterfalse(lambda x: x.attendance > 80000, worldcupdata) +pprint.pp(list(result)) \ No newline at end of file diff --git a/Start/2. Iterators/itertools4.py b/Start/2. Iterators/itertools4.py index 25b6441..9776352 100644 --- a/Start/2. Iterators/itertools4.py +++ b/Start/2. Iterators/itertools4.py @@ -7,13 +7,27 @@ # product() produces the cartesian product of input iterables cards = "A23456789TJQK" suits = "SCHD" +deck = list(itertools.product(cards, suits)) +# print(f"No.of cards: {len(deck)} cards ") +# print(f"Cards: {deck}") # permutations() creates tuples of a given length with no repeated elements teams = ("A","B","C","D") - +result = itertools.permutations(teams, 2) +permutation_list = list(result) +#print(f"Permutations: {permutation_list}") +#print(f"No. of Permutations: {len(permutation_list)} ") # combinations() will create combinations of a given length with no repeats +result = itertools.combinations("ABCD", 3) +combination_list = list(result) +#print(f"Combinations: {combination_list}") +#print(f"No. of Combinations: {len(combination_list)} ") # combinations_with_replacement() will create combinations of a given length with repeats +result = itertools.combinations_with_replacement("ABCD", 3) +combination_list = list(result) +print(f"Combinations with replacement: {combination_list}") +print(f"No. of Combinations with replacement: {len(combination_list)} ") \ No newline at end of file diff --git a/Start/2. Iterators/more_iterators.py b/Start/2. Iterators/more_iterators.py index 25e2e82..8f1ba14 100644 --- a/Start/2. Iterators/more_iterators.py +++ b/Start/2. Iterators/more_iterators.py @@ -1,21 +1,31 @@ # Example file for Advanced Python by Joe Marini - +import itertools # define a list of days in English and French days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] -daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"] +daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven"]#, "Sam"] +# for d in range(len(days)): +# print(d+1, days[d]) # the enumerate function - +# for i,d in enumerate(days): +# print(i+1, d) + # use zip to combine sequences +# for d in zip(days, daysFr): +# print(d) - -# use enumerate and zip together - +# # use enumerate and zip together +# for i,d in enumerate(zip(days, daysFr), start=1): +# print(i, d[0], '=', d[1], "in French") # use zip_longest seq1 = ["A","B","C","D","E","F"] seq2 = [1, 2, 3, 4] seq3 = "xyz" - \ No newline at end of file + +result = itertools.zip_longest(seq1, seq2, seq3, fillvalue="-") +print("Result:") +for item in result: + print(item) diff --git a/Start/3. Strings/Author_solution b/Start/3. Strings/Author_solution new file mode 100644 index 0000000..18bc603 --- /dev/null +++ b/Start/3. Strings/Author_solution @@ -0,0 +1,37 @@ +# Python code​​​​​​‌‌‌‌‌​‌‌‌‌​‌​‌​‌‌​‌‌‌​‌​‌ below +# Use print("messages...") to debug your solution. + +import string + +show_expected_result = True +show_hints = True + +test_string= "The quick, brown 'fox' jumps OVER the lazy dog; dog not impressed!" +search_term = "Fox" +def process_string(the_str, term): + # Your code goes here + result={ + "Punctuation": 0, + "Whitespace": 0, + "Uppercase": 0, + "Lowercase": 0, + "Found": False, + "Index": -1 + } + for c in the_str: + if c in string.punctuation: + result["Punctuation"] += 1 + elif c in string.ascii_lowercase: + result["Lowercase"] +=1 + elif c in string.ascii_uppercase: + result["Uppercase"] += 1 + elif c.isspace(): + result["Whitespace"] += 1 + + result["Index"] = the_str.upper().find(term.upper()) + result["Found"] = result["Index"] > 0 + + + return result + +print(process_string(test_string,search_term)) \ No newline at end of file diff --git a/Start/3. Strings/builtin_constants.py b/Start/3. Strings/builtin_constants.py index 5195da3..ff86375 100644 --- a/Start/3. Strings/builtin_constants.py +++ b/Start/3. Strings/builtin_constants.py @@ -1,31 +1,41 @@ # Example file for Advanced Python by Joe Marini # Using the built-in string constants - import string - - +import secrets # built-in constants for a variety of needs -print(string.ascii_letters) -print(string.ascii_lowercase) -print(string.ascii_uppercase) -print(string.digits) -print(string.hexdigits) -print(string.punctuation) + # print(string.ascii_letters) + # print(string.ascii_lowercase) + # print(string.ascii_uppercase) + # print(string.digits) + # print(string.hexdigits) + # print(string.punctuation) # Define a test string testStr = "The quick brown fox jumps OVER the lazy dog." # use an iterator to see if a string contains any punctuation - +if any(c in string.punctuation for c in testStr): + print("The string contains punctuation.") +else: + print("The string does not contain punctuation.") # generate a secure random password - +alphabet = string.ascii_letters + string.digits + string.punctuation +password = "".join(secrets.choice(alphabet) for i in range(10)) +print(f"Generated password: {password}") # Check the strength of a password def check_password_strength(testPass): - pass - -# print(check_password_strength("MyTestPa$$123!")) -# print(check_password_strength("password")) -# print(check_password_strength("pa$$w0rd!")) + if(len(testPass) <= 10 and + any(char in string.punctuation for char in testPass) and + any(char in string.digits for char in testPass) and + any(char in string.ascii_letters for char in testPass)): + return f"{testPass} is strong password." + else: + return f"{testPass} is weak password." + + +print(check_password_strength("MyTestPa$$123!")) +print(check_password_strength("password")) +print(check_password_strength("pa$$w0rd!")) diff --git a/Start/3. Strings/string_format.py b/Start/3. Strings/string_format.py index 44df4a0..602be08 100644 --- a/Start/3. Strings/string_format.py +++ b/Start/3. Strings/string_format.py @@ -2,7 +2,10 @@ # Formatting output strings # Basic formatting - center(), ljust(), rjust() - +width = 20 +# print("Center".center(width, "*")) +# print("Left".ljust(width, "-")) +# print("Right".rjust(width, "+")) # Formatting strings with format specification codes # Format spec is: [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["."precision][type] val1 = 1234.5678 @@ -10,24 +13,42 @@ val3 = 12.99 val4 = -280.7 -# print(f"{val1}") -# print(f"{val2}") -# print(f"{val3}") -# print(f"{val4}") +# print(f"{val1:.2f}") +# print(f"{val2:.2f}") +# print(f"{val3:.2f}") +# print(f"{val4:.2f}") # Specify a precision and type +# print(f"{val1:.2e}") +# print(f"{val2:.2e}") +# print(f"{val3:.2e}") +# print(f"{val4:.2e}") # Use alignment and width and leading zeros # < is left align, > is right align, ^ is centered - +# print(f"{val1:<010.2f}") +# print(f"{val2:>010.2f}") +# print(f"{val3:^010.2f}") +# print(f"{val4:0>010.2f}") # Use a grouping option and +/- signs +# print(f"{val1:>-10,.2f}") +# print(f"{val2:>+10.2f}") # Insert a fill character +# print(f"{val1:_>10.2f}") +# print(f"{val2:_>10.2f}") +# print(f"{val3:_>10.2f}") +# print(f"{val4:_>10.2f}") # Create format specifiers dynamically width = 10 precision = 2 +# format_spec = f"{123.456:{width}.{precision}f}" +# print(format_spec) + +format_spec = "{val:{width}.{precision}f}".format(val=val1,width=10,precision=2) +print(format_spec) diff --git a/Start/3. Strings/string_manipulation.py b/Start/3. Strings/string_manipulation.py index befbcc8..c35380d 100644 --- a/Start/3. Strings/string_manipulation.py +++ b/Start/3. Strings/string_manipulation.py @@ -5,14 +5,24 @@ test_str = "The quick, brown fox jumps over the lazy dog." # upper, lower, title - +# print("upper:", test_str.upper()) +# print("lower:", test_str.lower()) +# print("title:", test_str.title()) # strip, lstrip, rstrip -test_str2 = " This string has whitespace " +# test_str2 = " This string has whitespace " +# print("stripped:", test_str2.strip()) +# print("lstrip:", test_str2.lstrip()) +# print("rstrip:", test_str2.rstrip()) # split creates a sequence from a single string - +test_str3 = "The quick, brown fox jumps over the lazy dog." +# print("split:", test_str3.split()) +# print("split with comma:", test_str3.split(",")) # join concatenates an iterable into a single string words = ["Hello", "world", "from", "Python"] +seperator = "--" +sentence = seperator.join(words) +print("Joined string:", sentence) \ No newline at end of file diff --git a/Start/3. Strings/string_search.py b/Start/3. Strings/string_search.py index 3fcc71b..9c2c741 100644 --- a/Start/3. Strings/string_search.py +++ b/Start/3. Strings/string_search.py @@ -1,25 +1,23 @@ # Example file for Advanced Python by Joe Marini - - sample_text = "The quick brown fox jumps over the lazy dog." - +tempstr = sample_text.lower() # Using find() to find the first occurrence of a substring - - +#print("First occurrence of 'the':", tempstr.find("the",5,36)) # Example with optional start and end parameters - - # Using index() to find the first occurrence of a substring (raises ValueError if not found) - - +# try: +# print("First occurrence of 'fox':", tempstr.index("fax")) +# except ValueError: +# print("Substring not found.") # The 'in' operator can be used for Boolean testing: - - +#print("Is 'dog' in the string?", "dog" in tempstr) # Using rfind() to find the last occurrence of a substring - - +#print("Last occurrence of 'the':", tempstr.rfind("the")) # Using rindex() to find the last occurrence of a substring (raises ValueError if not found) - - +#print("Last occurrence of 'jump':", tempstr.rindex("jump")) # The replace() function will find content in the string and replace it +replace = sample_text.replace("lazy", "tired") +print("After replacement:", replace) +result = tempstr.replace("the", "THE") +print("After replacement:", result) \ No newline at end of file diff --git a/Start/3. Strings/test b/Start/3. Strings/test new file mode 100644 index 0000000..cc6e9f7 --- /dev/null +++ b/Start/3. Strings/test @@ -0,0 +1,41 @@ +# Python code​​​​​​‌‌‌‌‌​‌‌‌‌​‌​‌​‌‌​‌‌‌​‌​‌ below +# Use print("messages...") to debug your solution. + +import string + +show_expected_result = True +show_hints = True + +test_string= "The quick, brown 'fox' jumps OVER the lazy dog; dog not impressed!" +search_term = "Fox" +def process_string(the_str, term): + # Your code goes here + punch=0 + upper=0 + lower=0 + whitespace=0 + + for c in the_str: + if c in string.punctuation: + punch += 1 + elif c in string.ascii_lowercase: + lower +=1 + elif c in string.ascii_uppercase: + upper+= 1 + elif c.isspace(): + whitespace += 1 + + found = (term.lower() in the_str.lower()) + index= the_str.lower().find(term.lower()) + + dic = {"Punctuation": punch, + "Whitespace": whitespace, + "Uppercase": upper, + "Lowercase": lower, + "Found":found, + "Index": index + } + #print(dic) + return dic + +print(process_string(test_string,search_term)) \ No newline at end of file diff --git a/Start/4. Sequences/dict_comprehensions.py b/Start/4. Sequences/dict_comprehensions.py index 1a62f1f..0449b2d 100644 --- a/Start/4. Sequences/dict_comprehensions.py +++ b/Start/4. Sequences/dict_comprehensions.py @@ -5,8 +5,11 @@ ctemps = [0, 12, 34, 100] # Use a comprehension to build a dictionary - - +tempDict = {t: (t * 9 / 5) + 32 for t in ctemps if t < 100} +# print(tempDict) +# print(tempDict[34]) # Merge two dictionaries with a comprehension team1 = {"Jones": 24, "Jameson": 18, "Smith": 58, "Burns": 7} team2 = {"White": 12, "Macke": 88, "Perce": 4} +newteam = {k:v for team in (team1, team2) for k,v in team.items()} +print(newteam) \ No newline at end of file diff --git a/Start/4. Sequences/list_comprehensions.py b/Start/4. Sequences/list_comprehensions.py index b907f07..ade4fda 100644 --- a/Start/4. Sequences/list_comprehensions.py +++ b/Start/4. Sequences/list_comprehensions.py @@ -1,15 +1,18 @@ # Example file for Advanced Python by Joe Marini # Demonstrate how to use list comprehensions - # define two lists of numbers evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] # Perform a mapping and filter function on a list using built-in functions - +evenSquared = list(map(lambda x: x**2,filter(lambda x: x>4 and x<=16, evens))) +#print(evenSquared) # Derive a new list of numbers frm a given list - +evenSquared = [x**2 for x in evens] +#print(evenSquared) # Limit the items operated on with a predicate condition +oddSquared = [x**2 for x in odds if x>3 and x<=17] +print(oddSquared) diff --git a/Start/4. Sequences/sequence_compare.py b/Start/4. Sequences/sequence_compare.py index 4746f42..80dc5c9 100644 --- a/Start/4. Sequences/sequence_compare.py +++ b/Start/4. Sequences/sequence_compare.py @@ -7,19 +7,19 @@ # define some lists seq1 = [1, 2, 3, 6, 10, 15, 34, 56] seq2 = [1, 2, 5, 7, 9, 18, 22, 38, 91] - # define a tuple seq3 = (1, 2, 3, 6, 10, 15, 34, 56) - # compare the sequences - - +# print(seq1 == seq2) # False +# print(seq1 > seq2) # False, different types +# print(seq1 < seq2) # True, different types but seq1 is "less than" seq2 because it has fewer items # sequences that have equal values but different number of items: seq4 = [10, 20, 30] seq5 = [10, 20, 30, 40, 50] - - +#print(seq5 > seq4) # True, because seq5 has more items than seq4 # Sequences must be of the same type to be compared - - +print(tuple(seq1) == seq3) # False, different types # use the all() function to compare two arbitrary sequences +result = all(x == y for x, y in itertools.zip_longest(seq1, seq3)) +print(result) + diff --git a/Start/4. Sequences/sequence_slicing.py b/Start/4. Sequences/sequence_slicing.py index 507c90d..241ff36 100644 --- a/Start/4. Sequences/sequence_slicing.py +++ b/Start/4. Sequences/sequence_slicing.py @@ -4,24 +4,34 @@ from collections import deque names = ["Jim", "Pam", "Creed", "Michael", "Dwight", "Oscar", "Kevin", "Phyllis"] - +print("original list:", names) # a slice is a subset of a sequence. The form is [start:stop:step] - +#print(names[2:5]) # from index 2 to 4 # using a step - +#print(names[0:7:2]) # every second element # shorthand - +#print(names[:5]) # from the beginning to index 4 +#print(names[5:]) # from index 5 to the end # reversing with step of -1 - +#print(names[::-1]) # from the end to the beginning # assigning sequences - +newnames = ["Goms","Keisha","Vicky"] +names[2:5] = newnames # replaces the slice with the new sequence +#print(names) # the del operator works with slices +del names[2:5] # removes the slice from the list +#print(names) # not all sequence types support slicing, however deque_names = deque(["Jim", "Pam", "Creed", "Michael", "Dwight", "Oscar", "Kevin", "Phyllis"]) +for name in deque_names: + print(name,"", end="") +print() +print(len(deque_names)) +print(deque_names[2:5]) # this will raise an error because deque does not support slicing \ No newline at end of file diff --git a/Start/4. Sequences/set_comprehensions.py b/Start/4. Sequences/set_comprehensions.py index 93406c7..777bc93 100644 --- a/Start/4. Sequences/set_comprehensions.py +++ b/Start/4. Sequences/set_comprehensions.py @@ -5,7 +5,12 @@ ctemps = [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29] # build a set of unique Fahrenheit temperatures - +ftemps1 = [(t * 9 / 5) + 32 for t in ctemps] +ftemps2 = {(t * 9 / 5) + 32 for t in ctemps} +# print(ftemps1) +# print(ftemps2) # build a set from an input source sTemp = "The quick brown fox jumped over the lazy dog" +cupper = {c.upper() for c in sTemp if not c.isspace()} +print(cupper) diff --git a/Start/4. Sequences/test.py b/Start/4. Sequences/test.py new file mode 100644 index 0000000..46bde5a --- /dev/null +++ b/Start/4. Sequences/test.py @@ -0,0 +1,14 @@ +# Python code​​​​​​‌‌‌‌‌‌​​‌​​​‌‌‌​​​​​​​‌​‌ below +# Use print("messages...") to debug your solution. + +import string +show_expected_result = True +show_hints = True +the_str = "Mary, Mary, quite contrary -- how _does_ your garden grow?" + +def build_punctuation_set(the_str): + # Your code goes here + punc = {c for c in the_str if c in string.punctuation} + return punc + +print(build_punctuation_set(the_str)) \ No newline at end of file diff --git a/Start/5. Exceptions/basic_exceptions.py b/Start/5. Exceptions/basic_exceptions.py index 3d3fead..96f03f6 100644 --- a/Start/5. Exceptions/basic_exceptions.py +++ b/Start/5. Exceptions/basic_exceptions.py @@ -3,8 +3,17 @@ # Try to execute some code that might cause an exception: -num = input("Enter the first number: ") -denom = input("Enter the second numnber: ") -n = int(num) -d = int(denom) -print(n/d) +try: + num = input("Enter the first number: ") + denom = input("Enter the second number: ") + n = int(num) + d = int(denom) + result = n/d +except ZeroDivisionError as e: + print("You can't divide by zero!", e) +except ValueError as e: + print("You must enter a valid number!", e) +else: + print("The result is", result) +finally: + print("Thanks for using the program!") \ No newline at end of file diff --git a/Start/5. Exceptions/challenge.py b/Start/5. Exceptions/challenge.py index 22d2b9f..99ad404 100644 --- a/Start/5. Exceptions/challenge.py +++ b/Start/5. Exceptions/challenge.py @@ -2,13 +2,19 @@ # Programming challenge for working with Exceptions # Implement the InvalidTempError exception class here - +class InvalidTempError(Exception): + """Raised when an attempt is made to set the oven temperature outside the valid range.""" + def __init__(self, temp): + message = f"Invalid temperature setting: {temp} degrees. Valid range is 100-500 degrees." + super().__init__(message) class DigitalOven: def __init__(self): self.temp = 0 def set_temp(self, temp): + if (temp < 100 or temp > 500) and temp != 0: + raise InvalidTempError(temp) self.temp = temp def get_temp(self): @@ -18,6 +24,10 @@ def test_oven(test_temp): global oven try: oven.set_temp(test_temp) + except InvalidTempError as e: + print(f"Error: {e}") + else: + print(f"New Oven temperature set to {oven.get_temp()} degrees.") finally: print(f"Current temp setting is {oven.get_temp()}") diff --git a/Start/5. Exceptions/common_exceptions.py b/Start/5. Exceptions/common_exceptions.py index a6630c0..5cc62ed 100644 --- a/Start/5. Exceptions/common_exceptions.py +++ b/Start/5. Exceptions/common_exceptions.py @@ -3,15 +3,20 @@ # IndexError occurs when you try to access an index that is out of range int_list = [0,3,6,1,8,7,3,5] - +#print(int_list["A"]) # This will raise a TypeError because list indices must be integers or slices, not str # KeyError is similar - it is raised when a key is not found in a Dictionary my_dict = {1: "one", 2: "two", 3: "three"} - +#print(my_dict[4]) # This will raise a KeyError because the key 4 is not in the dictionary # FileNotFoundError is raised when you try to access a file that doesn't exist - +# with open("non_existent_file.txt", "r") as f: +# contents = f.read() # This will raise a FileNotFoundError because the file does not exist # FileExistsError is raised when a file or directory already exists +import os + +#os.mkdir("test_dir") # This will create a directory named "test_dir" # NotADirectoryError is raised when try to perform a dir operation on a non-dir object +os.listdir("myfile.txt") diff --git a/Start/5. Exceptions/custom_exceptions.py b/Start/5. Exceptions/custom_exceptions.py index 63be026..09ab867 100644 --- a/Start/5. Exceptions/custom_exceptions.py +++ b/Start/5. Exceptions/custom_exceptions.py @@ -2,6 +2,11 @@ # Defining and using custom exceptions in Python # Define a custom exception class +class InsufficientFundsError(Exception): + """Raised when an attempt is made to withdraw more money than is available in the account.""" + def __init__(self,balance, amount): + message=f"Insufficient funds in the account: Available balance is ${balance:.2f}, attempted withdrawal is ${amount:.2f}" + super().__init__(message) class BankAccount: @@ -12,6 +17,8 @@ def deposit(self, amount): self.balance += amount def withdraw(self, amount): + if amount > self.balance: + raise InsufficientFundsError(self.balance, amount) self.balance -= amount def get_balance(self): @@ -26,5 +33,7 @@ def get_balance(self): account.withdraw(50) # Attempt to withdraw $100, which exceeds the balance account.withdraw(100) +except InsufficientFundsError as e: + print(f"Error: {e}") finally: print(f"Current balance: ${account.get_balance():.2f}") diff --git a/Start/5. Exceptions/myfile.txt b/Start/5. Exceptions/myfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/printoutput.txt b/printoutput.txt new file mode 100644 index 0000000..364d218 --- /dev/null +++ b/printoutput.txt @@ -0,0 +1 @@ +one -- two -- three -- four -- five