From 8410af9a731050f2c965259b21ad226667609f6c Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 19:11:15 +0800 Subject: [PATCH 01/16] Add src and tests directory and Make module file --- projects/Calculate Age/calculate.py | 2 ++ projects/Calculate Age/src/__init__.py | 0 projects/Calculate Age/src/calculate_age.py | 0 projects/Calculate Age/src/main.py | 0 projects/Calculate Age/src/utilize_date.py | 0 projects/Calculate Age/test_calculate.py | 3 ++- projects/Calculate Age/tests/__init__.py | 0 projects/Calculate Age/tests/test_calculate_age.py | 0 projects/Calculate Age/tests/test_utilize_date.py | 0 9 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 projects/Calculate Age/src/__init__.py create mode 100644 projects/Calculate Age/src/calculate_age.py create mode 100644 projects/Calculate Age/src/main.py create mode 100644 projects/Calculate Age/src/utilize_date.py create mode 100644 projects/Calculate Age/tests/__init__.py create mode 100644 projects/Calculate Age/tests/test_calculate_age.py create mode 100644 projects/Calculate Age/tests/test_utilize_date.py diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py index a7dc34fa..2f56e381 100644 --- a/projects/Calculate Age/calculate.py +++ b/projects/Calculate Age/calculate.py @@ -47,3 +47,5 @@ def month_days(month, leap_year): day = day + localtime.tm_mday print("%s's age is %d years or " % (name, year), end="") print("%d months or %d days" % (month, day)) + + diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py new file mode 100644 index 00000000..e69de29b diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py new file mode 100644 index 00000000..e69de29b diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py new file mode 100644 index 00000000..e69de29b diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/test_calculate.py index 369ac65f..4cfa3e02 100644 --- a/projects/Calculate Age/test_calculate.py +++ b/projects/Calculate Age/test_calculate.py @@ -17,4 +17,5 @@ def test_month_days(): assert month_days(1, False) == 31 assert month_days(11, True) == 30 -# "pytest -s test_calculate.py" to test this file \ No newline at end of file +# "pytest -s test_calculate.py" to test this file + diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py new file mode 100644 index 00000000..e69de29b diff --git a/projects/Calculate Age/tests/test_utilize_date.py b/projects/Calculate Age/tests/test_utilize_date.py new file mode 100644 index 00000000..e69de29b From 12b0bd567a032f9adb9d297533fc83b61758ce36 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 19:15:26 +0800 Subject: [PATCH 02/16] Add modifiy code in each module --- projects/Calculate Age/src/calculate_age.py | 31 +++++++++++++++++++++ projects/Calculate Age/src/main.py | 25 +++++++++++++++++ projects/Calculate Age/src/utilize_date.py | 19 +++++++++++++ 3 files changed, 75 insertions(+) diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py index e69de29b..76ca7486 100644 --- a/projects/Calculate Age/src/calculate_age.py +++ b/projects/Calculate Age/src/calculate_age.py @@ -0,0 +1,31 @@ +import time +from utilize_date import judge_leap_year, month_days + + +def age_calculator(name, age): + localtime = time.localtime(time.time()) + + year = int(age) + month = year * 12 + localtime.tm_mon + day = 0 + + begin_year = int(localtime.tm_year) - year + end_year = begin_year + year + + for y in range(begin_year, end_year): + if judge_leap_year(y): + day += 366 + else: + day += 365 + + leap_year = judge_leap_year(localtime.tm_year) + for m in range(1, localtime.tm_mon): + day += month_days(m, leap_year) + + day += localtime.tm_mday + + return f"{name}'s age is {year} years or {month} months or {day} days" + + + + diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py index e69de29b..b655a716 100644 --- a/projects/Calculate Age/src/main.py +++ b/projects/Calculate Age/src/main.py @@ -0,0 +1,25 @@ +from calculate_age import age_calculator + + +def main(): + input_name = input("input your name: ") + + while True: + input_age = input("input your age: ") + try: + string_to_int_age = int(input_age) + if string_to_int_age <= 0: + print("Please input a positive number.") + else: + break + except ValueError: + print("Please input a valid age.") + + result = age_calculator(input_name, string_to_int_age) + + print(result) + +if __name__ == "__main__": + main() + + diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py index e69de29b..d56d97b1 100644 --- a/projects/Calculate Age/src/utilize_date.py +++ b/projects/Calculate Age/src/utilize_date.py @@ -0,0 +1,19 @@ +from calendar import isleap + + +def judge_leap_year(year): + if isleap(year): + return True + else: + return False + + +def month_days(month, leap_year): + if month in [1, 3, 5, 7, 8, 10, 12]: + return 31 + elif month in [4, 6, 9, 11]: + return 30 + elif month == 2 and leap_year: + return 29 + elif month == 2 and (not leap_year): + return 28 From f6ca789482454981c2f9d9708b81f7bd50e6fa67 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 19:18:16 +0800 Subject: [PATCH 03/16] Documentation: Add docstring in each module --- projects/Calculate Age/src/calculate_age.py | 11 +++++++++++ projects/Calculate Age/src/main.py | 10 ++++++++++ projects/Calculate Age/src/utilize_date.py | 17 +++++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py index 76ca7486..193fb64e 100644 --- a/projects/Calculate Age/src/calculate_age.py +++ b/projects/Calculate Age/src/calculate_age.py @@ -3,6 +3,17 @@ def age_calculator(name, age): + """ + Calculate user's age in years, month, and days + based on current date and print. + + Args: + name (str): user's name. + age (int): user's age in years. + + Returns: + None. + """ localtime = time.localtime(time.time()) year = int(age) diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py index b655a716..b7752356 100644 --- a/projects/Calculate Age/src/main.py +++ b/projects/Calculate Age/src/main.py @@ -2,6 +2,16 @@ def main(): + """ + the user to input name and age, validate input, + and calculates and displays the user age in years, months and days. + + Args: + None. + + Return: + None. + """ input_name = input("input your name: ") while True: diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py index d56d97b1..8d8b129c 100644 --- a/projects/Calculate Age/src/utilize_date.py +++ b/projects/Calculate Age/src/utilize_date.py @@ -2,6 +2,14 @@ def judge_leap_year(year): + """ + judge the leap year. + + Args: + year (int): To check the year. + return: + bool: Ture if the year is a leap year, False otherwise. + """ if isleap(year): return True else: @@ -9,6 +17,15 @@ def judge_leap_year(year): def month_days(month, leap_year): + """ + Returns the number of days in each month + + Args: + month (int): The month 1-12. + + Returns: + int: The number of days in the month. + """ if month in [1, 3, 5, 7, 8, 10, 12]: return 31 elif month in [4, 6, 9, 11]: From 9675b1f0049a2e423c49dc35e642101b2c90947a Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 19:21:49 +0800 Subject: [PATCH 04/16] Add test-code in each test module --- .../Calculate Age/tests/test_calculate_age.py | 25 +++++++++++++++++++ .../Calculate Age/tests/test_utilize_date.py | 18 +++++++++++++ 2 files changed, 43 insertions(+) diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py index e69de29b..af0c07ba 100644 --- a/projects/Calculate Age/tests/test_calculate_age.py +++ b/projects/Calculate Age/tests/test_calculate_age.py @@ -0,0 +1,25 @@ +import time +from unittest.mock import patch +from calculate_age import age_calculator + +@patch('time.time', return_value=1621848668.0) +def test_age_calculator(mock_time): + name = "Chloe" + age = 30 + expect_output = "Chloe's age is 30 years or 365 months or 11102 days" + assert age_calculator(name, age) == expect_output + +def test_age_calculator_negative_age(): + name = "Emma" + age = -5 + try: + age_calculator(name, age) + except ValueError as e: + assert str(e) == "Please input a positive number." + + +def test_age_calculator_leap_year(): + name = "David" + age = 30 + expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" + assert age_calculator(name, age) == expect_output_leap_year diff --git a/projects/Calculate Age/tests/test_utilize_date.py b/projects/Calculate Age/tests/test_utilize_date.py index e69de29b..d0b74c26 100644 --- a/projects/Calculate Age/tests/test_utilize_date.py +++ b/projects/Calculate Age/tests/test_utilize_date.py @@ -0,0 +1,18 @@ +import pytest +from utilize_date import judge_leap_year, month_days + +def test_judge_leap_year(): + assert judge_leap_year(2000) == True + assert judge_leap_year(2008) == True + assert judge_leap_year(2023) == False + assert judge_leap_year(1900) == False + assert judge_leap_year(2400) == True + assert judge_leap_year(2100) == False + +def test_month_days(): + assert month_days(7, False) == 31 + assert month_days(4, True) == 30 + assert month_days(2, True) == 29 + assert month_days(2, False) == 28 + assert month_days(1, False) == 31 + assert month_days(11, True) == 30 \ No newline at end of file From 6500d736ed535e250e136c4f1b34c8fa57317ed3 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 19:55:03 +0800 Subject: [PATCH 05/16] Add test command in test_utilize_date.py --- projects/Calculate Age/tests/test_utilize_date.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/projects/Calculate Age/tests/test_utilize_date.py b/projects/Calculate Age/tests/test_utilize_date.py index d0b74c26..70474d7f 100644 --- a/projects/Calculate Age/tests/test_utilize_date.py +++ b/projects/Calculate Age/tests/test_utilize_date.py @@ -1,6 +1,7 @@ import pytest from utilize_date import judge_leap_year, month_days + def test_judge_leap_year(): assert judge_leap_year(2000) == True assert judge_leap_year(2008) == True @@ -9,10 +10,13 @@ def test_judge_leap_year(): assert judge_leap_year(2400) == True assert judge_leap_year(2100) == False + def test_month_days(): assert month_days(7, False) == 31 assert month_days(4, True) == 30 assert month_days(2, True) == 29 assert month_days(2, False) == 28 assert month_days(1, False) == 31 - assert month_days(11, True) == 30 \ No newline at end of file + assert month_days(11, True) == 30 + +# "pytest -s test_calculate.py" to test this file From 4ac51d39e688904e9b1ff312d03207fd2f028873 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 20:00:52 +0800 Subject: [PATCH 06/16] modified test_utilize_date.py --- projects/Calculate Age/calculate.py | 51 ------------------- projects/Calculate Age/test_calculate.py | 21 -------- .../Calculate Age/tests/test_utilize_date.py | 3 +- 3 files changed, 2 insertions(+), 73 deletions(-) delete mode 100644 projects/Calculate Age/calculate.py delete mode 100644 projects/Calculate Age/test_calculate.py diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py deleted file mode 100644 index 2f56e381..00000000 --- a/projects/Calculate Age/calculate.py +++ /dev/null @@ -1,51 +0,0 @@ -import time -from calendar import isleap - - -# judge the leap year -def judge_leap_year(year): - if isleap(year): - return True - else: - return False - - -# returns the number of days in each month -def month_days(month, leap_year): - if month in [1, 3, 5, 7, 8, 10, 12]: - return 31 - elif month in [4, 6, 9, 11]: - return 30 - elif month == 2 and leap_year: - return 29 - elif month == 2 and (not leap_year): - return 28 - - -name = input("input your name: ") -age = input("input your age: ") -localtime = time.localtime(time.time()) - -year = int(age) -month = year * 12 + localtime.tm_mon -day = 0 - -begin_year = int(localtime.tm_year) - year -end_year = begin_year + year - -# calculate the days -for y in range(begin_year, end_year): - if judge_leap_year(y): - day = day + 366 - else: - day = day + 365 - -leap_year = judge_leap_year(localtime.tm_year) -for m in range(1, localtime.tm_mon): - day = day + month_days(m, leap_year) - -day = day + localtime.tm_mday -print("%s's age is %d years or " % (name, year), end="") -print("%d months or %d days" % (month, day)) - - diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/test_calculate.py deleted file mode 100644 index 4cfa3e02..00000000 --- a/projects/Calculate Age/test_calculate.py +++ /dev/null @@ -1,21 +0,0 @@ -import pytest -from calculate import judge_leap_year, month_days - -def test_judge_leap_year(): - assert judge_leap_year(2000) == True - assert judge_leap_year(2008) == True - assert judge_leap_year(2023) == False - assert judge_leap_year(1900) == False - assert judge_leap_year(2400) == True - assert judge_leap_year(2100) == False - -def test_month_days(): - assert month_days(7, False) == 31 - assert month_days(4, True) == 30 - assert month_days(2, True) == 29 - assert month_days(2, False) == 28 - assert month_days(1, False) == 31 - assert month_days(11, True) == 30 - -# "pytest -s test_calculate.py" to test this file - diff --git a/projects/Calculate Age/tests/test_utilize_date.py b/projects/Calculate Age/tests/test_utilize_date.py index 70474d7f..54e5efa0 100644 --- a/projects/Calculate Age/tests/test_utilize_date.py +++ b/projects/Calculate Age/tests/test_utilize_date.py @@ -19,4 +19,5 @@ def test_month_days(): assert month_days(1, False) == 31 assert month_days(11, True) == 30 -# "pytest -s test_calculate.py" to test this file + +# "pytest -s test_utilize_date.py" to test this file From dda7eb4c5cd69162d86e6334745f3f2be608898b Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 22 May 2024 20:16:44 +0800 Subject: [PATCH 07/16] Add feature-branch.diff --- feature-branch.diff | 254 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 feature-branch.diff diff --git a/feature-branch.diff b/feature-branch.diff new file mode 100644 index 00000000..79e44d46 --- /dev/null +++ b/feature-branch.diff @@ -0,0 +1,254 @@ +diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py +deleted file mode 100644 +index a7dc34f..0000000 +--- a/projects/Calculate Age/calculate.py ++++ /dev/null +@@ -1,49 +0,0 @@ +-import time +-from calendar import isleap +- +- +-# judge the leap year +-def judge_leap_year(year): +- if isleap(year): +- return True +- else: +- return False +- +- +-# returns the number of days in each month +-def month_days(month, leap_year): +- if month in [1, 3, 5, 7, 8, 10, 12]: +- return 31 +- elif month in [4, 6, 9, 11]: +- return 30 +- elif month == 2 and leap_year: +- return 29 +- elif month == 2 and (not leap_year): +- return 28 +- +- +-name = input("input your name: ") +-age = input("input your age: ") +-localtime = time.localtime(time.time()) +- +-year = int(age) +-month = year * 12 + localtime.tm_mon +-day = 0 +- +-begin_year = int(localtime.tm_year) - year +-end_year = begin_year + year +- +-# calculate the days +-for y in range(begin_year, end_year): +- if judge_leap_year(y): +- day = day + 366 +- else: +- day = day + 365 +- +-leap_year = judge_leap_year(localtime.tm_year) +-for m in range(1, localtime.tm_mon): +- day = day + month_days(m, leap_year) +- +-day = day + localtime.tm_mday +-print("%s's age is %d years or " % (name, year), end="") +-print("%d months or %d days" % (month, day)) +diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py +new file mode 100644 +index 0000000..e69de29 +diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py +new file mode 100644 +index 0000000..193fb64 +--- /dev/null ++++ b/projects/Calculate Age/src/calculate_age.py +@@ -0,0 +1,42 @@ ++import time ++from utilize_date import judge_leap_year, month_days ++ ++ ++def age_calculator(name, age): ++ """ ++ Calculate user's age in years, month, and days ++ based on current date and print. ++ ++ Args: ++ name (str): user's name. ++ age (int): user's age in years. ++ ++ Returns: ++ None. ++ """ ++ localtime = time.localtime(time.time()) ++ ++ year = int(age) ++ month = year * 12 + localtime.tm_mon ++ day = 0 ++ ++ begin_year = int(localtime.tm_year) - year ++ end_year = begin_year + year ++ ++ for y in range(begin_year, end_year): ++ if judge_leap_year(y): ++ day += 366 ++ else: ++ day += 365 ++ ++ leap_year = judge_leap_year(localtime.tm_year) ++ for m in range(1, localtime.tm_mon): ++ day += month_days(m, leap_year) ++ ++ day += localtime.tm_mday ++ ++ return f"{name}'s age is {year} years or {month} months or {day} days" ++ ++ ++ ++ +diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py +new file mode 100644 +index 0000000..b775235 +--- /dev/null ++++ b/projects/Calculate Age/src/main.py +@@ -0,0 +1,35 @@ ++from calculate_age import age_calculator ++ ++ ++def main(): ++ """ ++ the user to input name and age, validate input, ++ and calculates and displays the user age in years, months and days. ++ ++ Args: ++ None. ++ ++ Return: ++ None. ++ """ ++ input_name = input("input your name: ") ++ ++ while True: ++ input_age = input("input your age: ") ++ try: ++ string_to_int_age = int(input_age) ++ if string_to_int_age <= 0: ++ print("Please input a positive number.") ++ else: ++ break ++ except ValueError: ++ print("Please input a valid age.") ++ ++ result = age_calculator(input_name, string_to_int_age) ++ ++ print(result) ++ ++if __name__ == "__main__": ++ main() ++ ++ +diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py +new file mode 100644 +index 0000000..8d8b129 +--- /dev/null ++++ b/projects/Calculate Age/src/utilize_date.py +@@ -0,0 +1,36 @@ ++from calendar import isleap ++ ++ ++def judge_leap_year(year): ++ """ ++ judge the leap year. ++ ++ Args: ++ year (int): To check the year. ++ return: ++ bool: Ture if the year is a leap year, False otherwise. ++ """ ++ if isleap(year): ++ return True ++ else: ++ return False ++ ++ ++def month_days(month, leap_year): ++ """ ++ Returns the number of days in each month ++ ++ Args: ++ month (int): The month 1-12. ++ ++ Returns: ++ int: The number of days in the month. ++ """ ++ if month in [1, 3, 5, 7, 8, 10, 12]: ++ return 31 ++ elif month in [4, 6, 9, 11]: ++ return 30 ++ elif month == 2 and leap_year: ++ return 29 ++ elif month == 2 and (not leap_year): ++ return 28 +diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py +new file mode 100644 +index 0000000..e69de29 +diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py +new file mode 100644 +index 0000000..af0c07b +--- /dev/null ++++ b/projects/Calculate Age/tests/test_calculate_age.py +@@ -0,0 +1,25 @@ ++import time ++from unittest.mock import patch ++from calculate_age import age_calculator ++ ++@patch('time.time', return_value=1621848668.0) ++def test_age_calculator(mock_time): ++ name = "Chloe" ++ age = 30 ++ expect_output = "Chloe's age is 30 years or 365 months or 11102 days" ++ assert age_calculator(name, age) == expect_output ++ ++def test_age_calculator_negative_age(): ++ name = "Emma" ++ age = -5 ++ try: ++ age_calculator(name, age) ++ except ValueError as e: ++ assert str(e) == "Please input a positive number." ++ ++ ++def test_age_calculator_leap_year(): ++ name = "David" ++ age = 30 ++ expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" ++ assert age_calculator(name, age) == expect_output_leap_year +diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/tests/test_utilize_date.py +similarity index 83% +rename from projects/Calculate Age/test_calculate.py +rename to projects/Calculate Age/tests/test_utilize_date.py +index 369ac65..54e5efa 100644 +--- a/projects/Calculate Age/test_calculate.py ++++ b/projects/Calculate Age/tests/test_utilize_date.py +@@ -1,5 +1,6 @@ + import pytest +-from calculate import judge_leap_year, month_days ++from utilize_date import judge_leap_year, month_days ++ + + def test_judge_leap_year(): + assert judge_leap_year(2000) == True +@@ -9,6 +10,7 @@ def test_judge_leap_year(): + assert judge_leap_year(2400) == True + assert judge_leap_year(2100) == False + ++ + def test_month_days(): + assert month_days(7, False) == 31 + assert month_days(4, True) == 30 +@@ -17,4 +19,5 @@ def test_month_days(): + assert month_days(1, False) == 31 + assert month_days(11, True) == 30 + +-# "pytest -s test_calculate.py" to test this file +\ No newline at end of file ++ ++# "pytest -s test_utilize_date.py" to test this file From 98cec566e90ecf1065ba3bcca29c856bb0e6cf1f Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 6 Jun 2024 09:56:23 +0800 Subject: [PATCH 08/16] Add calculate.py and test_calculate.py --- projects/Calculate Age/calculate.py | 49 ++++++++++++++++++++++++ projects/Calculate Age/test_calculate.py | 21 ++++++++++ 2 files changed, 70 insertions(+) create mode 100644 projects/Calculate Age/calculate.py create mode 100644 projects/Calculate Age/test_calculate.py diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py new file mode 100644 index 00000000..7d87f97b --- /dev/null +++ b/projects/Calculate Age/calculate.py @@ -0,0 +1,49 @@ +import time +from calendar import isleap + + +# judge the leap year +def judge_leap_year(year): + if isleap(year): + return True + else: + return False + + +# returns the number of days in each month +def month_days(month, leap_year): + if month in [1, 3, 5, 7, 8, 10, 12]: + return 31 + elif month in [4, 6, 9, 11]: + return 30 + elif month == 2 and leap_year: + return 29 + elif month == 2 and (not leap_year): + return 28 + + +name = input("input your name: ") +age = input("input your age: ") +localtime = time.localtime(time.time()) + +year = int(age) +month = year * 12 + localtime.tm_mon +day = 0 + +begin_year = int(localtime.tm_year) - year +end_year = begin_year + year + +# calculate the days +for y in range(begin_year, end_year): + if judge_leap_year(y): + day = day + 366 + else: + day = day + 365 + +leap_year = judge_leap_year(localtime.tm_year) +for m in range(1, localtime.tm_mon): + day = day + month_days(m, leap_year) + +day = day + localtime.tm_mday +print("%s's age is %d years or " % (name, year), end="") +print("%d months or %d days" % (month, day)) \ No newline at end of file diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/test_calculate.py new file mode 100644 index 00000000..4cfa3e02 --- /dev/null +++ b/projects/Calculate Age/test_calculate.py @@ -0,0 +1,21 @@ +import pytest +from calculate import judge_leap_year, month_days + +def test_judge_leap_year(): + assert judge_leap_year(2000) == True + assert judge_leap_year(2008) == True + assert judge_leap_year(2023) == False + assert judge_leap_year(1900) == False + assert judge_leap_year(2400) == True + assert judge_leap_year(2100) == False + +def test_month_days(): + assert month_days(7, False) == 31 + assert month_days(4, True) == 30 + assert month_days(2, True) == 29 + assert month_days(2, False) == 28 + assert month_days(1, False) == 31 + assert month_days(11, True) == 30 + +# "pytest -s test_calculate.py" to test this file + From 9072ad37ca797d1be7927a530a863cafd85d3f3a Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 6 Jun 2024 10:07:24 +0800 Subject: [PATCH 09/16] fix test_calculate_age.py --- projects/Calculate Age/tests/test_calculate_age.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py index af0c07ba..104b6ef9 100644 --- a/projects/Calculate Age/tests/test_calculate_age.py +++ b/projects/Calculate Age/tests/test_calculate_age.py @@ -21,5 +21,5 @@ def test_age_calculator_negative_age(): def test_age_calculator_leap_year(): name = "David" age = 30 - expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" + expect_output_leap_year = "David's age is 30 years or 366 months or 11115 days" assert age_calculator(name, age) == expect_output_leap_year From 4e245e024d52310bf20d8669a09c99f79cf33b55 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 6 Jun 2024 22:24:22 +0800 Subject: [PATCH 10/16] Remove feature-branch.diff from the repository --- feature-branch.diff | 254 -------------------------------------------- 1 file changed, 254 deletions(-) delete mode 100644 feature-branch.diff diff --git a/feature-branch.diff b/feature-branch.diff deleted file mode 100644 index 79e44d46..00000000 --- a/feature-branch.diff +++ /dev/null @@ -1,254 +0,0 @@ -diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py -deleted file mode 100644 -index a7dc34f..0000000 ---- a/projects/Calculate Age/calculate.py -+++ /dev/null -@@ -1,49 +0,0 @@ --import time --from calendar import isleap -- -- --# judge the leap year --def judge_leap_year(year): -- if isleap(year): -- return True -- else: -- return False -- -- --# returns the number of days in each month --def month_days(month, leap_year): -- if month in [1, 3, 5, 7, 8, 10, 12]: -- return 31 -- elif month in [4, 6, 9, 11]: -- return 30 -- elif month == 2 and leap_year: -- return 29 -- elif month == 2 and (not leap_year): -- return 28 -- -- --name = input("input your name: ") --age = input("input your age: ") --localtime = time.localtime(time.time()) -- --year = int(age) --month = year * 12 + localtime.tm_mon --day = 0 -- --begin_year = int(localtime.tm_year) - year --end_year = begin_year + year -- --# calculate the days --for y in range(begin_year, end_year): -- if judge_leap_year(y): -- day = day + 366 -- else: -- day = day + 365 -- --leap_year = judge_leap_year(localtime.tm_year) --for m in range(1, localtime.tm_mon): -- day = day + month_days(m, leap_year) -- --day = day + localtime.tm_mday --print("%s's age is %d years or " % (name, year), end="") --print("%d months or %d days" % (month, day)) -diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py -new file mode 100644 -index 0000000..e69de29 -diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py -new file mode 100644 -index 0000000..193fb64 ---- /dev/null -+++ b/projects/Calculate Age/src/calculate_age.py -@@ -0,0 +1,42 @@ -+import time -+from utilize_date import judge_leap_year, month_days -+ -+ -+def age_calculator(name, age): -+ """ -+ Calculate user's age in years, month, and days -+ based on current date and print. -+ -+ Args: -+ name (str): user's name. -+ age (int): user's age in years. -+ -+ Returns: -+ None. -+ """ -+ localtime = time.localtime(time.time()) -+ -+ year = int(age) -+ month = year * 12 + localtime.tm_mon -+ day = 0 -+ -+ begin_year = int(localtime.tm_year) - year -+ end_year = begin_year + year -+ -+ for y in range(begin_year, end_year): -+ if judge_leap_year(y): -+ day += 366 -+ else: -+ day += 365 -+ -+ leap_year = judge_leap_year(localtime.tm_year) -+ for m in range(1, localtime.tm_mon): -+ day += month_days(m, leap_year) -+ -+ day += localtime.tm_mday -+ -+ return f"{name}'s age is {year} years or {month} months or {day} days" -+ -+ -+ -+ -diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py -new file mode 100644 -index 0000000..b775235 ---- /dev/null -+++ b/projects/Calculate Age/src/main.py -@@ -0,0 +1,35 @@ -+from calculate_age import age_calculator -+ -+ -+def main(): -+ """ -+ the user to input name and age, validate input, -+ and calculates and displays the user age in years, months and days. -+ -+ Args: -+ None. -+ -+ Return: -+ None. -+ """ -+ input_name = input("input your name: ") -+ -+ while True: -+ input_age = input("input your age: ") -+ try: -+ string_to_int_age = int(input_age) -+ if string_to_int_age <= 0: -+ print("Please input a positive number.") -+ else: -+ break -+ except ValueError: -+ print("Please input a valid age.") -+ -+ result = age_calculator(input_name, string_to_int_age) -+ -+ print(result) -+ -+if __name__ == "__main__": -+ main() -+ -+ -diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py -new file mode 100644 -index 0000000..8d8b129 ---- /dev/null -+++ b/projects/Calculate Age/src/utilize_date.py -@@ -0,0 +1,36 @@ -+from calendar import isleap -+ -+ -+def judge_leap_year(year): -+ """ -+ judge the leap year. -+ -+ Args: -+ year (int): To check the year. -+ return: -+ bool: Ture if the year is a leap year, False otherwise. -+ """ -+ if isleap(year): -+ return True -+ else: -+ return False -+ -+ -+def month_days(month, leap_year): -+ """ -+ Returns the number of days in each month -+ -+ Args: -+ month (int): The month 1-12. -+ -+ Returns: -+ int: The number of days in the month. -+ """ -+ if month in [1, 3, 5, 7, 8, 10, 12]: -+ return 31 -+ elif month in [4, 6, 9, 11]: -+ return 30 -+ elif month == 2 and leap_year: -+ return 29 -+ elif month == 2 and (not leap_year): -+ return 28 -diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py -new file mode 100644 -index 0000000..e69de29 -diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py -new file mode 100644 -index 0000000..af0c07b ---- /dev/null -+++ b/projects/Calculate Age/tests/test_calculate_age.py -@@ -0,0 +1,25 @@ -+import time -+from unittest.mock import patch -+from calculate_age import age_calculator -+ -+@patch('time.time', return_value=1621848668.0) -+def test_age_calculator(mock_time): -+ name = "Chloe" -+ age = 30 -+ expect_output = "Chloe's age is 30 years or 365 months or 11102 days" -+ assert age_calculator(name, age) == expect_output -+ -+def test_age_calculator_negative_age(): -+ name = "Emma" -+ age = -5 -+ try: -+ age_calculator(name, age) -+ except ValueError as e: -+ assert str(e) == "Please input a positive number." -+ -+ -+def test_age_calculator_leap_year(): -+ name = "David" -+ age = 30 -+ expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" -+ assert age_calculator(name, age) == expect_output_leap_year -diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/tests/test_utilize_date.py -similarity index 83% -rename from projects/Calculate Age/test_calculate.py -rename to projects/Calculate Age/tests/test_utilize_date.py -index 369ac65..54e5efa 100644 ---- a/projects/Calculate Age/test_calculate.py -+++ b/projects/Calculate Age/tests/test_utilize_date.py -@@ -1,5 +1,6 @@ - import pytest --from calculate import judge_leap_year, month_days -+from utilize_date import judge_leap_year, month_days -+ - - def test_judge_leap_year(): - assert judge_leap_year(2000) == True -@@ -9,6 +10,7 @@ def test_judge_leap_year(): - assert judge_leap_year(2400) == True - assert judge_leap_year(2100) == False - -+ - def test_month_days(): - assert month_days(7, False) == 31 - assert month_days(4, True) == 30 -@@ -17,4 +19,5 @@ def test_month_days(): - assert month_days(1, False) == 31 - assert month_days(11, True) == 30 - --# "pytest -s test_calculate.py" to test this file -\ No newline at end of file -+ -+# "pytest -s test_utilize_date.py" to test this file From 77e871db78722f95f8665c6831132da18e57adfd Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 6 Jun 2024 22:43:19 +0800 Subject: [PATCH 11/16] Add docstring in each test file --- feature-branch.diff | 254 ++++++++++++++++++ .../Calculate Age/tests/test_calculate_age.py | 13 + .../Calculate Age/tests/test_utilize_date.py | 10 + 3 files changed, 277 insertions(+) create mode 100644 feature-branch.diff diff --git a/feature-branch.diff b/feature-branch.diff new file mode 100644 index 00000000..79e44d46 --- /dev/null +++ b/feature-branch.diff @@ -0,0 +1,254 @@ +diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py +deleted file mode 100644 +index a7dc34f..0000000 +--- a/projects/Calculate Age/calculate.py ++++ /dev/null +@@ -1,49 +0,0 @@ +-import time +-from calendar import isleap +- +- +-# judge the leap year +-def judge_leap_year(year): +- if isleap(year): +- return True +- else: +- return False +- +- +-# returns the number of days in each month +-def month_days(month, leap_year): +- if month in [1, 3, 5, 7, 8, 10, 12]: +- return 31 +- elif month in [4, 6, 9, 11]: +- return 30 +- elif month == 2 and leap_year: +- return 29 +- elif month == 2 and (not leap_year): +- return 28 +- +- +-name = input("input your name: ") +-age = input("input your age: ") +-localtime = time.localtime(time.time()) +- +-year = int(age) +-month = year * 12 + localtime.tm_mon +-day = 0 +- +-begin_year = int(localtime.tm_year) - year +-end_year = begin_year + year +- +-# calculate the days +-for y in range(begin_year, end_year): +- if judge_leap_year(y): +- day = day + 366 +- else: +- day = day + 365 +- +-leap_year = judge_leap_year(localtime.tm_year) +-for m in range(1, localtime.tm_mon): +- day = day + month_days(m, leap_year) +- +-day = day + localtime.tm_mday +-print("%s's age is %d years or " % (name, year), end="") +-print("%d months or %d days" % (month, day)) +diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py +new file mode 100644 +index 0000000..e69de29 +diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py +new file mode 100644 +index 0000000..193fb64 +--- /dev/null ++++ b/projects/Calculate Age/src/calculate_age.py +@@ -0,0 +1,42 @@ ++import time ++from utilize_date import judge_leap_year, month_days ++ ++ ++def age_calculator(name, age): ++ """ ++ Calculate user's age in years, month, and days ++ based on current date and print. ++ ++ Args: ++ name (str): user's name. ++ age (int): user's age in years. ++ ++ Returns: ++ None. ++ """ ++ localtime = time.localtime(time.time()) ++ ++ year = int(age) ++ month = year * 12 + localtime.tm_mon ++ day = 0 ++ ++ begin_year = int(localtime.tm_year) - year ++ end_year = begin_year + year ++ ++ for y in range(begin_year, end_year): ++ if judge_leap_year(y): ++ day += 366 ++ else: ++ day += 365 ++ ++ leap_year = judge_leap_year(localtime.tm_year) ++ for m in range(1, localtime.tm_mon): ++ day += month_days(m, leap_year) ++ ++ day += localtime.tm_mday ++ ++ return f"{name}'s age is {year} years or {month} months or {day} days" ++ ++ ++ ++ +diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py +new file mode 100644 +index 0000000..b775235 +--- /dev/null ++++ b/projects/Calculate Age/src/main.py +@@ -0,0 +1,35 @@ ++from calculate_age import age_calculator ++ ++ ++def main(): ++ """ ++ the user to input name and age, validate input, ++ and calculates and displays the user age in years, months and days. ++ ++ Args: ++ None. ++ ++ Return: ++ None. ++ """ ++ input_name = input("input your name: ") ++ ++ while True: ++ input_age = input("input your age: ") ++ try: ++ string_to_int_age = int(input_age) ++ if string_to_int_age <= 0: ++ print("Please input a positive number.") ++ else: ++ break ++ except ValueError: ++ print("Please input a valid age.") ++ ++ result = age_calculator(input_name, string_to_int_age) ++ ++ print(result) ++ ++if __name__ == "__main__": ++ main() ++ ++ +diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py +new file mode 100644 +index 0000000..8d8b129 +--- /dev/null ++++ b/projects/Calculate Age/src/utilize_date.py +@@ -0,0 +1,36 @@ ++from calendar import isleap ++ ++ ++def judge_leap_year(year): ++ """ ++ judge the leap year. ++ ++ Args: ++ year (int): To check the year. ++ return: ++ bool: Ture if the year is a leap year, False otherwise. ++ """ ++ if isleap(year): ++ return True ++ else: ++ return False ++ ++ ++def month_days(month, leap_year): ++ """ ++ Returns the number of days in each month ++ ++ Args: ++ month (int): The month 1-12. ++ ++ Returns: ++ int: The number of days in the month. ++ """ ++ if month in [1, 3, 5, 7, 8, 10, 12]: ++ return 31 ++ elif month in [4, 6, 9, 11]: ++ return 30 ++ elif month == 2 and leap_year: ++ return 29 ++ elif month == 2 and (not leap_year): ++ return 28 +diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py +new file mode 100644 +index 0000000..e69de29 +diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py +new file mode 100644 +index 0000000..af0c07b +--- /dev/null ++++ b/projects/Calculate Age/tests/test_calculate_age.py +@@ -0,0 +1,25 @@ ++import time ++from unittest.mock import patch ++from calculate_age import age_calculator ++ ++@patch('time.time', return_value=1621848668.0) ++def test_age_calculator(mock_time): ++ name = "Chloe" ++ age = 30 ++ expect_output = "Chloe's age is 30 years or 365 months or 11102 days" ++ assert age_calculator(name, age) == expect_output ++ ++def test_age_calculator_negative_age(): ++ name = "Emma" ++ age = -5 ++ try: ++ age_calculator(name, age) ++ except ValueError as e: ++ assert str(e) == "Please input a positive number." ++ ++ ++def test_age_calculator_leap_year(): ++ name = "David" ++ age = 30 ++ expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" ++ assert age_calculator(name, age) == expect_output_leap_year +diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/tests/test_utilize_date.py +similarity index 83% +rename from projects/Calculate Age/test_calculate.py +rename to projects/Calculate Age/tests/test_utilize_date.py +index 369ac65..54e5efa 100644 +--- a/projects/Calculate Age/test_calculate.py ++++ b/projects/Calculate Age/tests/test_utilize_date.py +@@ -1,5 +1,6 @@ + import pytest +-from calculate import judge_leap_year, month_days ++from utilize_date import judge_leap_year, month_days ++ + + def test_judge_leap_year(): + assert judge_leap_year(2000) == True +@@ -9,6 +10,7 @@ def test_judge_leap_year(): + assert judge_leap_year(2400) == True + assert judge_leap_year(2100) == False + ++ + def test_month_days(): + assert month_days(7, False) == 31 + assert month_days(4, True) == 30 +@@ -17,4 +19,5 @@ def test_month_days(): + assert month_days(1, False) == 31 + assert month_days(11, True) == 30 + +-# "pytest -s test_calculate.py" to test this file +\ No newline at end of file ++ ++# "pytest -s test_utilize_date.py" to test this file diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py index 104b6ef9..8fa6d389 100644 --- a/projects/Calculate Age/tests/test_calculate_age.py +++ b/projects/Calculate Age/tests/test_calculate_age.py @@ -4,12 +4,21 @@ @patch('time.time', return_value=1621848668.0) def test_age_calculator(mock_time): + """ + Test the age_calculator function + Mocks the current time and check if the age is calculated + based on current time + """ name = "Chloe" age = 30 expect_output = "Chloe's age is 30 years or 365 months or 11102 days" assert age_calculator(name, age) == expect_output def test_age_calculator_negative_age(): + """ + Tests the age_calculator function for negative age input + Check for ValueError when user input negative age. + """ name = "Emma" age = -5 try: @@ -19,6 +28,10 @@ def test_age_calculator_negative_age(): def test_age_calculator_leap_year(): + """ + Test the age_calculator function considering leap years + Check for expect_output_leap_year comparing the real output considering leap years + """ name = "David" age = 30 expect_output_leap_year = "David's age is 30 years or 366 months or 11115 days" diff --git a/projects/Calculate Age/tests/test_utilize_date.py b/projects/Calculate Age/tests/test_utilize_date.py index 54e5efa0..088d201c 100644 --- a/projects/Calculate Age/tests/test_utilize_date.py +++ b/projects/Calculate Age/tests/test_utilize_date.py @@ -3,6 +3,11 @@ def test_judge_leap_year(): + """ + judge_leap_year function tests whether a given year is a leap year. + + A leap year is divisible by 4 and, if divisible by 100, must also be divisible by 400. + """ assert judge_leap_year(2000) == True assert judge_leap_year(2008) == True assert judge_leap_year(2023) == False @@ -12,6 +17,11 @@ def test_judge_leap_year(): def test_month_days(): + """ + The month_days function tests whether if returns the correct number of days for a given month + + For Feb, both leap years and common years are considered. + """ assert month_days(7, False) == 31 assert month_days(4, True) == 30 assert month_days(2, True) == 29 From b04bcdb988568764e676c4f046e248a98ae6751d Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 6 Jun 2024 22:44:37 +0800 Subject: [PATCH 12/16] remove reature-branch.diff from the origin --- feature-branch.diff | 254 -------------------------------------------- 1 file changed, 254 deletions(-) delete mode 100644 feature-branch.diff diff --git a/feature-branch.diff b/feature-branch.diff deleted file mode 100644 index 79e44d46..00000000 --- a/feature-branch.diff +++ /dev/null @@ -1,254 +0,0 @@ -diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py -deleted file mode 100644 -index a7dc34f..0000000 ---- a/projects/Calculate Age/calculate.py -+++ /dev/null -@@ -1,49 +0,0 @@ --import time --from calendar import isleap -- -- --# judge the leap year --def judge_leap_year(year): -- if isleap(year): -- return True -- else: -- return False -- -- --# returns the number of days in each month --def month_days(month, leap_year): -- if month in [1, 3, 5, 7, 8, 10, 12]: -- return 31 -- elif month in [4, 6, 9, 11]: -- return 30 -- elif month == 2 and leap_year: -- return 29 -- elif month == 2 and (not leap_year): -- return 28 -- -- --name = input("input your name: ") --age = input("input your age: ") --localtime = time.localtime(time.time()) -- --year = int(age) --month = year * 12 + localtime.tm_mon --day = 0 -- --begin_year = int(localtime.tm_year) - year --end_year = begin_year + year -- --# calculate the days --for y in range(begin_year, end_year): -- if judge_leap_year(y): -- day = day + 366 -- else: -- day = day + 365 -- --leap_year = judge_leap_year(localtime.tm_year) --for m in range(1, localtime.tm_mon): -- day = day + month_days(m, leap_year) -- --day = day + localtime.tm_mday --print("%s's age is %d years or " % (name, year), end="") --print("%d months or %d days" % (month, day)) -diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py -new file mode 100644 -index 0000000..e69de29 -diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py -new file mode 100644 -index 0000000..193fb64 ---- /dev/null -+++ b/projects/Calculate Age/src/calculate_age.py -@@ -0,0 +1,42 @@ -+import time -+from utilize_date import judge_leap_year, month_days -+ -+ -+def age_calculator(name, age): -+ """ -+ Calculate user's age in years, month, and days -+ based on current date and print. -+ -+ Args: -+ name (str): user's name. -+ age (int): user's age in years. -+ -+ Returns: -+ None. -+ """ -+ localtime = time.localtime(time.time()) -+ -+ year = int(age) -+ month = year * 12 + localtime.tm_mon -+ day = 0 -+ -+ begin_year = int(localtime.tm_year) - year -+ end_year = begin_year + year -+ -+ for y in range(begin_year, end_year): -+ if judge_leap_year(y): -+ day += 366 -+ else: -+ day += 365 -+ -+ leap_year = judge_leap_year(localtime.tm_year) -+ for m in range(1, localtime.tm_mon): -+ day += month_days(m, leap_year) -+ -+ day += localtime.tm_mday -+ -+ return f"{name}'s age is {year} years or {month} months or {day} days" -+ -+ -+ -+ -diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py -new file mode 100644 -index 0000000..b775235 ---- /dev/null -+++ b/projects/Calculate Age/src/main.py -@@ -0,0 +1,35 @@ -+from calculate_age import age_calculator -+ -+ -+def main(): -+ """ -+ the user to input name and age, validate input, -+ and calculates and displays the user age in years, months and days. -+ -+ Args: -+ None. -+ -+ Return: -+ None. -+ """ -+ input_name = input("input your name: ") -+ -+ while True: -+ input_age = input("input your age: ") -+ try: -+ string_to_int_age = int(input_age) -+ if string_to_int_age <= 0: -+ print("Please input a positive number.") -+ else: -+ break -+ except ValueError: -+ print("Please input a valid age.") -+ -+ result = age_calculator(input_name, string_to_int_age) -+ -+ print(result) -+ -+if __name__ == "__main__": -+ main() -+ -+ -diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py -new file mode 100644 -index 0000000..8d8b129 ---- /dev/null -+++ b/projects/Calculate Age/src/utilize_date.py -@@ -0,0 +1,36 @@ -+from calendar import isleap -+ -+ -+def judge_leap_year(year): -+ """ -+ judge the leap year. -+ -+ Args: -+ year (int): To check the year. -+ return: -+ bool: Ture if the year is a leap year, False otherwise. -+ """ -+ if isleap(year): -+ return True -+ else: -+ return False -+ -+ -+def month_days(month, leap_year): -+ """ -+ Returns the number of days in each month -+ -+ Args: -+ month (int): The month 1-12. -+ -+ Returns: -+ int: The number of days in the month. -+ """ -+ if month in [1, 3, 5, 7, 8, 10, 12]: -+ return 31 -+ elif month in [4, 6, 9, 11]: -+ return 30 -+ elif month == 2 and leap_year: -+ return 29 -+ elif month == 2 and (not leap_year): -+ return 28 -diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py -new file mode 100644 -index 0000000..e69de29 -diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py -new file mode 100644 -index 0000000..af0c07b ---- /dev/null -+++ b/projects/Calculate Age/tests/test_calculate_age.py -@@ -0,0 +1,25 @@ -+import time -+from unittest.mock import patch -+from calculate_age import age_calculator -+ -+@patch('time.time', return_value=1621848668.0) -+def test_age_calculator(mock_time): -+ name = "Chloe" -+ age = 30 -+ expect_output = "Chloe's age is 30 years or 365 months or 11102 days" -+ assert age_calculator(name, age) == expect_output -+ -+def test_age_calculator_negative_age(): -+ name = "Emma" -+ age = -5 -+ try: -+ age_calculator(name, age) -+ except ValueError as e: -+ assert str(e) == "Please input a positive number." -+ -+ -+def test_age_calculator_leap_year(): -+ name = "David" -+ age = 30 -+ expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" -+ assert age_calculator(name, age) == expect_output_leap_year -diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/tests/test_utilize_date.py -similarity index 83% -rename from projects/Calculate Age/test_calculate.py -rename to projects/Calculate Age/tests/test_utilize_date.py -index 369ac65..54e5efa 100644 ---- a/projects/Calculate Age/test_calculate.py -+++ b/projects/Calculate Age/tests/test_utilize_date.py -@@ -1,5 +1,6 @@ - import pytest --from calculate import judge_leap_year, month_days -+from utilize_date import judge_leap_year, month_days -+ - - def test_judge_leap_year(): - assert judge_leap_year(2000) == True -@@ -9,6 +10,7 @@ def test_judge_leap_year(): - assert judge_leap_year(2400) == True - assert judge_leap_year(2100) == False - -+ - def test_month_days(): - assert month_days(7, False) == 31 - assert month_days(4, True) == 30 -@@ -17,4 +19,5 @@ def test_month_days(): - assert month_days(1, False) == 31 - assert month_days(11, True) == 30 - --# "pytest -s test_calculate.py" to test this file -\ No newline at end of file -+ -+# "pytest -s test_utilize_date.py" to test this file From 12ec693199e5ec50e2348dbd6d18b1dd1a4d7a57 Mon Sep 17 00:00:00 2001 From: Lint Action Date: Fri, 7 Jun 2024 02:54:46 +0000 Subject: [PATCH 13/16] Fix code style issues with Black --- projects/Calculate Age/calculate.py | 2 +- projects/Calculate Age/src/calculate_age.py | 20 ++- projects/Calculate Age/src/main.py | 17 ++- projects/Calculate Age/src/utilize_date.py | 24 ++-- projects/Calculate Age/test_calculate.py | 1 + .../Calculate Age/tests/test_calculate_age.py | 10 +- .../Calculate Age/tests/test_utilize_date.py | 4 +- .../Chat-GPT-Discord-Bot/Chat_GPT_Function.py | 47 +++---- projects/Chat-GPT-Discord-Bot/main.py | 106 ++++++++++----- projects/Chat-GPT-Discord-Bot/tests.py | 33 ++--- projects/Pokemon Battle/pokemon.py | 125 +++++++++++------- projects/Quiz Game/main.py | 31 +++-- projects/Quiz Game/setup_db.py | 10 +- projects/Snake Game/src/constants.py | 2 +- projects/Snake Game/src/display.py | 42 ++++-- projects/Snake Game/src/game.py | 35 +++-- projects/Snake Game/src/snake.py | 7 +- projects/Snake Game/tests/test_display.py | 76 ++++++----- projects/Snake Game/tests/test_game.py | 64 +++++---- projects/Snake Game/tests/test_snake.py | 8 +- projects/computer-algebra/main.py | 99 ++++++++------ projects/computer-algebra/newton_command.py | 79 +++++------ 22 files changed, 503 insertions(+), 339 deletions(-) diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py index 7d87f97b..a7dc34fa 100644 --- a/projects/Calculate Age/calculate.py +++ b/projects/Calculate Age/calculate.py @@ -46,4 +46,4 @@ def month_days(month, leap_year): day = day + localtime.tm_mday print("%s's age is %d years or " % (name, year), end="") -print("%d months or %d days" % (month, day)) \ No newline at end of file +print("%d months or %d days" % (month, day)) diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py index 193fb64e..1d630420 100644 --- a/projects/Calculate Age/src/calculate_age.py +++ b/projects/Calculate Age/src/calculate_age.py @@ -4,16 +4,16 @@ def age_calculator(name, age): """ - Calculate user's age in years, month, and days - based on current date and print. + Calculate user's age in years, month, and days + based on current date and print. - Args: - name (str): user's name. - age (int): user's age in years. + Args: + name (str): user's name. + age (int): user's age in years. - Returns: - None. - """ + Returns: + None. + """ localtime = time.localtime(time.time()) year = int(age) @@ -36,7 +36,3 @@ def age_calculator(name, age): day += localtime.tm_mday return f"{name}'s age is {year} years or {month} months or {day} days" - - - - diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py index b7752356..35befcd2 100644 --- a/projects/Calculate Age/src/main.py +++ b/projects/Calculate Age/src/main.py @@ -3,15 +3,15 @@ def main(): """ - the user to input name and age, validate input, - and calculates and displays the user age in years, months and days. + the user to input name and age, validate input, + and calculates and displays the user age in years, months and days. - Args: - None. + Args: + None. - Return: - None. - """ + Return: + None. + """ input_name = input("input your name: ") while True: @@ -29,7 +29,6 @@ def main(): print(result) + if __name__ == "__main__": main() - - diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py index 8d8b129c..e59f8fca 100644 --- a/projects/Calculate Age/src/utilize_date.py +++ b/projects/Calculate Age/src/utilize_date.py @@ -3,13 +3,13 @@ def judge_leap_year(year): """ - judge the leap year. + judge the leap year. - Args: - year (int): To check the year. - return: - bool: Ture if the year is a leap year, False otherwise. - """ + Args: + year (int): To check the year. + return: + bool: Ture if the year is a leap year, False otherwise. + """ if isleap(year): return True else: @@ -18,14 +18,14 @@ def judge_leap_year(year): def month_days(month, leap_year): """ - Returns the number of days in each month + Returns the number of days in each month - Args: - month (int): The month 1-12. + Args: + month (int): The month 1-12. - Returns: - int: The number of days in the month. - """ + Returns: + int: The number of days in the month. + """ if month in [1, 3, 5, 7, 8, 10, 12]: return 31 elif month in [4, 6, 9, 11]: diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/test_calculate.py index c6e2a37c..c8f5f7f1 100644 --- a/projects/Calculate Age/test_calculate.py +++ b/projects/Calculate Age/test_calculate.py @@ -19,4 +19,5 @@ def test_month_days(): assert month_days(1, False) == 31 assert month_days(11, True) == 30 + # "pytest -s test_calculate.py" to test this file diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py index 8fa6d389..9efa6790 100644 --- a/projects/Calculate Age/tests/test_calculate_age.py +++ b/projects/Calculate Age/tests/test_calculate_age.py @@ -2,18 +2,20 @@ from unittest.mock import patch from calculate_age import age_calculator -@patch('time.time', return_value=1621848668.0) + +@patch("time.time", return_value=1621848668.0) def test_age_calculator(mock_time): """ - Test the age_calculator function - Mocks the current time and check if the age is calculated - based on current time + Test the age_calculator function + Mocks the current time and check if the age is calculated + based on current time """ name = "Chloe" age = 30 expect_output = "Chloe's age is 30 years or 365 months or 11102 days" assert age_calculator(name, age) == expect_output + def test_age_calculator_negative_age(): """ Tests the age_calculator function for negative age input diff --git a/projects/Calculate Age/tests/test_utilize_date.py b/projects/Calculate Age/tests/test_utilize_date.py index 088d201c..43632de5 100644 --- a/projects/Calculate Age/tests/test_utilize_date.py +++ b/projects/Calculate Age/tests/test_utilize_date.py @@ -4,9 +4,9 @@ def test_judge_leap_year(): """ - judge_leap_year function tests whether a given year is a leap year. + judge_leap_year function tests whether a given year is a leap year. - A leap year is divisible by 4 and, if divisible by 100, must also be divisible by 400. + A leap year is divisible by 4 and, if divisible by 100, must also be divisible by 400. """ assert judge_leap_year(2000) == True assert judge_leap_year(2008) == True diff --git a/projects/Chat-GPT-Discord-Bot/Chat_GPT_Function.py b/projects/Chat-GPT-Discord-Bot/Chat_GPT_Function.py index e36ad87b..82013f77 100644 --- a/projects/Chat-GPT-Discord-Bot/Chat_GPT_Function.py +++ b/projects/Chat-GPT-Discord-Bot/Chat_GPT_Function.py @@ -6,47 +6,44 @@ gpt_api_key = os.getenv("GPT_API_KEY") + def gpt(model: str, prompt: str, sys_prompt: str, temp: float): - client = OpenAI(api_key= gpt_api_key) + client = OpenAI(api_key=gpt_api_key) response = client.chat.completions.create( - model = model, + model=model, messages=[ - { - "role": "system", - "content": sys_prompt - }, - { - "role": "user", - "content": prompt - } + {"role": "system", "content": sys_prompt}, + {"role": "user", "content": prompt}, ], - temperature = temp, + temperature=temp, # max_tokens=64, - top_p=1 + top_p=1, ) output = response.choices[0].message.content.strip() return output + def dalle3(prompt: str, quality: str, size: str, style: str): - client = OpenAI(api_key= gpt_api_key) + client = OpenAI(api_key=gpt_api_key) response = client.images.generate( - model = "dall-e-3", - prompt = prompt, - size = size, - quality = quality, - style = style, + model="dall-e-3", + prompt=prompt, + size=size, + quality=quality, + style=style, n=1, - ) + ) image_url = response.data[0].url return image_url + def dalle2(prompt: str, size: str): - client = OpenAI(api_key= gpt_api_key) + client = OpenAI(api_key=gpt_api_key) response = client.images.generate( - model = "dall-e-2", - prompt = prompt, - size = size, + model="dall-e-2", + prompt=prompt, + size=size, n=1, - ) + ) image_url = response.data[0].url - return image_url \ No newline at end of file + return image_url diff --git a/projects/Chat-GPT-Discord-Bot/main.py b/projects/Chat-GPT-Discord-Bot/main.py index 38d3709f..a6afd3a9 100644 --- a/projects/Chat-GPT-Discord-Bot/main.py +++ b/projects/Chat-GPT-Discord-Bot/main.py @@ -15,7 +15,8 @@ data = json.load(f) # Loads the gpt system prompts char_limit = data["system_content"][0][ - "character_limit_prompt"] # Makes sure that the gpt output won't exceed the discord embed character limit of 4096 characters + "character_limit_prompt" +] # Makes sure that the gpt output won't exceed the discord embed character limit of 4096 characters try: token = os.getenv("BOT_TOKEN") # returns a str @@ -58,7 +59,9 @@ def __init__(self, *, intents: discord.Intents): # This allows for faster bot testing and development. async def setup_hook(self): # This copies the global commands over to your guild(s). - self.tree.clear_commands(guild=discord_server_1) # Prevents command duplication. + self.tree.clear_commands( + guild=discord_server_1 + ) # Prevents command duplication. await self.tree.sync(guild=discord_server_1) self.tree.clear_commands(guild=discord_server_2) await self.tree.sync(guild=discord_server_2) # Prevents command duplication. @@ -108,9 +111,11 @@ async def send(interaction: discord.Interaction): for slash_command in client.tree.walk_commands(): embed.add_field( name=slash_command.name, - value=f"- {slash_command.description}\n-----------------------------------------" - if slash_command.description - else slash_command.name, + value=( + f"- {slash_command.description}\n-----------------------------------------" + if slash_command.description + else slash_command.name + ), inline=False, ) # Send as followup message @@ -433,8 +438,14 @@ async def send(interaction: discord.Interaction, text: str): # noqa: F811 @client.tree.command(name="gpt_general_question", description="For all your questions") @app_commands.rename(text="prompt") @app_commands.describe(text="What do you want to ask chatGPT?") -@app_commands.describe(gpt_model="Possible options = gpt-4 or gpt-3.5 (gpt-3.5-turbo-16k abbreviated)") -async def send(interaction: discord.Interaction, text: str, gpt_model: str,): # noqa: F811 +@app_commands.describe( + gpt_model="Possible options = gpt-4 or gpt-3.5 (gpt-3.5-turbo-16k abbreviated)" +) +async def send( + interaction: discord.Interaction, + text: str, + gpt_model: str, +): # noqa: F811 try: await interaction.response.defer( ephemeral=False @@ -447,7 +458,7 @@ async def send(interaction: discord.Interaction, text: str, gpt_model: str,): # return else: gpt_prompt = text - + if gpt_model.lower() not in ("gpt-4", "gpt-3.5"): await interaction.followup.send( "Invalid GPT model. Must be either gpt-4 or gpt-3.5." @@ -458,7 +469,6 @@ async def send(interaction: discord.Interaction, text: str, gpt_model: str,): # gpt_model = "gpt-3.5-turbo-16k" else: gpt_model = gpt_model.lower() - # It is best to use discord embeds for gpt commands as discord embed descriptions allow for 4096 characters instead of 2000 characters for normal messages embed = discord.Embed( @@ -485,25 +495,38 @@ async def send(interaction: discord.Interaction, text: str, gpt_model: str,): # await interaction.followup.send( "An error occurred while processing the command." ) - + + # -------------------------- DALLE 3 ---------------------------------- @client.tree.command(name="dalle_3", description="Generates an image with DALL·E 3") @app_commands.describe(prompt="Describe the image you want DALL·E 3 to create") -@app_commands.describe(img_dimensions="Must be either 1024x1024, 1792x1024, or 1024x1792 for dall-e-3") -@app_commands.describe(img_quality="Must be either hd or standard. HD = images with finer details and greater consistency across the image.") -@app_commands.describe(img_style="Must be either vivid or natural. Vivid = hyper-real and dramatic images. Natural = more natural, less hyper-real looking images.") -async def send(interaction: discord.Interaction, prompt: str, img_dimensions: str, img_quality: str, img_style: str): # noqa: F811 +@app_commands.describe( + img_dimensions="Must be either 1024x1024, 1792x1024, or 1024x1792 for dall-e-3" +) +@app_commands.describe( + img_quality="Must be either hd or standard. HD = images with finer details and greater consistency across the image." +) +@app_commands.describe( + img_style="Must be either vivid or natural. Vivid = hyper-real and dramatic images. Natural = more natural, less hyper-real looking images." +) +async def send( + interaction: discord.Interaction, + prompt: str, + img_dimensions: str, + img_quality: str, + img_style: str, +): # noqa: F811 try: await interaction.response.defer( ephemeral=False ) # Defer the response to prevent command timeout - + # Get the current time current_time = datetime.now() - + # Add 1 hour to the current time future_time = current_time + timedelta(hours=1) - + if img_dimensions.lower() not in ("1024x1024", "1792x1024", "1024x1792"): await interaction.followup.send( "Invalid image dimension. Must be either 1024x1024, 1792x1024, or 1024x1792." @@ -511,7 +534,7 @@ async def send(interaction: discord.Interaction, prompt: str, img_dimensions: st return else: img_dimensions = img_dimensions.lower() - + if img_quality.lower() not in ("hd", "standard"): await interaction.followup.send( "Invalid image quality. Must be either hd or standard." @@ -519,7 +542,7 @@ async def send(interaction: discord.Interaction, prompt: str, img_dimensions: st return else: img_quality = img_quality.lower() - + if img_style.lower() not in ("vivid", "natural"): await interaction.followup.send( "Invalid image style. Must be either vivid or natural." @@ -527,35 +550,46 @@ async def send(interaction: discord.Interaction, prompt: str, img_dimensions: st return else: img_style = img_style.lower() - - loop = asyncio.get_event_loop() # Prevents heartbeat block warning and bot disconnecting from discord error - image_url = await loop.run_in_executor(None, dalle3, prompt, img_quality, img_dimensions, img_style) # Prevents heartbeat block warning and bot disconnecting from discord error + + loop = ( + asyncio.get_event_loop() + ) # Prevents heartbeat block warning and bot disconnecting from discord error + image_url = await loop.run_in_executor( + None, dalle3, prompt, img_quality, img_dimensions, img_style + ) # Prevents heartbeat block warning and bot disconnecting from discord error # Send as followup message - await interaction.followup.send(f"{image_url} IMAGE LINK EXPIRES IN ") + await interaction.followup.send( + f"{image_url} IMAGE LINK EXPIRES IN " + ) except Exception as e: # Handle exceptions print(f"An error occurred: {str(e)}") await interaction.followup.send( "An error occurred while processing the command." ) - + + # -------------------------- DALLE 2 ---------------------------------- @client.tree.command(name="dalle_2", description="Generates an image with DALL·E 2") @app_commands.describe(prompt="Describe the image you want DALL·E 2 to create") -@app_commands.describe(img_dimensions="Must be either 256x256, 512x512, or 1024x1024 for dall-e-2") -async def send(interaction: discord.Interaction, prompt: str, img_dimensions: str): # noqa: F811 +@app_commands.describe( + img_dimensions="Must be either 256x256, 512x512, or 1024x1024 for dall-e-2" +) +async def send( + interaction: discord.Interaction, prompt: str, img_dimensions: str +): # noqa: F811 try: await interaction.response.defer( ephemeral=False ) # Defer the response to prevent command timeout - + # Get the current time current_time = datetime.now() - + # Add 1 hour to the current time future_time = current_time + timedelta(hours=1) - + if img_dimensions.lower() not in ("256x256", "512x512", "1024x1024"): await interaction.followup.send( "Invalid image dimension. Must be either 256x256, 512x512, or 1024x1024." @@ -563,12 +597,18 @@ async def send(interaction: discord.Interaction, prompt: str, img_dimensions: st return else: img_dimensions = img_dimensions.lower() - - loop = asyncio.get_event_loop() # Prevents heartbeat block warning and bot disconnecting from discord error - image_url = await loop.run_in_executor(None, dalle2, prompt, img_dimensions) # Prevents heartbeat block warning and bot disconnecting from discord error + + loop = ( + asyncio.get_event_loop() + ) # Prevents heartbeat block warning and bot disconnecting from discord error + image_url = await loop.run_in_executor( + None, dalle2, prompt, img_dimensions + ) # Prevents heartbeat block warning and bot disconnecting from discord error # Send as followup message - await interaction.followup.send(f"{image_url} IMAGE LINK EXPIRES IN ") # Convert future_time to unix timestamp. + await interaction.followup.send( + f"{image_url} IMAGE LINK EXPIRES IN " + ) # Convert future_time to unix timestamp. except Exception as e: # Handle exceptions print(f"An error occurred: {str(e)}") diff --git a/projects/Chat-GPT-Discord-Bot/tests.py b/projects/Chat-GPT-Discord-Bot/tests.py index a28d9da0..70997c39 100644 --- a/projects/Chat-GPT-Discord-Bot/tests.py +++ b/projects/Chat-GPT-Discord-Bot/tests.py @@ -7,8 +7,10 @@ load_dotenv(override=True) gpt_api_key = os.getenv("GPT_API_KEY") + + class TestGPT(unittest.TestCase): - @patch('Chat_GPT_Function.OpenAI') + @patch("Chat_GPT_Function.OpenAI") def test_gpt_success(self, mock_openai): mock_client = MagicMock() mock_openai.return_value = mock_client @@ -25,13 +27,13 @@ def test_gpt_success(self, mock_openai): model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "sys_prompt"}, - {"role": "user", "content": "prompt"} + {"role": "user", "content": "prompt"}, ], temperature=0.5, - top_p=1 + top_p=1, ) - @patch('Chat_GPT_Function.OpenAI') + @patch("Chat_GPT_Function.OpenAI") def test_gpt_failure(self, mock_openai): mock_client = MagicMock() mock_openai.return_value = mock_client @@ -40,8 +42,9 @@ def test_gpt_failure(self, mock_openai): with self.assertRaises(Exception): gpt("model", "prompt", "sys_prompt", 0.5) + class TestDALLE3(unittest.TestCase): - @patch('Chat_GPT_Function.OpenAI') + @patch("Chat_GPT_Function.OpenAI") def test_dalle3_success(self, mock_openai): mock_client = MagicMock() mock_openai.return_value = mock_client @@ -60,11 +63,10 @@ def test_dalle3_success(self, mock_openai): size="1792x1024", quality="hd", style="vivid", - n=1 + n=1, ) - - @patch('Chat_GPT_Function.OpenAI') + @patch("Chat_GPT_Function.OpenAI") def test_dalle3_failure(self, mock_openai): mock_client = MagicMock() mock_openai.return_value = mock_client @@ -73,8 +75,9 @@ def test_dalle3_failure(self, mock_openai): with self.assertRaises(Exception): dalle3("prompt", "quality", "size", "style") + class TestDALLE2(unittest.TestCase): - @patch('Chat_GPT_Function.OpenAI') + @patch("Chat_GPT_Function.OpenAI") def test_dalle2_success(self, mock_openai): mock_client = MagicMock() mock_openai.return_value = mock_client @@ -88,13 +91,10 @@ def test_dalle2_success(self, mock_openai): self.assertTrue(result.startswith("https://")) mock_openai.assert_called_once_with(api_key=gpt_api_key) mock_client.images.generate.assert_called_once_with( - model="dall-e-2", - prompt="prompt", - size="256x256", - n=1 + model="dall-e-2", prompt="prompt", size="256x256", n=1 ) - @patch('Chat_GPT_Function.OpenAI') + @patch("Chat_GPT_Function.OpenAI") def test_dalle2_failure(self, mock_openai): mock_client = MagicMock() mock_openai.return_value = mock_client @@ -103,5 +103,6 @@ def test_dalle2_failure(self, mock_openai): with self.assertRaises(Exception): dalle2("prompt", "size") -if __name__ == '__main__': - unittest.main() \ No newline at end of file + +if __name__ == "__main__": + unittest.main() diff --git a/projects/Pokemon Battle/pokemon.py b/projects/Pokemon Battle/pokemon.py index 3d5382aa..2b2877fa 100644 --- a/projects/Pokemon Battle/pokemon.py +++ b/projects/Pokemon Battle/pokemon.py @@ -13,17 +13,18 @@ def delay_print(s): sys.stdout.flush() time.sleep(0.05) + # Create the class class Pokemon: - def __init__(self, name, types, moves, EVs, health='==================='): + def __init__(self, name, types, moves, EVs, health="==================="): # save variables as attributes self.name = name self.types = types self.moves = moves - self.attack = EVs['ATTACK'] - self.defense = EVs['DEFENSE'] + self.attack = EVs["ATTACK"] + self.defense = EVs["DEFENSE"] self.health = health self.bars = 20 # Amount of health bars @@ -36,42 +37,42 @@ def fight(self, Pokemon2): print("TYPE/", self.types) print("ATTACK/", self.attack) print("DEFENSE/", self.defense) - print("LVL/", 3*(1+np.mean([self.attack, self.defense]))) + print("LVL/", 3 * (1 + np.mean([self.attack, self.defense]))) print("\nVS") print(f"\n{Pokemon2.name}") print("TYPE/", Pokemon2.types) print("ATTACK/", Pokemon2.attack) print("DEFENSE/", Pokemon2.defense) - print("LVL/", 3*(1+np.mean([Pokemon2.attack, Pokemon2.defense]))) + print("LVL/", 3 * (1 + np.mean([Pokemon2.attack, Pokemon2.defense]))) time.sleep(2) # Consider type advantages - version = ['Fire', 'Water', 'Grass'] + version = ["Fire", "Water", "Grass"] for i, k in enumerate(version): if self.types == k: # Both are same type if Pokemon2.types == k: - string_1_attack = '\nIts not very effective...' - string_2_attack = '\nIts not very effective...' + string_1_attack = "\nIts not very effective..." + string_2_attack = "\nIts not very effective..." # Pokemon2 is STRONG - if Pokemon2.types == version[(i+1) % 3]: + if Pokemon2.types == version[(i + 1) % 3]: Pokemon2.attack *= 2 Pokemon2.defense *= 2 self.attack /= 2 self.defense /= 2 - string_1_attack = '\nIts not very effective...' - string_2_attack = '\nIts super effective!' + string_1_attack = "\nIts not very effective..." + string_2_attack = "\nIts super effective!" # Pokemon2 is WEAK - if Pokemon2.types == version[(i+2) % 3]: + if Pokemon2.types == version[(i + 2) % 3]: self.attack *= 2 self.defense *= 2 Pokemon2.attack /= 2 Pokemon2.defense /= 2 - string_1_attack = '\nIts super effective!' - string_2_attack = '\nIts not very effective...' + string_1_attack = "\nIts super effective!" + string_2_attack = "\nIts not very effective..." # Now for the actual fighting... # Continue while pokemon still have health @@ -83,7 +84,7 @@ def fight(self, Pokemon2): print(f"Go {self.name}!") for i, x in enumerate(self.moves): print(f"{i+1}.", x) - index = int(input('Pick a move: ')) + index = int(input("Pick a move: ")) delay_print(f"\n{self.name} used {self.moves[index-1]}!") time.sleep(1) delay_print(string_1_attack) @@ -93,17 +94,17 @@ def fight(self, Pokemon2): Pokemon2.health = "" # Add back bars plus defense boost - for j in range(int(Pokemon2.bars+.1*Pokemon2.defense)): + for j in range(int(Pokemon2.bars + 0.1 * Pokemon2.defense)): Pokemon2.health += "=" time.sleep(1) print(f"\n{self.name}\t\tHLTH\t{self.health}") print(f"{Pokemon2.name}\t\tHLTH\t{Pokemon2.health}\n") - time.sleep(.5) + time.sleep(0.5) # Check to see if Pokemon fainted if Pokemon2.bars <= 0: - delay_print("\n..." + Pokemon2.name + ' fainted.') + delay_print("\n..." + Pokemon2.name + " fainted.") break # Pokemon2s turn @@ -111,7 +112,7 @@ def fight(self, Pokemon2): print(f"Go {Pokemon2.name}!") for i, x in enumerate(Pokemon2.moves): print(f"{i+1}.", x) - index = int(input('Pick a move: ')) + index = int(input("Pick a move: ")) delay_print(f"\n{Pokemon2.name} used {Pokemon2.moves[index-1]}!") time.sleep(1) delay_print(string_2_attack) @@ -121,46 +122,80 @@ def fight(self, Pokemon2): self.health = "" # Add back bars plus defense boost - for j in range(int(self.bars+.1*self.defense)): + for j in range(int(self.bars + 0.1 * self.defense)): self.health += "=" time.sleep(1) print(f"{self.name}\t\tHLTH\t{self.health}") print(f"{Pokemon2.name}\t\tHLTH\t{Pokemon2.health}\n") - time.sleep(.5) + time.sleep(0.5) # Check to see if Pokemon fainted if self.bars <= 0: - delay_print("\n..." + self.name + ' fainted.') + delay_print("\n..." + self.name + " fainted.") break money = np.random.choice(5000) delay_print(f"\nOpponent paid you ${money}.\n") -if __name__ == '__main__': +if __name__ == "__main__": # Create Pokemon - Charizard = Pokemon('Charizard', 'Fire', [ - 'Flamethrower', 'Fly', 'Blast Burn', 'Fire Punch'], {'ATTACK': 12, 'DEFENSE': 8}) - Blastoise = Pokemon('Blastoise', 'Water', [ - 'Water Gun', 'Bubblebeam', 'Hydro Pump', 'Surf'], {'ATTACK': 10, 'DEFENSE': 10}) - Venusaur = Pokemon('Venusaur', 'Grass', [ - 'Vine Wip', 'Razor Leaf', 'Earthquake', 'Frenzy Plant'], {'ATTACK': 8, 'DEFENSE': 12}) - - - Charmeleon = Pokemon('Charmeleon', 'Fire', [ - 'Ember', 'Scratch', 'Flamethrower', 'Fire Punch'], {'ATTACK': 6, 'DEFENSE': 5}) - Wartortle = Pokemon('Wartortle', 'Water', [ - 'Bubblebeam', 'Water Gun', 'Headbutt', 'Surf'], {'ATTACK': 5, 'DEFENSE': 5}) - Ivysaur = Pokemon('Ivysaur\t', 'Grass', [ - 'Vine Wip', 'Razor Leaf', 'Bullet Seed', 'Leech Seed'], {'ATTACK': 4, 'DEFENSE': 6}) - - Charmander = Pokemon('Charmander', 'Fire', [ - 'Ember', 'Scratch', 'Tackle', 'Fire Punch'], {'ATTACK': 4, 'DEFENSE': 2}) - Squirtle = Pokemon('Squirtle', 'Water', [ - 'Bubblebeam', 'Tackle', 'Headbutt', 'Surf'], {'ATTACK': 3, 'DEFENSE': 3}) - Bulbasaur = Pokemon('Bulbasaur', 'Grass', [ - 'Vine Wip', 'Razor Leaf', 'Tackle', 'Leech Seed'], {'ATTACK': 2, 'DEFENSE': 4}) - + Charizard = Pokemon( + "Charizard", + "Fire", + ["Flamethrower", "Fly", "Blast Burn", "Fire Punch"], + {"ATTACK": 12, "DEFENSE": 8}, + ) + Blastoise = Pokemon( + "Blastoise", + "Water", + ["Water Gun", "Bubblebeam", "Hydro Pump", "Surf"], + {"ATTACK": 10, "DEFENSE": 10}, + ) + Venusaur = Pokemon( + "Venusaur", + "Grass", + ["Vine Wip", "Razor Leaf", "Earthquake", "Frenzy Plant"], + {"ATTACK": 8, "DEFENSE": 12}, + ) + + Charmeleon = Pokemon( + "Charmeleon", + "Fire", + ["Ember", "Scratch", "Flamethrower", "Fire Punch"], + {"ATTACK": 6, "DEFENSE": 5}, + ) + Wartortle = Pokemon( + "Wartortle", + "Water", + ["Bubblebeam", "Water Gun", "Headbutt", "Surf"], + {"ATTACK": 5, "DEFENSE": 5}, + ) + Ivysaur = Pokemon( + "Ivysaur\t", + "Grass", + ["Vine Wip", "Razor Leaf", "Bullet Seed", "Leech Seed"], + {"ATTACK": 4, "DEFENSE": 6}, + ) + + Charmander = Pokemon( + "Charmander", + "Fire", + ["Ember", "Scratch", "Tackle", "Fire Punch"], + {"ATTACK": 4, "DEFENSE": 2}, + ) + Squirtle = Pokemon( + "Squirtle", + "Water", + ["Bubblebeam", "Tackle", "Headbutt", "Surf"], + {"ATTACK": 3, "DEFENSE": 3}, + ) + Bulbasaur = Pokemon( + "Bulbasaur", + "Grass", + ["Vine Wip", "Razor Leaf", "Tackle", "Leech Seed"], + {"ATTACK": 2, "DEFENSE": 4}, + ) Blastoise.fight(Squirtle) # Get them to fight diff --git a/projects/Quiz Game/main.py b/projects/Quiz Game/main.py index 8c9d4bb3..1464f7f3 100644 --- a/projects/Quiz Game/main.py +++ b/projects/Quiz Game/main.py @@ -1,25 +1,31 @@ -# import the sqlite3 to reterive previous scores +# import the sqlite3 to reterive previous scores import sqlite3 + + # create Conn to have the database file def create_connection(db_file): - """ create a database connection to the SQLite database """ + """create a database connection to the SQLite database""" conn = None try: conn = sqlite3.connect(db_file) except sqlite3.Error as e: print(e) return conn - # store the player's score with their name + + +# store the player's score with their name def save_score(conn, name, score): """ Save the player's score to the database """ - sql = ''' INSERT INTO scores(name, score) - VALUES(?,?) ''' + sql = """ INSERT INTO scores(name, score) + VALUES(?,?) """ cur = conn.cursor() cur.execute(sql, (name, score)) conn.commit() return cur.lastrowid + + # recall the previous scores to display them def get_all_scores(conn): """ @@ -31,6 +37,7 @@ def get_all_scores(conn): rows = cur.fetchall() return rows + # The beginning of the game print("Welcome to AskPython Quiz") @@ -60,7 +67,9 @@ def get_all_scores(conn): print("Wrong Answer :(") # User's answer is incorrect # Question 3 - answer = input("Question 3: What is the name of your favourite website for learning Python?") + answer = input( + "Question 3: What is the name of your favourite website for learning Python?" + ) if answer.lower() == "askpython": score += 1 print("correct") # User's answer is correct, increment the score @@ -68,7 +77,11 @@ def get_all_scores(conn): print("Wrong Answer :(") # User's answer is incorrect # Display the result and user's score - print("Thank you for Playing this small quiz game, you attempted", score, "questions correctly!") + print( + "Thank you for Playing this small quiz game, you attempted", + score, + "questions correctly!", + ) mark = int((score / total_questions) * 100) print(f"Marks obtained: {mark}%") @@ -84,13 +97,13 @@ def get_all_scores(conn): if conn is not None: # Save the player's score save_score(conn, player_name, player_score) - + # Display all scores print("Previous scores:") scores = get_all_scores(conn) for row in scores: print(f"Name: {row[1]}, Score: {row[2]}, Date: {row[3]}") - + conn.close() else: print("Error! Cannot create the database connection.") diff --git a/projects/Quiz Game/setup_db.py b/projects/Quiz Game/setup_db.py index cb3b7c34..9fe5ad00 100644 --- a/projects/Quiz Game/setup_db.py +++ b/projects/Quiz Game/setup_db.py @@ -1,21 +1,24 @@ import sqlite3 + def create_database(): # Connect to the SQLite database (it will create the file if it doesn't exist) - conn = sqlite3.connect('quiz_game.db') + conn = sqlite3.connect("quiz_game.db") # Create a cursor object cursor = conn.cursor() # Create a table to store players' scores - cursor.execute(''' + cursor.execute( + """ CREATE TABLE IF NOT EXISTS scores ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, score INTEGER NOT NULL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP ) - ''') + """ + ) # Commit the changes and close the connection conn.commit() @@ -23,5 +26,6 @@ def create_database(): print("Database and table created successfully.") + if __name__ == "__main__": create_database() diff --git a/projects/Snake Game/src/constants.py b/projects/Snake Game/src/constants.py index 6cfb64e7..d5537822 100644 --- a/projects/Snake Game/src/constants.py +++ b/projects/Snake Game/src/constants.py @@ -24,4 +24,4 @@ class Direction(Enum): DOWN = 4 -Point = namedtuple('Point', ['x', 'y']) +Point = namedtuple("Point", ["x", "y"]) diff --git a/projects/Snake Game/src/display.py b/projects/Snake Game/src/display.py index 898031a1..3b407f48 100644 --- a/projects/Snake Game/src/display.py +++ b/projects/Snake Game/src/display.py @@ -4,6 +4,7 @@ class Display: """Manages the display of the game.""" + def __init__(self): pygame.init() self.width = GameSettings.WIDTH @@ -32,18 +33,25 @@ def update_ui(self, snake, food, score, high_score): def draw_snake(self, snake): for block in snake.blocks: pygame.draw.rect( - self.window, RgbColors.BLUE1, - pygame.Rect(block.x, block.y, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE) + self.window, + RgbColors.BLUE1, + pygame.Rect( + block.x, block.y, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE + ), ) pygame.draw.rect( - self.window, RgbColors.BLUE2, pygame.Rect(block.x + 4, block.y + 4, 12, 12) + self.window, + RgbColors.BLUE2, + pygame.Rect(block.x + 4, block.y + 4, 12, 12), ) def draw_food(self, food): pygame.draw.rect( self.window, RgbColors.RED, - pygame.Rect(food.x, food.y, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE), + pygame.Rect( + food.x, food.y, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE + ), ) def draw_score(self, score): @@ -58,27 +66,35 @@ def render_game_over(self): text_height = game_over_display.get_height() text_x = (self.width - text_width) // 2 text_y = (self.height // 4) - (text_height // 2) - self.window.blit(game_over_display, - [text_x, text_y]) + self.window.blit(game_over_display, [text_x, text_y]) pygame.display.flip() def render_play_again(self): self.font = pygame.font.Font(None, 32) - play_again_display = self.font.render("Play again? (Y/N)", True, RgbColors.WHITE) - display_box = play_again_display.get_rect(center=(self.width // 2, self.height // 2)) + play_again_display = self.font.render( + "Play again? (Y/N)", True, RgbColors.WHITE + ) + display_box = play_again_display.get_rect( + center=(self.width // 2, self.height // 2) + ) self.window.blit(play_again_display, display_box) pygame.display.flip() def render_high_score(self, high_score): - high_score_display = self.font.render(f"High Score: {high_score}", True, RgbColors.WHITE) - self.window.blit(high_score_display, [self.width - high_score_display.get_width(), 0]) + high_score_display = self.font.render( + f"High Score: {high_score}", True, RgbColors.WHITE + ) + self.window.blit( + high_score_display, [self.width - high_score_display.get_width(), 0] + ) def render_new_high_score(self, new_high_score): - new_high_score_display = self.font.render(f"New High Score: {new_high_score}", True, RgbColors.WHITE) + new_high_score_display = self.font.render( + f"New High Score: {new_high_score}", True, RgbColors.WHITE + ) text_width = new_high_score_display.get_width() text_height = new_high_score_display.get_height() text_x = (self.width - text_width) // 2 text_y = (self.height // 3) - (text_height // 2) - self.window.blit(new_high_score_display, - [text_x, text_y]) + self.window.blit(new_high_score_display, [text_x, text_y]) pygame.display.flip() diff --git a/projects/Snake Game/src/game.py b/projects/Snake Game/src/game.py index 86796078..c36308a9 100644 --- a/projects/Snake Game/src/game.py +++ b/projects/Snake Game/src/game.py @@ -8,6 +8,7 @@ class Game: """Manages the gameplay logic and its user interactions.""" + def __init__(self): self.display = Display() self.snake = Snake() @@ -41,10 +42,10 @@ def is_collision(self): """ # Snake hits boundary if ( - self.snake.head.x > self.display.width - self.snake.block_size - or self.snake.head.x < 0 - or self.snake.head.y > self.display.height - self.snake.block_size - or self.snake.head.y < 0 + self.snake.head.x > self.display.width - self.snake.block_size + or self.snake.head.x < 0 + or self.snake.head.y > self.display.height - self.snake.block_size + or self.snake.head.y < 0 ): return True # Snake hits itself @@ -87,10 +88,22 @@ def play_step(self): def place_food(self): """Randomly places the food on the screen.""" - x = random.randint(0, ( - self.display.width - GameSettings.BLOCK_SIZE) // GameSettings.BLOCK_SIZE) * GameSettings.BLOCK_SIZE - y = random.randint(0, ( - self.display.height - GameSettings.BLOCK_SIZE) // GameSettings.BLOCK_SIZE) * GameSettings.BLOCK_SIZE + x = ( + random.randint( + 0, + (self.display.width - GameSettings.BLOCK_SIZE) + // GameSettings.BLOCK_SIZE, + ) + * GameSettings.BLOCK_SIZE + ) + y = ( + random.randint( + 0, + (self.display.height - GameSettings.BLOCK_SIZE) + // GameSettings.BLOCK_SIZE, + ) + * GameSettings.BLOCK_SIZE + ) self.food = Point(x, y) if self.food in self.snake.blocks: self.place_food() @@ -117,9 +130,9 @@ def restart_game(self): def load_high_score(self): """Loads the high score from a JSON file.""" try: - with open('high_score.json', 'r') as file: + with open("high_score.json", "r") as file: data = json.load(file) - return data.get('high_score') + return data.get("high_score") except FileNotFoundError: return 0 @@ -128,5 +141,5 @@ def update_high_score(self, new_score): high_score = self.load_high_score() if new_score > high_score: data = {"high_score": new_score} - with open('high_score.json', 'w') as file: + with open("high_score.json", "w") as file: json.dump(data, file) diff --git a/projects/Snake Game/src/snake.py b/projects/Snake Game/src/snake.py index 1fc3e89f..74ad8419 100644 --- a/projects/Snake Game/src/snake.py +++ b/projects/Snake Game/src/snake.py @@ -3,6 +3,7 @@ class Snake: """Represents the snake in the game.""" + def __init__(self, init_length=3): """Initializes the snake. @@ -11,8 +12,10 @@ def __init__(self, init_length=3): """ self.head = Point(GameSettings.WIDTH / 2, GameSettings.HEIGHT / 2) self.block_size = GameSettings.BLOCK_SIZE - self.blocks = ([self.head] + - [Point(self.head.x - (i * self.block_size), self.head.y) for i in range(1, init_length)]) + self.blocks = [self.head] + [ + Point(self.head.x - (i * self.block_size), self.head.y) + for i in range(1, init_length) + ] self.direction = Direction.RIGHT def move(self, direction): diff --git a/projects/Snake Game/tests/test_display.py b/projects/Snake Game/tests/test_display.py index 3a4208de..6ac8b85f 100644 --- a/projects/Snake Game/tests/test_display.py +++ b/projects/Snake Game/tests/test_display.py @@ -15,12 +15,14 @@ def setUp(self): self.display.width = 640 self.display.height = 480 - @patch('pygame.init') - @patch('pygame.font.Font') - @patch('pygame.display.set_mode') - @patch('pygame.display.set_caption') - @patch('pygame.time.Clock') - def test_init(self, mock_init, mock_font, mock_set_mode, mock_set_caption, mock_clock): + @patch("pygame.init") + @patch("pygame.font.Font") + @patch("pygame.display.set_mode") + @patch("pygame.display.set_caption") + @patch("pygame.time.Clock") + def test_init( + self, mock_init, mock_font, mock_set_mode, mock_set_caption, mock_clock + ): mock_init.return_value = True mock_font_instance = MagicMock() mock_font.return_value = mock_font_instance @@ -39,12 +41,14 @@ def test_init(self, mock_init, mock_font, mock_set_mode, mock_set_caption, mock_ self.assertIsInstance(self.display.window, MagicMock) self.assertIsInstance(self.display.clock, MagicMock) - @patch('pygame.init') - @patch('pygame.display.set_mode') - @patch('pygame.display.set_caption') - @patch('pygame.font.Font') - @patch('pygame.time.Clock') - def test_init(self, mock_clock, mock_font, mock_set_caption, mock_set_mode, mock_init): + @patch("pygame.init") + @patch("pygame.display.set_mode") + @patch("pygame.display.set_caption") + @patch("pygame.font.Font") + @patch("pygame.time.Clock") + def test_init( + self, mock_clock, mock_font, mock_set_caption, mock_set_mode, mock_init + ): display = Display() mock_init.assert_called_once() mock_font.assert_called_once() @@ -56,11 +60,13 @@ def test_init(self, mock_clock, mock_font, mock_set_caption, mock_set_mode, mock self.assertIsInstance(display.window, MagicMock) self.assertIsInstance(display.clock, MagicMock) - @patch('pygame.draw.rect') - @patch('pygame.font.Font') - @patch('pygame.display.flip') - @patch('pygame.display.set_mode') - def test_update_ui(self, mock_set_mode, mock_display_flip, mock_font, mock_draw_rect): + @patch("pygame.draw.rect") + @patch("pygame.font.Font") + @patch("pygame.display.flip") + @patch("pygame.display.set_mode") + def test_update_ui( + self, mock_set_mode, mock_display_flip, mock_font, mock_draw_rect + ): mock_window = mock_set_mode.return_value mock_font_instance = mock_font.return_value mock_font_instance.render = MagicMock() @@ -76,31 +82,39 @@ def test_update_ui(self, mock_set_mode, mock_display_flip, mock_font, mock_draw_ mock_font_instance.render.assert_called() mock_display_flip.assert_called() - @patch('pygame.draw.rect') + @patch("pygame.draw.rect") def test_draw_snake(self, mock_draw_rect): snake = MagicMock() - snake.blocks = [Point(0, 0), Point(GameSettings.BLOCK_SIZE, 0), Point(2 * GameSettings.BLOCK_SIZE, 0)] + snake.blocks = [ + Point(0, 0), + Point(GameSettings.BLOCK_SIZE, 0), + Point(2 * GameSettings.BLOCK_SIZE, 0), + ] self.display.draw_snake(snake) # Check for correct snake block rendering mock_draw_rect.assert_any_call( - self.display.window, RgbColors.BLUE1, pygame.Rect(0, 0, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE) + self.display.window, + RgbColors.BLUE1, + pygame.Rect(0, 0, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE), ) mock_draw_rect.assert_any_call( self.display.window, RgbColors.BLUE2, pygame.Rect(4, 4, 12, 12) ) - @patch('pygame.draw.rect') + @patch("pygame.draw.rect") def test_draw_food(self, mock_draw_rect): food = Point(0, 0) self.display.draw_food(food) # Check for correct food rendering mock_draw_rect.assert_called_once_with( - self.display.window, RgbColors.RED, pygame.Rect(0, 0, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE) + self.display.window, + RgbColors.RED, + pygame.Rect(0, 0, GameSettings.BLOCK_SIZE, GameSettings.BLOCK_SIZE), ) - @patch('pygame.font.Font') + @patch("pygame.font.Font") def test_draw_score(self, mock_font): score = 10 mock_font_instance = mock_font.return_value @@ -116,8 +130,8 @@ def test_draw_score(self, mock_font): mock_font_instance.render.assert_called_once() mock_window_surface.blit.assert_called_once() - @patch('pygame.display.flip') - @patch('pygame.font.Font') + @patch("pygame.display.flip") + @patch("pygame.font.Font") def test_render_game_over(self, mock_font, mock_flip): mock_font_instance = mock_font.return_value mock_render = MagicMock() @@ -132,8 +146,8 @@ def test_render_game_over(self, mock_font, mock_flip): mock_window_surface.blit.assert_called_once() mock_flip.assert_called_once() - @patch('pygame.display.flip') - @patch('pygame.font.Font') + @patch("pygame.display.flip") + @patch("pygame.font.Font") def test_render_play_again(self, mock_font, mock_flip): mock_font_instance = mock_font.return_value mock_render = MagicMock() @@ -147,7 +161,7 @@ def test_render_play_again(self, mock_font, mock_flip): mock_window_surface.blit.assert_called_once() mock_flip.assert_called_once() - @patch('pygame.font.Font') + @patch("pygame.font.Font") def test_render_high_score(self, mock_font): high_score = 100 mock_font_instance = mock_font.return_value @@ -163,8 +177,8 @@ def test_render_high_score(self, mock_font): mock_font_instance.render.assert_called_once() mock_window_surface.blit.assert_called_once() - @patch('pygame.display.flip') - @patch('pygame.font.Font') + @patch("pygame.display.flip") + @patch("pygame.font.Font") def test_render_new_high_score(self, mock_font, mock_flip): mock_font_instance = mock_font.return_value mock_render = MagicMock() @@ -179,5 +193,5 @@ def test_render_new_high_score(self, mock_font, mock_flip): mock_flip.assert_called_once() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/projects/Snake Game/tests/test_game.py b/projects/Snake Game/tests/test_game.py index 192c5d22..4be8b894 100644 --- a/projects/Snake Game/tests/test_game.py +++ b/projects/Snake Game/tests/test_game.py @@ -25,11 +25,13 @@ def test_is_collision(self): self.game.snake.head = self.game.snake.blocks[1] self.assertTrue(self.game.is_collision()) - @patch('pygame.event.get') - @patch('pygame.draw.rect') - @patch('pygame.display.flip') - @patch('pygame.font.Font') - def test_play_step(self, mock_font, mock_display_flip, mock_draw_rect, mock_event_get): + @patch("pygame.event.get") + @patch("pygame.draw.rect") + @patch("pygame.display.flip") + @patch("pygame.font.Font") + def test_play_step( + self, mock_font, mock_display_flip, mock_draw_rect, mock_event_get + ): mock_event_get.return_value = [] mock_font_instance = MagicMock() self.game.display.window = MagicMock(spec=pygame.Surface) @@ -41,38 +43,46 @@ def test_play_step(self, mock_font, mock_display_flip, mock_draw_rect, mock_even init_score = self.game.score init_head_position = self.game.snake.head # Place food in front of snake - self.game.food = Point(init_head_position.x + GameSettings.BLOCK_SIZE, init_head_position.y) + self.game.food = Point( + init_head_position.x + GameSettings.BLOCK_SIZE, init_head_position.y + ) self.game.play_step() self.assertEqual(len(self.game.snake.blocks), init_snake_length + 1) self.assertEqual(self.game.score, init_score + 1) # Check snake head is one block in front of the initial head position - new_head_position = Point(init_head_position.x + GameSettings.BLOCK_SIZE, init_head_position.y) + new_head_position = Point( + init_head_position.x + GameSettings.BLOCK_SIZE, init_head_position.y + ) self.assertEqual(self.game.snake.head, new_head_position) def test_place_food(self): self.game.place_food() self.assertNotIn(self.game.food, self.game.snake.blocks) - @patch('pygame.event.get') + @patch("pygame.event.get") def test_play_again_y(self, mock_event_get): mock_event_get.return_value = [MagicMock(type=pygame.KEYDOWN, key=pygame.K_y)] value = self.game.play_again() self.assertTrue(value) - @patch('pygame.event.get') + @patch("pygame.event.get") def test_play_again_return(self, mock_event_get): - mock_event_get.return_value = [MagicMock(type=pygame.KEYDOWN, key=pygame.K_RETURN)] + mock_event_get.return_value = [ + MagicMock(type=pygame.KEYDOWN, key=pygame.K_RETURN) + ] value = self.game.play_again() self.assertTrue(value) - @patch('pygame.event.get') + @patch("pygame.event.get") def test_play_again_n(self, mock_event_get): mock_event_get.return_value = [MagicMock(type=pygame.KEYDOWN, key=pygame.K_n)] - @patch('pygame.event.get') + @patch("pygame.event.get") def test_play_again_esc(self, mock_event_get): - mock_event_get.return_value = [MagicMock(type=pygame.KEYDOWN, key=pygame.K_ESCAPE)] + mock_event_get.return_value = [ + MagicMock(type=pygame.KEYDOWN, key=pygame.K_ESCAPE) + ] def test_restart_game(self): self.game.snake = Snake(init_length=10) @@ -85,19 +95,19 @@ def test_restart_game(self): self.assertIsNotNone(self.game.food) self.assertEqual(init_high_score, self.game.high_score) - @patch('builtins.open', side_effect=FileNotFoundError) + @patch("builtins.open", side_effect=FileNotFoundError) def test_load_high_score_no_json_file(self, mock_open): returned_high_score = self.game.load_high_score() self.assertEqual(returned_high_score, 0) - @patch('builtins.open', return_value=io.StringIO('{"high_score": 100}')) + @patch("builtins.open", return_value=io.StringIO('{"high_score": 100}')) def test_load_high_score_existing_file(self, mock_open): returned_high_score = self.game.load_high_score() self.assertEqual(returned_high_score, 100) - @patch('builtins.open', new_callable=mock_open) - @patch('json.dump') - @patch('json.load', return_value={"high_score": 100}) + @patch("builtins.open", new_callable=mock_open) + @patch("json.dump") + @patch("json.load", return_value={"high_score": 100}) def test_update_high_score(self, mock_load, mock_dump, mock_open): mock_file = mock_open.return_value mock_file.__enter__.return_value = mock_file @@ -105,24 +115,26 @@ def test_update_high_score(self, mock_load, mock_dump, mock_open): self.game.update_high_score(200) # Check file is opened in read-mode for loading high score, and opened in write-mode for updating high score - mock_open.assert_any_call('high_score.json', 'r') - mock_open.assert_any_call('high_score.json', 'w') + mock_open.assert_any_call("high_score.json", "r") + mock_open.assert_any_call("high_score.json", "w") mock_dump.assert_called_with({"high_score": 200}, mock_file) - @patch('builtins.open', new_callable=mock_open) - @patch('json.dump') - @patch('json.load', return_value={"high_score": 100}) - def test_update_high_score_with_score_lower_than_high_score(self, mock_load, mock_dump, mock_open): + @patch("builtins.open", new_callable=mock_open) + @patch("json.dump") + @patch("json.load", return_value={"high_score": 100}) + def test_update_high_score_with_score_lower_than_high_score( + self, mock_load, mock_dump, mock_open + ): mock_file = mock_open.return_value mock_file.__enter__.return_value = mock_file self.game.update_high_score(50) # Check high score is not changed - mock_open.assert_called_once_with('high_score.json', 'r') + mock_open.assert_called_once_with("high_score.json", "r") mock_dump.assert_not_called() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/projects/Snake Game/tests/test_snake.py b/projects/Snake Game/tests/test_snake.py index 2de74486..587c2610 100644 --- a/projects/Snake Game/tests/test_snake.py +++ b/projects/Snake Game/tests/test_snake.py @@ -8,7 +8,9 @@ def setUp(self): self.snake = Snake() def test_init(self): - self.assertEqual(self.snake.head, Point(GameSettings.WIDTH / 2, GameSettings.HEIGHT / 2)) + self.assertEqual( + self.snake.head, Point(GameSettings.WIDTH / 2, GameSettings.HEIGHT / 2) + ) self.assertEqual(self.snake.block_size, GameSettings.BLOCK_SIZE) self.assertEqual(len(self.snake.blocks), 3) self.assertEqual(self.snake.direction, Direction.RIGHT) @@ -26,10 +28,10 @@ def test_self_collision(self): self.snake.head, Point(80, 100), Point(60, 100), - Point(100, 100) + Point(100, 100), ] self.assertTrue(self.snake.self_collision()) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/projects/computer-algebra/main.py b/projects/computer-algebra/main.py index dc6c36d4..bd69856d 100644 --- a/projects/computer-algebra/main.py +++ b/projects/computer-algebra/main.py @@ -17,7 +17,7 @@ def selection_cb(sender, app_data, user_data): def show_info(title, message, selection_callback): """ Display an information message box with title, message, and callback. - + References: https://github.com/hoffstadt/DearPyGui/discussions/1002 """ @@ -27,88 +27,101 @@ def show_info(title, message, selection_callback): viewport_width = dpg.get_viewport_client_width() viewport_height = dpg.get_viewport_client_height() - with dpg.window(tag='popup-window', label=title, modal=True, no_close=True) as modal_id: + with dpg.window( + tag="popup-window", label=title, modal=True, no_close=True + ) as modal_id: dpg.add_text(message) - dpg.add_button(label="Ok", width=75, user_data=(modal_id, True), callback=selection_callback) + dpg.add_button( + label="Ok", + width=75, + user_data=(modal_id, True), + callback=selection_callback, + ) dpg.add_same_line() - dpg.add_button(label="Cancel", width=75, user_data=(modal_id, False), callback=selection_callback) + dpg.add_button( + label="Cancel", + width=75, + user_data=(modal_id, False), + callback=selection_callback, + ) # guarantee these commands happen in another frame dpg.split_frame() width = dpg.get_item_width(modal_id) height = dpg.get_item_height(modal_id) - dpg.set_item_pos(modal_id, [viewport_width // 2 - width // 2, viewport_height // 2 - height // 2]) + dpg.set_item_pos( + modal_id, [viewport_width // 2 - width // 2, viewport_height // 2 - height // 2] + ) # Callbacks and Helpers def on_evaluate(sender, app_data, user_data): """Callback function for the 'Evaluate' button.""" # Get the Command - cmd = dpg.get_value('radio-cmds') + cmd = dpg.get_value("radio-cmds") cmd_func = NEWTON_CMDS_DICT[cmd] # Get the Expression - expr = dpg.get_value('inp-expr') - - if expr.strip() in ['']: - show_info( - 'Error', - 'Please use valid mathematical expressions.', - selection_cb - ) + expr = dpg.get_value("inp-expr") + + if expr.strip() in [""]: + show_info("Error", "Please use valid mathematical expressions.", selection_cb) # Clear Expression - dpg.set_value('inp-expr', '') + dpg.set_value("inp-expr", "") return # Evaluate response = cmd_func(expr) result = response.result - dpg.set_value('label-output', result) + dpg.set_value("label-output", result) dpg.create_context() -dpg.create_viewport(title='Computer Algebra', width=1300, height=750) - -with dpg.window(tag='inp-window', - label="Input", - pos=[0, 0], - autosize=True, - # width=1150, - # height=350, - no_collapse=True, - no_close=True, - ): +dpg.create_viewport(title="Computer Algebra", width=1300, height=750) + +with dpg.window( + tag="inp-window", + label="Input", + pos=[0, 0], + autosize=True, + # width=1150, + # height=350, + no_collapse=True, + no_close=True, +): # Radio Button for Commands dpg.add_radio_button( horizontal=True, - tag='radio-cmds', - items=[cmd for cmd in NEWTON_CMDS_DICT.keys()] + tag="radio-cmds", + items=[cmd for cmd in NEWTON_CMDS_DICT.keys()], ) # Text Area for Mathematical Expression dpg.add_input_text( - tag='inp-expr', + tag="inp-expr", width=int(1150 * 0.8), ) # Button for Evaluating Command and Expression dpg.add_button(label="Evaluate", callback=on_evaluate) -with dpg.window(tag='out-window', - pos=[0, 100], - label="Output", - # width=700, - # height=350, - autosize=True, - no_collapse=True, - no_close=True, - ): +with dpg.window( + tag="out-window", + pos=[0, 100], + label="Output", + # width=700, + # height=350, + autosize=True, + no_collapse=True, + no_close=True, +): # Use Label for Output - dpg.add_text(tag='label-output', - label='Result', - show_label=True, - ) + dpg.add_text( + tag="label-output", + label="Result", + show_label=True, + ) dpg.setup_dearpygui() dpg.show_viewport() diff --git a/projects/computer-algebra/newton_command.py b/projects/computer-algebra/newton_command.py index e38e1e88..8212da05 100644 --- a/projects/computer-algebra/newton_command.py +++ b/projects/computer-algebra/newton_command.py @@ -7,6 +7,7 @@ @dataclass(frozen=True) class NewtonResponse: """Newton API Response.""" + operation: str expression: str result: str @@ -20,7 +21,7 @@ class NewtonCommand(CmdBase): """Base class for all the Newton API Commands.""" def __init__(self, operation: str): - super().__init__(operation, 'https://newton.now.sh/api/v2') + super().__init__(operation, "https://newton.now.sh/api/v2") def command(self, expr: str) -> NewtonResponse: """ @@ -49,46 +50,48 @@ def command(self, expr: str) -> NewtonResponse: response_data = response.json() # Extract relevant data from the response - operation = response_data['operation'] - expression = response_data['expression'] - result = response_data['result'] + operation = response_data["operation"] + expression = response_data["expression"] + result = response_data["result"] # Create and return a NewtonResponse object - return NewtonResponse(operation=operation, expression=expression, result=result) + return NewtonResponse( + operation=operation, expression=expression, result=result + ) else: - raise NewtonCmdException(f'{response.text}') - - -newton_simplify = NewtonCommand('simplify').command -newton_factor = NewtonCommand('factor').command -newton_derive = NewtonCommand('derive').command -newton_integrate = NewtonCommand('integrate').command -newton_zeroes = NewtonCommand('zeroes').command -newton_tangent = NewtonCommand('tangent').command -newton_area = NewtonCommand('area').command -newton_cos = NewtonCommand('cos').command -newton_sin = NewtonCommand('sin').command -newton_tan = NewtonCommand('tan').command -newton_arc_cos = NewtonCommand('arccos').command -newton_arc_sin = NewtonCommand('arcsin').command -newton_arc_tan = NewtonCommand('arctan').command -newton_abs = NewtonCommand('abs').command -newton_log = NewtonCommand('log').command + raise NewtonCmdException(f"{response.text}") + + +newton_simplify = NewtonCommand("simplify").command +newton_factor = NewtonCommand("factor").command +newton_derive = NewtonCommand("derive").command +newton_integrate = NewtonCommand("integrate").command +newton_zeroes = NewtonCommand("zeroes").command +newton_tangent = NewtonCommand("tangent").command +newton_area = NewtonCommand("area").command +newton_cos = NewtonCommand("cos").command +newton_sin = NewtonCommand("sin").command +newton_tan = NewtonCommand("tan").command +newton_arc_cos = NewtonCommand("arccos").command +newton_arc_sin = NewtonCommand("arcsin").command +newton_arc_tan = NewtonCommand("arctan").command +newton_abs = NewtonCommand("abs").command +newton_log = NewtonCommand("log").command NEWTON_CMDS_DICT = { - 'simplify': newton_simplify, - 'factor': newton_factor, - 'derive': newton_derive, - 'integrate': newton_integrate, - 'zeroes': newton_zeroes, - 'tangent': newton_tangent, - 'area': newton_area, - 'cos': newton_cos, - 'sin': newton_sin, - 'tan': newton_tan, - 'arccos': newton_arc_cos, - 'arcsin': newton_arc_sin, - 'arctan': newton_arc_tan, - 'abs': newton_abs, - 'log': newton_log + "simplify": newton_simplify, + "factor": newton_factor, + "derive": newton_derive, + "integrate": newton_integrate, + "zeroes": newton_zeroes, + "tangent": newton_tangent, + "area": newton_area, + "cos": newton_cos, + "sin": newton_sin, + "tan": newton_tan, + "arccos": newton_arc_cos, + "arcsin": newton_arc_sin, + "arctan": newton_arc_tan, + "abs": newton_abs, + "log": newton_log, } From 2860a987a09b37cf204d6672de55528bb2bfe646 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 7 Jun 2024 11:11:06 +0800 Subject: [PATCH 14/16] update test_calculate_age.py code --- feature-branch.diff | 254 ++++++++++++++++++ .../Calculate Age/tests/test_calculate_age.py | 8 +- 2 files changed, 259 insertions(+), 3 deletions(-) create mode 100644 feature-branch.diff diff --git a/feature-branch.diff b/feature-branch.diff new file mode 100644 index 00000000..79e44d46 --- /dev/null +++ b/feature-branch.diff @@ -0,0 +1,254 @@ +diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py +deleted file mode 100644 +index a7dc34f..0000000 +--- a/projects/Calculate Age/calculate.py ++++ /dev/null +@@ -1,49 +0,0 @@ +-import time +-from calendar import isleap +- +- +-# judge the leap year +-def judge_leap_year(year): +- if isleap(year): +- return True +- else: +- return False +- +- +-# returns the number of days in each month +-def month_days(month, leap_year): +- if month in [1, 3, 5, 7, 8, 10, 12]: +- return 31 +- elif month in [4, 6, 9, 11]: +- return 30 +- elif month == 2 and leap_year: +- return 29 +- elif month == 2 and (not leap_year): +- return 28 +- +- +-name = input("input your name: ") +-age = input("input your age: ") +-localtime = time.localtime(time.time()) +- +-year = int(age) +-month = year * 12 + localtime.tm_mon +-day = 0 +- +-begin_year = int(localtime.tm_year) - year +-end_year = begin_year + year +- +-# calculate the days +-for y in range(begin_year, end_year): +- if judge_leap_year(y): +- day = day + 366 +- else: +- day = day + 365 +- +-leap_year = judge_leap_year(localtime.tm_year) +-for m in range(1, localtime.tm_mon): +- day = day + month_days(m, leap_year) +- +-day = day + localtime.tm_mday +-print("%s's age is %d years or " % (name, year), end="") +-print("%d months or %d days" % (month, day)) +diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py +new file mode 100644 +index 0000000..e69de29 +diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py +new file mode 100644 +index 0000000..193fb64 +--- /dev/null ++++ b/projects/Calculate Age/src/calculate_age.py +@@ -0,0 +1,42 @@ ++import time ++from utilize_date import judge_leap_year, month_days ++ ++ ++def age_calculator(name, age): ++ """ ++ Calculate user's age in years, month, and days ++ based on current date and print. ++ ++ Args: ++ name (str): user's name. ++ age (int): user's age in years. ++ ++ Returns: ++ None. ++ """ ++ localtime = time.localtime(time.time()) ++ ++ year = int(age) ++ month = year * 12 + localtime.tm_mon ++ day = 0 ++ ++ begin_year = int(localtime.tm_year) - year ++ end_year = begin_year + year ++ ++ for y in range(begin_year, end_year): ++ if judge_leap_year(y): ++ day += 366 ++ else: ++ day += 365 ++ ++ leap_year = judge_leap_year(localtime.tm_year) ++ for m in range(1, localtime.tm_mon): ++ day += month_days(m, leap_year) ++ ++ day += localtime.tm_mday ++ ++ return f"{name}'s age is {year} years or {month} months or {day} days" ++ ++ ++ ++ +diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py +new file mode 100644 +index 0000000..b775235 +--- /dev/null ++++ b/projects/Calculate Age/src/main.py +@@ -0,0 +1,35 @@ ++from calculate_age import age_calculator ++ ++ ++def main(): ++ """ ++ the user to input name and age, validate input, ++ and calculates and displays the user age in years, months and days. ++ ++ Args: ++ None. ++ ++ Return: ++ None. ++ """ ++ input_name = input("input your name: ") ++ ++ while True: ++ input_age = input("input your age: ") ++ try: ++ string_to_int_age = int(input_age) ++ if string_to_int_age <= 0: ++ print("Please input a positive number.") ++ else: ++ break ++ except ValueError: ++ print("Please input a valid age.") ++ ++ result = age_calculator(input_name, string_to_int_age) ++ ++ print(result) ++ ++if __name__ == "__main__": ++ main() ++ ++ +diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py +new file mode 100644 +index 0000000..8d8b129 +--- /dev/null ++++ b/projects/Calculate Age/src/utilize_date.py +@@ -0,0 +1,36 @@ ++from calendar import isleap ++ ++ ++def judge_leap_year(year): ++ """ ++ judge the leap year. ++ ++ Args: ++ year (int): To check the year. ++ return: ++ bool: Ture if the year is a leap year, False otherwise. ++ """ ++ if isleap(year): ++ return True ++ else: ++ return False ++ ++ ++def month_days(month, leap_year): ++ """ ++ Returns the number of days in each month ++ ++ Args: ++ month (int): The month 1-12. ++ ++ Returns: ++ int: The number of days in the month. ++ """ ++ if month in [1, 3, 5, 7, 8, 10, 12]: ++ return 31 ++ elif month in [4, 6, 9, 11]: ++ return 30 ++ elif month == 2 and leap_year: ++ return 29 ++ elif month == 2 and (not leap_year): ++ return 28 +diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py +new file mode 100644 +index 0000000..e69de29 +diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py +new file mode 100644 +index 0000000..af0c07b +--- /dev/null ++++ b/projects/Calculate Age/tests/test_calculate_age.py +@@ -0,0 +1,25 @@ ++import time ++from unittest.mock import patch ++from calculate_age import age_calculator ++ ++@patch('time.time', return_value=1621848668.0) ++def test_age_calculator(mock_time): ++ name = "Chloe" ++ age = 30 ++ expect_output = "Chloe's age is 30 years or 365 months or 11102 days" ++ assert age_calculator(name, age) == expect_output ++ ++def test_age_calculator_negative_age(): ++ name = "Emma" ++ age = -5 ++ try: ++ age_calculator(name, age) ++ except ValueError as e: ++ assert str(e) == "Please input a positive number." ++ ++ ++def test_age_calculator_leap_year(): ++ name = "David" ++ age = 30 ++ expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" ++ assert age_calculator(name, age) == expect_output_leap_year +diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/tests/test_utilize_date.py +similarity index 83% +rename from projects/Calculate Age/test_calculate.py +rename to projects/Calculate Age/tests/test_utilize_date.py +index 369ac65..54e5efa 100644 +--- a/projects/Calculate Age/test_calculate.py ++++ b/projects/Calculate Age/tests/test_utilize_date.py +@@ -1,5 +1,6 @@ + import pytest +-from calculate import judge_leap_year, month_days ++from utilize_date import judge_leap_year, month_days ++ + + def test_judge_leap_year(): + assert judge_leap_year(2000) == True +@@ -9,6 +10,7 @@ def test_judge_leap_year(): + assert judge_leap_year(2400) == True + assert judge_leap_year(2100) == False + ++ + def test_month_days(): + assert month_days(7, False) == 31 + assert month_days(4, True) == 30 +@@ -17,4 +19,5 @@ def test_month_days(): + assert month_days(1, False) == 31 + assert month_days(11, True) == 30 + +-# "pytest -s test_calculate.py" to test this file +\ No newline at end of file ++ ++# "pytest -s test_utilize_date.py" to test this file diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py index 8fa6d389..60fdf39f 100644 --- a/projects/Calculate Age/tests/test_calculate_age.py +++ b/projects/Calculate Age/tests/test_calculate_age.py @@ -1,7 +1,7 @@ -import time from unittest.mock import patch from calculate_age import age_calculator + @patch('time.time', return_value=1621848668.0) def test_age_calculator(mock_time): """ @@ -14,6 +14,7 @@ def test_age_calculator(mock_time): expect_output = "Chloe's age is 30 years or 365 months or 11102 days" assert age_calculator(name, age) == expect_output + def test_age_calculator_negative_age(): """ Tests the age_calculator function for negative age input @@ -27,12 +28,13 @@ def test_age_calculator_negative_age(): assert str(e) == "Please input a positive number." -def test_age_calculator_leap_year(): +@patch('time.time', return_value=1621848668.0) +def test_age_calculator_leap_year(mock_time): """ Test the age_calculator function considering leap years Check for expect_output_leap_year comparing the real output considering leap years """ name = "David" age = 30 - expect_output_leap_year = "David's age is 30 years or 366 months or 11115 days" + expect_output_leap_year = "David's age is 30 years or 365 months or 11102 days" assert age_calculator(name, age) == expect_output_leap_year From 3e7167d45c3a10807599333ff482661a912d33b4 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 7 Jun 2024 11:30:16 +0800 Subject: [PATCH 15/16] remove feature-branch.diff --- feature-branch.diff | 254 -------------------------------------------- 1 file changed, 254 deletions(-) delete mode 100644 feature-branch.diff diff --git a/feature-branch.diff b/feature-branch.diff deleted file mode 100644 index 79e44d46..00000000 --- a/feature-branch.diff +++ /dev/null @@ -1,254 +0,0 @@ -diff --git a/projects/Calculate Age/calculate.py b/projects/Calculate Age/calculate.py -deleted file mode 100644 -index a7dc34f..0000000 ---- a/projects/Calculate Age/calculate.py -+++ /dev/null -@@ -1,49 +0,0 @@ --import time --from calendar import isleap -- -- --# judge the leap year --def judge_leap_year(year): -- if isleap(year): -- return True -- else: -- return False -- -- --# returns the number of days in each month --def month_days(month, leap_year): -- if month in [1, 3, 5, 7, 8, 10, 12]: -- return 31 -- elif month in [4, 6, 9, 11]: -- return 30 -- elif month == 2 and leap_year: -- return 29 -- elif month == 2 and (not leap_year): -- return 28 -- -- --name = input("input your name: ") --age = input("input your age: ") --localtime = time.localtime(time.time()) -- --year = int(age) --month = year * 12 + localtime.tm_mon --day = 0 -- --begin_year = int(localtime.tm_year) - year --end_year = begin_year + year -- --# calculate the days --for y in range(begin_year, end_year): -- if judge_leap_year(y): -- day = day + 366 -- else: -- day = day + 365 -- --leap_year = judge_leap_year(localtime.tm_year) --for m in range(1, localtime.tm_mon): -- day = day + month_days(m, leap_year) -- --day = day + localtime.tm_mday --print("%s's age is %d years or " % (name, year), end="") --print("%d months or %d days" % (month, day)) -diff --git a/projects/Calculate Age/src/__init__.py b/projects/Calculate Age/src/__init__.py -new file mode 100644 -index 0000000..e69de29 -diff --git a/projects/Calculate Age/src/calculate_age.py b/projects/Calculate Age/src/calculate_age.py -new file mode 100644 -index 0000000..193fb64 ---- /dev/null -+++ b/projects/Calculate Age/src/calculate_age.py -@@ -0,0 +1,42 @@ -+import time -+from utilize_date import judge_leap_year, month_days -+ -+ -+def age_calculator(name, age): -+ """ -+ Calculate user's age in years, month, and days -+ based on current date and print. -+ -+ Args: -+ name (str): user's name. -+ age (int): user's age in years. -+ -+ Returns: -+ None. -+ """ -+ localtime = time.localtime(time.time()) -+ -+ year = int(age) -+ month = year * 12 + localtime.tm_mon -+ day = 0 -+ -+ begin_year = int(localtime.tm_year) - year -+ end_year = begin_year + year -+ -+ for y in range(begin_year, end_year): -+ if judge_leap_year(y): -+ day += 366 -+ else: -+ day += 365 -+ -+ leap_year = judge_leap_year(localtime.tm_year) -+ for m in range(1, localtime.tm_mon): -+ day += month_days(m, leap_year) -+ -+ day += localtime.tm_mday -+ -+ return f"{name}'s age is {year} years or {month} months or {day} days" -+ -+ -+ -+ -diff --git a/projects/Calculate Age/src/main.py b/projects/Calculate Age/src/main.py -new file mode 100644 -index 0000000..b775235 ---- /dev/null -+++ b/projects/Calculate Age/src/main.py -@@ -0,0 +1,35 @@ -+from calculate_age import age_calculator -+ -+ -+def main(): -+ """ -+ the user to input name and age, validate input, -+ and calculates and displays the user age in years, months and days. -+ -+ Args: -+ None. -+ -+ Return: -+ None. -+ """ -+ input_name = input("input your name: ") -+ -+ while True: -+ input_age = input("input your age: ") -+ try: -+ string_to_int_age = int(input_age) -+ if string_to_int_age <= 0: -+ print("Please input a positive number.") -+ else: -+ break -+ except ValueError: -+ print("Please input a valid age.") -+ -+ result = age_calculator(input_name, string_to_int_age) -+ -+ print(result) -+ -+if __name__ == "__main__": -+ main() -+ -+ -diff --git a/projects/Calculate Age/src/utilize_date.py b/projects/Calculate Age/src/utilize_date.py -new file mode 100644 -index 0000000..8d8b129 ---- /dev/null -+++ b/projects/Calculate Age/src/utilize_date.py -@@ -0,0 +1,36 @@ -+from calendar import isleap -+ -+ -+def judge_leap_year(year): -+ """ -+ judge the leap year. -+ -+ Args: -+ year (int): To check the year. -+ return: -+ bool: Ture if the year is a leap year, False otherwise. -+ """ -+ if isleap(year): -+ return True -+ else: -+ return False -+ -+ -+def month_days(month, leap_year): -+ """ -+ Returns the number of days in each month -+ -+ Args: -+ month (int): The month 1-12. -+ -+ Returns: -+ int: The number of days in the month. -+ """ -+ if month in [1, 3, 5, 7, 8, 10, 12]: -+ return 31 -+ elif month in [4, 6, 9, 11]: -+ return 30 -+ elif month == 2 and leap_year: -+ return 29 -+ elif month == 2 and (not leap_year): -+ return 28 -diff --git a/projects/Calculate Age/tests/__init__.py b/projects/Calculate Age/tests/__init__.py -new file mode 100644 -index 0000000..e69de29 -diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py -new file mode 100644 -index 0000000..af0c07b ---- /dev/null -+++ b/projects/Calculate Age/tests/test_calculate_age.py -@@ -0,0 +1,25 @@ -+import time -+from unittest.mock import patch -+from calculate_age import age_calculator -+ -+@patch('time.time', return_value=1621848668.0) -+def test_age_calculator(mock_time): -+ name = "Chloe" -+ age = 30 -+ expect_output = "Chloe's age is 30 years or 365 months or 11102 days" -+ assert age_calculator(name, age) == expect_output -+ -+def test_age_calculator_negative_age(): -+ name = "Emma" -+ age = -5 -+ try: -+ age_calculator(name, age) -+ except ValueError as e: -+ assert str(e) == "Please input a positive number." -+ -+ -+def test_age_calculator_leap_year(): -+ name = "David" -+ age = 30 -+ expect_output_leap_year = "David's age is 30 years or 365 months or 11100 days" -+ assert age_calculator(name, age) == expect_output_leap_year -diff --git a/projects/Calculate Age/test_calculate.py b/projects/Calculate Age/tests/test_utilize_date.py -similarity index 83% -rename from projects/Calculate Age/test_calculate.py -rename to projects/Calculate Age/tests/test_utilize_date.py -index 369ac65..54e5efa 100644 ---- a/projects/Calculate Age/test_calculate.py -+++ b/projects/Calculate Age/tests/test_utilize_date.py -@@ -1,5 +1,6 @@ - import pytest --from calculate import judge_leap_year, month_days -+from utilize_date import judge_leap_year, month_days -+ - - def test_judge_leap_year(): - assert judge_leap_year(2000) == True -@@ -9,6 +10,7 @@ def test_judge_leap_year(): - assert judge_leap_year(2400) == True - assert judge_leap_year(2100) == False - -+ - def test_month_days(): - assert month_days(7, False) == 31 - assert month_days(4, True) == 30 -@@ -17,4 +19,5 @@ def test_month_days(): - assert month_days(1, False) == 31 - assert month_days(11, True) == 30 - --# "pytest -s test_calculate.py" to test this file -\ No newline at end of file -+ -+# "pytest -s test_utilize_date.py" to test this file From 593c7d2862d02a734a83d981c760df1f1d8c2441 Mon Sep 17 00:00:00 2001 From: Lint Action Date: Fri, 7 Jun 2024 03:30:50 +0000 Subject: [PATCH 16/16] Fix code style issues with Black --- projects/Calculate Age/tests/test_calculate_age.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/Calculate Age/tests/test_calculate_age.py b/projects/Calculate Age/tests/test_calculate_age.py index 7fd76624..481764c8 100644 --- a/projects/Calculate Age/tests/test_calculate_age.py +++ b/projects/Calculate Age/tests/test_calculate_age.py @@ -28,7 +28,7 @@ def test_age_calculator_negative_age(): assert str(e) == "Please input a positive number." -@patch('time.time', return_value=1621848668.0) +@patch("time.time", return_value=1621848668.0) def test_age_calculator_leap_year(mock_time): """ Test the age_calculator function considering leap years