diff --git a/python-modulo-operator/README.md b/python-modulo-operator/README.md new file mode 100644 index 0000000000..9f49f5b962 --- /dev/null +++ b/python-modulo-operator/README.md @@ -0,0 +1,28 @@ +# Python Modulo Operator (%): How to Use Mod in Python + +In this folder, you'll find the code examples for the Real Python tutorial [Python Modulo Operator (%): How to Use Mod in Python](https://realpython.com/python-modulo-operator/). + +## Setup + +You need Python 3.7 or later. The examples only use the standard library, so there's nothing to install. + +## Usage + +Run any script to see the output that the tutorial shows for it: + +```sh +$ python even_odd.py +$ python intervals.py +$ python unit_conversion.py +$ python prime_number.py +$ python caesar_cipher.py +$ python vigenere_cipher.py +$ python decimal_modulo.py +$ python student.py +``` + +The `cyclic_iteration.py` script opens a `turtle` graphics window and keeps drawing until you close it: + +```sh +$ python cyclic_iteration.py +``` diff --git a/python-modulo-operator/caesar_cipher.py b/python-modulo-operator/caesar_cipher.py new file mode 100644 index 0000000000..aefa40f275 --- /dev/null +++ b/python-modulo-operator/caesar_cipher.py @@ -0,0 +1,28 @@ +import string + + +def caesar_cipher(text, shift, decrypt=False): + if not text.isascii() or not text.isalpha(): + raise ValueError("Text must be ASCII and contain no numbers.") + + lowercase = string.ascii_lowercase + uppercase = string.ascii_uppercase + result = "" + + if decrypt: + shift = shift * -1 + + for char in text: + if char.islower(): + index = lowercase.index(char) + result += lowercase[(index + shift) % 26] + else: + index = uppercase.index(char) + result += uppercase[(index + shift) % 26] + + return result + + +if __name__ == "__main__": + print(repr(caesar_cipher("meetMeAtOurHideOutAtTwo", 10))) + print(repr(caesar_cipher("woodWoKdYebRsnoYedKdDgy", 10, decrypt=True))) diff --git a/python-modulo-operator/cyclic_iteration.py b/python-modulo-operator/cyclic_iteration.py new file mode 100644 index 0000000000..ee8df80983 --- /dev/null +++ b/python-modulo-operator/cyclic_iteration.py @@ -0,0 +1,26 @@ +import random +import turtle + + +def draw_with_cyclic_iteration(): + colors = ["green", "cyan", "orange", "purple", "red", "yellow", "white"] + + turtle.bgcolor("gray8") # Hex: #333333 + turtle.pendown() + turtle.pencolor(random.choice(colors)) # First color is random + + i = 0 # Initial index + + while True: + i = (i + 1) % 6 # Update the index + turtle.pensize(i) # Set pensize to i + turtle.forward(225) + turtle.right(170) + + # Pick a random color + if i == 0: + turtle.pencolor(random.choice(colors)) + + +if __name__ == "__main__": + draw_with_cyclic_iteration() diff --git a/python-modulo-operator/decimal_modulo.py b/python-modulo-operator/decimal_modulo.py new file mode 100644 index 0000000000..b84aa97f95 --- /dev/null +++ b/python-modulo-operator/decimal_modulo.py @@ -0,0 +1,17 @@ +import decimal +import math + +print(repr(decimal.Decimal(15) % decimal.Decimal(4))) +print(repr(decimal.Decimal(240) % decimal.Decimal(13))) + +print(repr(decimal.Decimal("12.5") % decimal.Decimal("5.5"))) +print(repr(decimal.Decimal("13.3") % decimal.Decimal("1.1"))) + +print(-17 % 3) # Sign of the divisor +print(repr(decimal.Decimal(-17) % decimal.Decimal(3))) # Sign of the dividend +print(17 % -3) # Sign of the divisor +print(repr(decimal.Decimal(17) % decimal.Decimal(-3))) # Sign of dividend +print(-13.3 % 1.1) # Sign of the divisor +print(repr(decimal.Decimal("-13.3") % decimal.Decimal("1.1"))) + +print(math.fmod(-13.3, 1.1)) diff --git a/python-modulo-operator/even_odd.py b/python-modulo-operator/even_odd.py new file mode 100644 index 0000000000..8a3deea3de --- /dev/null +++ b/python-modulo-operator/even_odd.py @@ -0,0 +1,14 @@ +def is_even(num): + return num % 2 == 0 + + +def is_odd(num): + return num % 2 != 0 + + +if __name__ == "__main__": + for number in [-3, -2, 0, 7, 10]: + print(f"{number}: is_even={is_even(number)}, is_odd={is_odd(number)}") + + print(-3 % 2) + print(3 % -2) diff --git a/python-modulo-operator/intervals.py b/python-modulo-operator/intervals.py new file mode 100644 index 0000000000..4a458513f5 --- /dev/null +++ b/python-modulo-operator/intervals.py @@ -0,0 +1,14 @@ +def split_names_into_rows(name_list, modulus=3): + for index, name in enumerate(name_list, start=1): + print(f"{name:-^15} ", end="") + if index % modulus == 0: + print() + print() + + +if __name__ == "__main__": + names = ["Picard", "Riker", "Troi", "Crusher", "Worf", "Data", "La Forge"] + split_names_into_rows(names) + split_names_into_rows(names, modulus=4) + split_names_into_rows(names, modulus=2) + split_names_into_rows(names, modulus=1) diff --git a/python-modulo-operator/prime_number.py b/python-modulo-operator/prime_number.py new file mode 100644 index 0000000000..2c40be3c1e --- /dev/null +++ b/python-modulo-operator/prime_number.py @@ -0,0 +1,24 @@ +def check_prime_number(num): + if num < 2: + print(f"{num} must be greater than or equal to 2 to be prime.") + return + + factors = [(1, num)] + i = 2 + + while i * i <= num: + if num % i == 0: + factors.append((i, num // i)) + i += 1 + + if len(factors) > 1: + print(f"{num} is not prime. It has the following factors: {factors}") + else: + print(f"{num} is a prime number") + + +if __name__ == "__main__": + check_prime_number(44) + check_prime_number(53) + check_prime_number(115) + check_prime_number(997) diff --git a/python-modulo-operator/student.py b/python-modulo-operator/student.py new file mode 100644 index 0000000000..a759035e49 --- /dev/null +++ b/python-modulo-operator/student.py @@ -0,0 +1,26 @@ +class Student: + def __init__(self, name): + self.name = name + self.study_sessions = [] + + def add_study_sessions(self, sessions): + self.study_sessions += sessions + + def __mod__(self, other): + return sum(self.study_sessions) % other + + def __floordiv__(self, other): + return sum(self.study_sessions) // other + + +def total_study_time_in_hours(student): + hours = student // 60 + minutes = student % 60 + + print(f"{student.name} studied {hours} hours and {minutes} minutes") + + +if __name__ == "__main__": + jane = Student("Jane") + jane.add_study_sessions([120, 30, 56, 260, 130, 25, 75]) + total_study_time_in_hours(jane) diff --git a/python-modulo-operator/unit_conversion.py b/python-modulo-operator/unit_conversion.py new file mode 100644 index 0000000000..86a9b380b7 --- /dev/null +++ b/python-modulo-operator/unit_conversion.py @@ -0,0 +1,36 @@ +def convert_inches_to_feet(total_inches): + inches = total_inches % 12 + feet = total_inches // 12 + + print(f"{total_inches} inches = {feet} feet and {inches} inches") + + +def convert_minutes_to_days(total_mins): + days = total_mins // 1440 + extra_minutes = total_mins % 1440 + + hours = extra_minutes // 60 + minutes = extra_minutes % 60 + + print(f"{total_mins} = {days} days, {hours} hours, and {minutes} minutes") + + +def convert_inches_to_feet_updated(total_inches): + feet, inches = divmod(total_inches, 12) + print(f"{total_inches} inches = {feet} feet and {inches} inches") + + +def convert_minutes_to_days_updated(total_mins): + days, extra_minutes = divmod(total_mins, 1440) + hours, minutes = divmod(extra_minutes, 60) + + print(f"{total_mins} = {days} days, {hours} hours, and {minutes} minutes") + + +if __name__ == "__main__": + convert_inches_to_feet(450) + convert_minutes_to_days(1503) + convert_minutes_to_days(3456) + convert_minutes_to_days(35000) + convert_inches_to_feet_updated(450) + convert_minutes_to_days_updated(1503) diff --git a/python-modulo-operator/vigenere_cipher.py b/python-modulo-operator/vigenere_cipher.py new file mode 100644 index 0000000000..f73c7520c4 --- /dev/null +++ b/python-modulo-operator/vigenere_cipher.py @@ -0,0 +1,30 @@ +import string + + +def vigenere_cipher(text, key, decrypt=False): + if not text.isascii() or not text.isalpha() or not text.isupper(): + raise ValueError("Text must be uppercase ASCII without numbers.") + + uppercase = string.ascii_uppercase # "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + results = "" + + for i, char in enumerate(text): + current_key = key[i % len(key)] + char_index = uppercase.index(char) + key_index = uppercase.index(current_key) + + if decrypt: + index = char_index - key_index + 26 + else: + index = char_index + key_index + + results += uppercase[index % 26] + + return results + + +if __name__ == "__main__": + print(repr(vigenere_cipher(text="REALPYTHON", key="MODULO"))) + encrypted = vigenere_cipher(text="REALPYTHON", key="MODULO") + print(encrypted) + print(repr(vigenere_cipher(encrypted, "MODULO", decrypt=True)))