Snippets Collections
find_item = input("Enter the item to be searched here:- ").lower()

items = {'wand': 5, 'telescope': 2, 'feather pen': 7}

for thing in items:
    if thing == find_item:
        print(f"{items[thing]} units of {thing} are present.")
        break
else:
    print('No stock left! You need to go and buy!!')
numbers = [51, 32, 63, 74, 45, 36, 47]

for i in numbers:
   pass
numbers = [51, 32, 63, 74, 45, 36, 47]

for num in numbers:
    if num % 2 == 0:
        continue
    else:
        print(num)
numbers = [51, 32, 63, 74, 45, 36, 47]

for num in numbers:
    if num % 5 == 0:
        print(num)
        break
wizard_list = ["Wand", "Cauldron", "crystal phials", \
        "telescope", "brass scales", "Owl", \
        "Cat", "Toad", \
        "Feather"]

for items in wizard_list:
    print(items)
wizard_list = ["Wand", "Cauldron", "crystal phials", \
        "telescope", "brass scales", "Owl", \
        "Cat", "Toad", \
        "Feather pen"]

print(wizard_list[0])
print(wizard_list[1])
print(wizard_list[2])
print(wizard_list[3])
print(wizard_list[4])
print(wizard_list[5])
print(wizard_list[6])
print(wizard_list[7])
print(wizard_list[8])
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
                           Welcome to pythonista Calculator
                  We support the following operations on two numbers:
                  - subraction
                  + addition
                  * multiplication
                  / division
                  ** exponention
                  % modular division

Enter 1st number:- 13
Enter 2nd number:- 2 
Enter the operator here:- *
13 * 2 = 26
calc = """
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
                           Welcome to pythonista Calculator
                  We support the following operations on two numbers:
                  - subraction
                  + addition
                  * multiplication
                  / division
                  ** exponention
                  % modular division
"""
print(calc)
first_number = int(input("Enter 1st number:- "))
second_number = int(input("Enter 2nd number:- "))
operator_ = input("Enter the operator here:- ")

if operator_ == "-":
    result = first_number - second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "+":
    result = first_number + second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "*":
    result = first_number * second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "/":
    result = first_number / second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "**":
    result = first_number ** second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "%":
    result = first_number % second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

else:
    print("You entered an invalid operator!!")
a = int(input("Enter value of a:-\n"))
b = int(input("Enter value of b:-\n"))
print("a is greater than b") if a > b else print("b is greater than a")
num = -19

if num>=0:
    if type(num)==float:
        print(f"{num} is a positive floating-point number.")
    elif type(num)==int:
        print(f"{num} is a positive integer.")

else:
    if type(num)==float:
        print(f"{num} is a negative floating-point number.")
    elif type(num)==int:
        print(f"{num} is a negative integer.")
age = 19

if age==18:
    print("You're 18 go through the next check to know whether you qualify for license or not.")
if age > 18:
    print("You are above 18 you do qualify age criteria for license.")
else:
    print(f"You are not yet 18 come after {18-age} years to qualify the age criteria.")
age = 19

if age==18:
    print("You're 18 go through the next check to know whether you qualify for license or not.")
elif age > 18:
    print("You are above 18 you do qualify age criteria for license.")
else:
    print(f"You are not yet 18 come after {18-age} years to qualify the age criteria.")
num = -19

if num>=0:
    print(f"{num} is a positive number.")
else:
    print(f"{num} is a negative number.")

print("This will always be printed")
Welcome to the fun world ladies and gentleman


⠀⠀⠀⠀⠀⠀⠀⣠⡔⠚⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠑⠢⢄⠀⢀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠋⠻⢿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣽⣧⣷⠀⠀⠀⠀
⠀⠀⢀⠴⠁⠀⠀⠀⠀⢈⣹⣿⣿⣷⠀⠀⠀⠀⠀⢾⣿⣿⣟⠋⠁⠈⠳⡀⠀⠀
⠀⢠⠊⣀⣤⠴⠶⠖⢛⠻⣿⣿⣭⣀⣀⠀⠀⠀⠀⠀⠉⠻⡿⠳⠖⠶⠶⠟⠓⠲
⣴⢣⡞⡉⢄⠒⡈⠜⡀⢾⣏⠉⠙⠛⠻⠿⢿⣿⣶⣶⣿⠿⢷⡡⢘⡐⢢⠘⡄⢂
⣿⡏⡐⢌⠢⠑⡌⠂⢥⣿⣿⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⣀⣼⣷⠠⠘⡄⠣⡐⠂..
⡟⣷⠀⢆⠢⡑⣈⢡⡾⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⣅⠰⢁...⡡
⡇⠈⠻⣦⣴⣤⠶⠋⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⠉⠓⠒⢪
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⢸
⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⢸
⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⢀⠏
⠀⠙⣄⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⣠⠏⠀
⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⢀⡴⠁⠀⠀
⠀⠀⠀⠀⠈⠲⢄⠀⠀⠀⠀⠀⠀⠉⠿⣿⣿⣿⣿⣿⠿⠋⠀⣠⠔⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⠒⠤⣤⣀⣀⣀⣀⣀⣈⣉⣉⣠⠤⠖⠏⠁

Enter any of the words below and press enter to know its meaning in the fun world
['Bumfuzzle', 'Everywhen', 'Erf', 'Obelus', 'Bumbershoot']

Enter the word here:- Obelus
searching...

The meaning of 'Obelus' in our world is:-  the symbol used for division in a math problem
print("\nWelcome to the fun world ladies and gentleman\n")
print("""
⠀⠀⠀⠀⠀⠀⠀⣠⡔⠚⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠑⠢⢄⠀⢀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠋⠻⢿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣽⣧⣷⠀⠀⠀⠀
⠀⠀⢀⠴⠁⠀⠀⠀⠀⢈⣹⣿⣿⣷⠀⠀⠀⠀⠀⢾⣿⣿⣟⠋⠁⠈⠳⡀⠀⠀
⠀⢠⠊⣀⣤⠴⠶⠖⢛⠻⣿⣿⣭⣀⣀⠀⠀⠀⠀⠀⠉⠻⡿⠳⠖⠶⠶⠟⠓⠲
⣴⢣⡞⡉⢄⠒⡈⠜⡀⢾⣏⠉⠙⠛⠻⠿⢿⣿⣶⣶⣿⠿⢷⡡⢘⡐⢢⠘⡄⢂
⣿⡏⡐⢌⠢⠑⡌⠂⢥⣿⣿⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⣀⣼⣷⠠⠘⡄⠣⡐⠂..
⡟⣷⠀⢆⠢⡑⣈⢡⡾⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⣅⠰⢁...⡡
⡇⠈⠻⣦⣴⣤⠶⠋⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⠉⠓⠒⢪
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⢸
⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⢸
⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⢀⠏
⠀⠙⣄⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⣠⠏⠀
⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⢀⡴⠁⠀⠀
⠀⠀⠀⠀⠈⠲⢄⠀⠀⠀⠀⠀⠀⠉⠿⣿⣿⣿⣿⣿⠿⠋⠀⣠⠔⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⠒⠤⣤⣀⣀⣀⣀⣀⣈⣉⣉⣠⠤⠖⠏⠁
""")

fun_world_dictionary = {'Bumfuzzle': "confused",
                        'Everywhen': "all the time",
                        'Erf': "plot of land",
                        'Obelus': " the symbol used for division in a math problem",
                        'Bumbershoot': "umbrella"}

# I know that it's not quiet funnny(ok not at all funny). But, please forgive me for that

print("Enter any of the words below and press enter to know its meaning in the fun world")
list_of_words = list(fun_world_dictionary.keys())
print(list_of_words, "\n")


word_to_be_searched = input("Enter the word here:- ")
print("searching...\n")
meaning =""

if word_to_be_searched=="Bumfuzzle":
    meaning= fun_world_dictionary['Bumfuzzle']

if word_to_be_searched=="Everywhen":
    meaning= fun_world_dictionary['Everywhen']

if word_to_be_searched=="Erf":
    meaning= fun_world_dictionary['Erf']

if word_to_be_searched=="Obelus":
    meaning= fun_world_dictionary['Obelus']

if word_to_be_searched=="Bumbershoot":
    meaning= fun_world_dictionary['Bumbershoot']


print(f"The meaning of '{word_to_be_searched}' in our world is:- {meaning}\n")
trophies = {"Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam"}

print(trophies)
print(type(trophies))
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀

{'Liam': ('Yes', 'No', 'Yes'), 'Olivia': ('Yes', 'No', 'Yes'), 'Noah': ('Yes', 'Yes', 'Yes'), 'Emma': ('Yes', 'No', 'Yes')}
done = """
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀
"""
print(done)

name_homework_done = {"Liam": ("Yes", "No", "Yes"),
                      "Olivia": ("Yes", "No", "Yes"),
                      "Noah": ("Yes", "Yes", "Yes"),
                      "Emma": ("Yes", "No", "Yes")}
print(name_homework_done)
homework = ("Multiplication Table of Two", \
"A poem on environment", "Multiplication Table of Two",\
"Process of Photosynthesis",\
"Maps of the world", "glorious past revision",\
"Multiplication Table of Two")

print(homework)
print()
print(homework.index("Multiplication Table of Two"))
homework = ("Multiplication Table of Two", \
"A poem on environment", "Multiplication Table of Two",\
"Process of Photosynthesis",\
"Maps of the world", "glorious past revision",\
"Multiplication Table of Two")

print(homework)
print()
print(homework.count("Multiplication Table of Two"))
homework = ("Multiplication Table of Two", \
"A poem on environment", "Process of Photosynthesis",\
"Maps of the world", "glorious past revision")

print(homework)

HW = homework
print(HW)
homework1 = ("Multiplication Table of Two", \
"A poem on environment", "Process of Photosynthesis")

homework2 = ("Maps of the world", "glorious past revision")

homework = homework1 + homework2

print(homework)
s_tup = hello <class 'str'>
s1_tup = ('hello',) <class 'tuple'>
s2_tup = hello <class 'str'>       
s3_tup = ('hello',) <class 'tuple'>
s_tup = "hello"  # This will be a string
s1_tup = "hello",  # This will be a tuple
s2_tup = ("hello")  # This will be a string
s3_tup = ("hello",)  # This will be a tuple

print(f"s_tup = {s_tup} {type(s_tup)}")
print(f"s1_tup = {s1_tup} {type(s1_tup)}")
print(f"s2_tup = {s2_tup} {type(s2_tup)}")
print(f"s3_tup = {s3_tup} {type(s3_tup)}")
___________________________________ 
|#######====================#######|
|#(1)*UNITED STATES OF AMERICA*(1)#|
|#**          /===\   ********  **#|
|*# {G}      | (") |             #*|
|#*  ******  | /v\ |    O N E    *#|
|#(1)         \===/            (1)#|
|##=========ONE DOLLAR===========##|
------------------------------------

{'apple': [100, 10000, 1000], 'banana': [90, 9000, 900], 'spinach': [50, 4000, 800], 'pineapples': [100, 8000, 900]}
money = """
___________________________________
|#######====================#######|
|#(1)*UNITED STATES OF AMERICA*(1)#|
|#**          /===\   ********  **#|
|*# {G}      | (") |             #*|
|#*  ******  | /v\ |    O N E    *#|
|#(1)         \===/            (1)#|
|##=========ONE DOLLAR===========##|
------------------------------------
"""
print(money)

price_profit_revenue = {"apple": [100, 10000, 1000], 
                        "banana": [90, 9000, 900], 
                        "spinach": [50, 4000, 800], 
                        "pineapples": [100, 8000, 900]}

print(price_profit_revenue)
            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- someone
Enter a skill:- programming
Enter any object:- laptop
Enter a verb:- typing
Enter another verb:- searching
Enter a verb again:- creating
Enter an adjective:- fast


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A fast boy named someone had just passed his programming test
and asked his Dad if he could start using the family laptop. The Dad
said he'd make a typing with someone, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the laptop". someone thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "someone, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
someone said, "You know, Dad, I've been searching about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all creating everywhere they went?"
Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Store the variables in a list
blanks = [name, skill, object_, verb1, verb2, verb3, adjective]

#step4: Merge variable in story using an f-string
changed_story = f'''A {blanks[6]} boy named {blanks[0]} had just passed his {blanks[1]} test
and asked his Dad if he could start using the family {blanks[2]}. The Dad
said he'd make a {blanks[3]} with {blanks[0]}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {blanks[2]}". {blanks[0]} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{blanks[0]}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{blanks[0]} said, "You know, Dad, I've been {blanks[4]} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {blanks[5]} everywhere they went?"'''

#step5: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")
            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- Emma
Enter a skill:- acting
Enter any object:- sword
Enter a verb:- crying
Enter another verb:- sleeping
Enter a verb again:- dancing
Enter an adjective:- magical


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A magical boy named Emma had just passed his acting test
and asked his Dad if he could start using the family sword. The Dad
said he'd make a crying with Emma, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the sword". Emma thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "Emma, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
Emma said, "You know, Dad, I've been sleeping about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all dancing everywhere they went?"
Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Merge variable in story using an f-string
changed_story = f'''A {adjective} boy named {name} had just passed his {skill} test
and asked his Dad if he could start using the family {object_}. The Dad
said he'd make a {verb1} with {name}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {object_}". {name} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{name}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{name} said, "You know, Dad, I've been {verb2} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {verb3} everywhere they went?"'''

#step4: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")
input_string = input()
input_string = input_string.upper() #to convert all letters of
#string to upper case
print(len(input_string)) #to count the total no. of characters
str_to_list = input_string.split(",") #to convert the string to list
#so that we can join the list with full stops
print(".".join(str_to_list)) #to join the elements of the list to
#form a full stop separated string
word="standard"
ans5 = word[1:4]
print(ans5)
#Output should be tan
word="standard"
ans4 = word[:6:2]
#Another way:- word[0:6:2]
print(ans4)
#Output should be sad
wrd="Toscana"
ans3 =wrd[3:6]
print(ans3)
#Output should be can
find_sum = 'Lorem Ipsum'
ans2 = find_sum[8:]
# Another way:- find_sum[8:11]
print(ans2)
#Output should be sum
word = 'Typesetting'
ans1 = word[:3] 
#Another way:- word[0:3]
print(ans1)
#output: Typ
word="standard"
ans5 =
print(ans5)
#Output should be tan
word="standard"
ans4 =
print(ans4)
#Output should be sad
wrd="Toscana"
ans3 =
print(ans3)
#Output should be can
find_sum = 'Lorem Ipsum'
ans2 =
print(ans2)
#Output should be sum
word = 'Typesetting'
ans1 = 
print(ans1)
#Output should be Typ
str1 = "I am happy"
print(str1[0]) # I
print(str1[1]) #  (whitespace)
print(str1[2]) # a
print(str1[3]) # m
print(str1[4]) #  (whitespace)
print(str1[5]) # h
print(str1[6]) # a
print(str1[7]) # p
print(str1[8]) # p
print(str1[9]) # y
son = "John"
father = "Dad"
thing = "car"
verb = "walked"
print(f'''A teenage boy named {son} had just passed his driving test
and asked his {father} if he could start using the family {thing}.
The {father} said he'd make a deal with {son}, "You bring your 
grades up from a C to a B average, study your Bible a little, and 
get your hair cut.
Then we'll talk about the {thing}". {son} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the {father} said, "{son}, you've brought 
your grades up and I've observed that you have been studying your 
Bible, but I'm disappointed you haven't had your hair cut."
{son} said, "You know, {father}, I've been thinking about that, and
I've noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's
even strong evidence that Jesus had long hair." His {father} 
replied, "Did you also notice that they all {verb} everywhere they 
went?"''')
what ="f-string"
adjective = "fantastic"

print(f"{what} is {adjective}")
name = "Python"
age = 31
number = 284.242

print("I am %s I am %d years old. I support floating point numbers like %f." % (name, age, number))
action1 = "Sing"
action2 = "Dance"
action3 = "Be difficult"

print("Three things that python can't do:- {}, {}, and {}!!".format(action1, action2, action3))
#Keyword and position are also possible
show = "Monty Python's Flying Circus,"

print("Python is named after ", show, " a BBC comedy series from the 1970s.")
game = "PUBG"
print(game+" is a game!!")

#!!Don't forget to give a space before 'is' otherwise
#PUBGis a game!!   #This will be your ouptut
#-----GAME-----
diamonds = 10
#player won 
daimonds += 5
#player lost
diamonds -= 1
#player wants to see total no. of diamonds he has
print("The total no. of diamonds you have = ", diamonds)
num_str = "10" #it is a string because it is inside quotes
num = 10.1 #it is an float
num_result = int(num_str) + num #telling python that num_str 
#is a number and to add it to num.
print(num_result)
print(type(num_result))
num_str = "10" #it is a string because it is inside quotes
num = 10.1 #it is an float
num_result = num_str + num
print(num_result)
print(type(num_result))
num1 = 10 #it is an integer
num2 = 10.1 #it is an float
num3 = num1 + num2 #it will be converted to float to avoid data loss
print(num3) #20.1
print(type(num3)) #it got converted to float datatype
#addition
print(8+9) #17
#division
print(8/9) #0.8888888888888888
#multiplication
print(8*9) #72
#finding remainder
print(8%9) #8
#These are all examples of arithmetic operators(+,/,*,%).
print(3+1j)
a = (3+1j) # This is also a variable we will discuss them next to next post.
print(type(a))
print(10 > 9)
print(10 == 9)
print(10 < 9)
player= "won" # this line creates a variable we will discuss them later. It prints nothing.
print(player=="won")
print(1)
print(1,1)
print(type(1))
#And so on.
print("Hiii")#this is an inline comment
print(" '#' This is not a comment this will be printed")
#First
#Put a
# hash 
#before all the lines
#you want to comment

print('This must be quite obvious, anyways the next option is:')

  #Second
"""put the
multi line either between three 
double quotes or"""
'''between
three
single quotes'''
#
#This is a single line comment
print("Hello World")
#print("This too will be treated as a comment")
#This is a comment.
print("however, this will be printed") #This is also a comment
# Create a custom application class "Hobbies" that inherits from CTk (Custom Tkinter)
class Hobbies(CTk):
    # Constructor of the class
    def __init__(self):
        # Call the constructor of the parent class (CTk) using super()
        super().__init__()
        self.title("Hobbies")
        
        # Create a label to display "Select your hobbies"
        self.display_label = CTkLabel(self, text="Select your hobbies")
        self.display_label.pack(padx=10, pady=10)

        # Create a frame to hold the checkboxes
        self.frame =CTkFrame(self)
        self.frame.pack(padx=10, pady=10)

        # Create a StringVar to store the value of the first hobby (initially empty)
        self.hobby1 = StringVar()
        # Create a CTkCheckBox for "Coding"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby1, and its values are "Coding" (checked) and "" (unchecked)
        self.hobby1_cb = CTkCheckBox(self.frame, text="Coding", command=self.hobby,
                                            variable=self.hobby1, onvalue="Coding", offvalue="")
        self.hobby1_cb.grid(row=0, padx=10, pady=10)

        # Create a StringVar to store the value of the second hobby (initially empty)
        self.hobby2 = StringVar()
        # Create a CTkCheckBox for "Cricket"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby2, and its values are "Cricket" (checked) and "" (unchecked)
        self.hobby2_cb = CTkCheckBox(self.frame, text="Cricket", command=self.hobby,
                                            variable=self.hobby2, onvalue="Cricket", offvalue="")
        self.hobby2_cb.grid(row=1, padx=10, pady=10)

        # Create a StringVar to store the value of the third hobby (initially empty)
        self.hobby3 = StringVar()
        # Create a CTkCheckBox for "Drawing"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby3, and its values are "Drawing" (checked) and "" (unchecked)
        self.hobby3_cb = CTkCheckBox(self.frame, text="Drawing", command=self.hobby,
                                            variable=self.hobby3, onvalue="Drawing", offvalue="")
        self.hobby3_cb.grid(row=2, padx=10, pady=10)

        # Create a label to display the selected hobbies
        self.label= CTkLabel(self.frame, text="")
        self.label.grid(row=3)

    # Method to handle the checkbox toggle event
    def hobby(self):
        # Destroy the existing label to clear its contents
        self.label.destroy()

        # Create a new label to display the selected hobbies
        self.label = CTkLabel(self.frame, text=f"{self.hobby1.get()} {self.hobby2.get()} {self.hobby3.get()}")
        self.label.grid(row=3)

# Create an instance of the custom application class "Hobbies"
app = Hobbies()
# Start the main event loop of the application
app.mainloop()
# Importing the necessary modules from customtkinter library
from customtkinter import *
# This function will be called when the checkbox is toggled
def checkbox_event():
    # Create a new CTkLabel widget and display the current value of the checkbox
    label = CTkLabel(app, text=f"checkbox toggled, current value: {check_var.get()}")
    label.pack()

# Create a CTk application instance
app = CTk()
# Create a StringVar to hold the value of the checkbox (initially empty)
check_var = StringVar()
# Create a CTkCheckBox widget with text "Switch"
# When the checkbox is toggled, the checkbox_event function will be called
# The checkbox's variable is check_var, and its values are "on" (checked) and "off" (unchecked)
checkbox = CTkCheckBox(app, text="Switch", command=checkbox_event,
                                     variable=check_var, onvalue="on", offvalue="off")
# Pack the checkbox widget, adding padding around it
checkbox.pack(padx=10, pady=10)
# Start the main event loop of the application
app.mainloop()

"""
# ------------------IN OOP------------------
# Create a custom application class "App" that inherits from CTk (Custom Tkinter)
class App(CTk):
    # Constructor of the class
    def __init__(self):
        # Call the constructor of the parent class (CTk) using super()
        super().__init__()

        # Create a StringVar to hold the value of the checkbox (initially empty)
        self.check_var = StringVar()
        # Create a CTkCheckBox widget with text "Switch"
        # When the checkbox is toggled, the self.checkbox_event method will be called
        # The checkbox's variable is self.check_var, and its values are "on" (checked) and "off" (unchecked)
        self.checkbox = CTkCheckBox(self, text="Switch", command=self.checkbox_event,
                                            variable=self.check_var, onvalue="on", offvalue="off")
        # Pack the checkbox widget, adding padding around it
        self.checkbox.pack(padx=10, pady=10)

    # Method to handle the checkbox toggle event
    def checkbox_event(self):
        # Create a new CTkLabel widget and display the current value of the checkbox
        label = CTkLabel(self, text=f"checkbox toggled, current value: {self.check_var.get()}")
        label.pack()

# Create an instance of the custom application class "App"
app = App()
app.mainloop()
"""
class App(CTk):
    def __init__(self):
        super().__init__()

        self.button = CTkButton(
            self, text="Blogs", #Text to be displayed
            fg_color="#ec3642", #color of the button
            hover_color="white", #color of the button when mouse is over
            font=("Montserrat", 16), #font used
            corner_radius=12, width=100, #radius of edges and total width
            command=self.open) #Command to run when button is clicked
        self.button.pack(padx = 10, pady = 10)

    def open(self):
        import webbrowser #library to open a specific URL
        # Opening the given link.
        webbrowser.open("https://python-hub.com/blog-2/")

if __name__ == "__main__":
    app = App()
    app.mainloop()
from customtkinter import *

app = CTk()

button = CTkButton(app)
button.pack(padx = 10, pady = 10)

app.mainloop()

# In OOP
class App(CTk):
    def __init__(self):
        super().__init__()

        self.button = CTkButton(self)
        self.button.pack(padx = 10, pady = 10)

        
if __name__ == "__main__":
    app = App()
    app.mainloop()
# A GUI real time spell checker.
# for removing special characters
import re
# for GUI
from tkinter import scrolledtext
import tkinter as tk
from customtkinter import *
# for matching words
import nltk
from nltk.corpus import words

nltk.download("words")
class SpellingChecker(CTk):
    def __init__(self):
        super().__init__()
        self.title("Spelling Checker")
        self.geometry("600x500")

        # Creating a widget to let user type
        self.text_area = scrolledtext.ScrolledText(self,
                                      wrap = tk.WORD, 
                                      width = 70, 
                                      height = 27, 
                                      font = ("Times New Roman",
                                              15))
        # To check the spellings whenever any key is released.
        self.text_area.bind("<KeyRelease>", self.check)
        self.text_area.grid(column = 0, pady = 10, padx = 10)
        # keeping track of spaces.
        self.old_spaces = 0
    
    def check(self, event):
        # getting whole content typed by user
        content = self.text_area.get("1.0", tk.END)
        # counting spaces
        space_count = content.count(" ")

        # checks spelling only if the space key was pressed.
        if space_count != self.old_spaces: #checking if there are anymore spaces.
            self.old_spaces = space_count #updating the new no. of spaces.

            # removing any red highlights if there
            for tag in self.text_area.tag_names():
                self.text_area.tag_delete(tag)

            # getting all the words
            for word in content.split(" "):
                # removinga any special characters if there
                if re.sub(r"[^\w]", '', word.lower()) not in words.words():
                    # getting the starting position of incorrect word
                    position = content.find(word)
                    # marking wrong spelling red
                    self.text_area.tag_add(word, f"1.{position}", f"1.{position + len( word)}")
                    self.text_area.tag_config(word, foreground="red")


if __name__ == "__main__":
    si = SpellingChecker()
    si.mainloop()
from customtkinter import *
from PIL import Image

class Fooled(CTkToplevel):
    """A custom Tkinter Toplevel window to display a text label and a GIF image of Jerry from the 'Tom and Jerry' cartoon."""
    def __init__(self):
        """Initialize the Fooled Toplevel window."""
        super().__init__()
        self.title("")
        set_appearance_mode("light")
        self.geometry("250x250")
        
        self.label = CTkLabel(self, text="Idk, just look outside🤣")
        self.label.pack()
        self.forward_img = CTkImage(light_image=Image.open("images\\jerry.gif"), size=(199,199))
        self.front = CTkLabel(self, text="", image=self.forward_img)
        self.front.pack()


class ShowWhether(CTkToplevel):
    """A custom Tkinter Toplevel window that simulates a weather forecast process with text labels and a progress bar."""
    def __init__(self):
        """Initialize the ShowWhether Toplevel window."""
        super().__init__()
        self.title("AI weather forecast")
        set_appearance_mode("light")
        self.geometry("300x140")

        self.label = CTkLabel(self, text="Searching Location...")
        self.label.grid(row=0, padx=20, pady=20)

        self.label.after(1000, self.on_after)
        self.pb = CTkProgressBar(self, orientation="horizontal", mode="determinate")
        self.pb.grid(row=1, padx=20, pady=20)
        self.pb.set(0)
    def on_after(self):
        """Update the label text and progress bar after a delay."""
        self.label = CTkLabel(self, text="Analyzing the clouds...")
        self.label.grid(row=0, padx=20, pady=20)
        self.label.after(1000, self.on_after1)
        self.pb.set(0.25)

    def on_after1(self):
        """Update the label text and progress bar after a delay."""
        self.label = CTkLabel(self, text="Looking outside your window...")
        self.label.grid(row=0, padx=20, pady=20)
        self.label.after(1000, self.on_after2)
        self.pb.set(0.50)

    def on_after2(self):
        """Update the label text and progress bar after a delay."""
        self.label = CTkLabel(self, text="Gathering last the information...")
        self.label.grid(row=0, padx=20, pady=20)
        self.label.after(1000, self.last)
        self.pb.set(0.75)

    def last(self):
        """Finalize the weather forecast process and display the Fooled Toplevel window."""
        self.pb.set(1)
        show = Fooled()
        show.mainloop()


class Get_City(CTk):
    """A custom Tkinter main application class to get the user's location and initiate the weather forecast."""
    def __init__(self):
        """Initialize the Get_City application."""
        super().__init__()
        set_appearance_mode("light")
        self.title("AI weather forecast")

        self.geometry("400x175")
        self.label = CTkLabel(self, text="Enter your Location: ")
        self.label.pack(padx=20, pady=15)
        self.city = CTkEntry(self, placeholder_text="Enter Your city ")
        self.city.pack(padx=20, pady=10)

        self.check_weather = CTkButton(self, text="Check weather", command=self.weather)
        self.check_weather.pack(padx=20, pady=10)

    def weather(self):
        """Check if the city input is valid and initiate the weather forecast process."""
        if self.city.get() == "":
            print("Enter a city First")
        else:
            show = ShowWhether()
            show.mainloop()
if __name__ == "__main__":
    app = Get_City()
    app.mainloop()
import os
import numpy as np

class Game:
    def __init__(self):
        """Initialize a new Tic-Tac-Toe game with an empty game board."""
        self.game_arr = np.array([
                            [" ", " ", " "],
                            [" ", " ", " "],
                            [" ", " ", " "]
                         ])
        
    def update(self, row, column, new_val):
        """
        Update the game board with the player's move at the specified position.

        Parameters:
            row (int): The row index of the move.
            column (int): The column index of the move.
            new_val (str): The value of the player's move ("X" or "O").

        Raises:
            ValueError: If the new_val is not a valid move ("X" or "O").
        """
        valid = ["X", "x", "O", "o"]
        if new_val in valid:
            self.game_arr[row][column] = new_val
            self.make_grid(self.game_arr)
        else:
            print("Invalid Value!!")

    
    def make_grid(self,arr):
        """
        Display the current Tic-Tac-Toe game board.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.
        """
        print(f"""
{arr[0][0]} | {arr[0][1]} | {arr[0][2]}
----------
{arr[1][0]} | {arr[1][1]} | {arr[1][2]}
----------
{arr[2][0]} | {arr[2][1]} | {arr[2][2]}
""")

    def get_current_game(self):
        """
        Get the current state of the Tic-Tac-Toe game board.

        Returns:
            numpy.array: The 3x3 numpy array representing the game board.
        """
        return self.game_arr 
      
    def check_win(self, arr):
        """
        Check if there is a winning combination on the game board.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning combination, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        res_r = self.check_row(arr)
        if not res_r:
            res_c = self.check_col(arr)
            if not res_c:
                res_d = self.check_diag(arr)
                if not res_d:
                    return False
                else:
                    return [True,res_d[1]]
            else:
                return [True,res_c[1]]
        else:
            return [True,res_r[1]]

    
    def check_row(self, arr):
        """
        Check if any row on the game board has a winning combination.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning row, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        # This shouldn't be hard-coded, but
        # I am doing it to save time
        for i in arr:
            if i[0] == i[1] == i[2] != " ":
                return [True,i[0]]
        return False
        
    def check_col(self, arr):
        """
        Check if any column on the game board has a winning combination.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning column, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        # This shouldn't be hard-coded, but
        # I am doing it to save time
        for i in range(3):  # Assuming it's a 3x3 grid
            if arr[0][i] == arr[1][i] == arr[2][i] != " ":
                return [True, arr[0][i]]
        return False
    
    def check_diag(self, arr):
        """
        Check if any diagonal on the game board has a winning combination.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning diagonal, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        # This shouldn't be hard-coded, but
        # I am doing it to save time
        if arr[0][0] == arr[1][1] == arr[2][2] != " ":
            return [True,arr[0][0]]
        elif arr[0][2] == arr[1][1] == arr[2][0] != " ":
            return [True,arr[0][2]]
        else:
            return False
        
    def check_tie(self, arr) -> bool:
        """
        Check if the game has ended in a tie (draw).

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            bool: True if the game is a tie, False otherwise.
        """
        if " " in arr:
            return False
        else:
            return True
        
    def game_details(self):
        print("Enter your choice according to this: ")
        print("1. Top Left")
        print("2. Top Center")
        print("3. Top Right")
        print("4. Center Left")
        print("5. Center Center")
        print("6. Center Right")
        print("7. Bottom Left")
        print("8. Bottom Center")
        print("9. Bottom Right")


        
g = Game()
win = False
map_dict = {
            1:[0,0], 2:[0,1], 3:[0,2],
            4:[1,0], 5:[1,1], 6:[1,2],
            7:[2,0], 8:[2,1], 9:[2,2],
        }
players = {"O":"Player1", "X":"Player2"}
choices = []

while not win:
    g.game_details()
    g.make_grid(g.get_current_game())
    # getting input from player 1
    player1 = int(input("Player 1 Enter the Choice(1-9): "))
    # Checking if it's already taken
    while player1 in choices:
        print("Make another choice! It's already Taken!")
        player1 = int(input("Player 2 Enter the Choice(1-9): "))
    # updating according to the player1's choice
    g.update(map_dict[player1][0], map_dict[player1][1], "O")
    # Checking for tie
    if g.check_tie(g.get_current_game()):
        os.system('cls' if os.name == 'nt' else 'clear')
        g.make_grid(g.get_current_game())
        print("It's a tie!")
        break
    # checking if player 1 won
    check = g.check_win(g.get_current_game())
    try:
        if check[0]==True:
            os.system('cls' if os.name == 'nt' else 'clear')
            g.make_grid(g.get_current_game())
            print(f"{players[check[1]]} wins")
            win=True
            break
    except Exception:
        pass

    g.make_grid(g.get_current_game())
    choices.append(player1)
    # getting input from player 2
    player2 = int(input("Player 2 Enter the Choice(1-9): "))
    # Checking if it's already taken
    while player2 in choices:
        print("Make another choice! It's already Taken!")
        player2 = int(input("Player 2 Enter the Choice(1-9): "))
    # updating according to the player2's choice
    g.update(map_dict[player2][0], map_dict[player2][1], "X")
    # Checking for tie
    if g.check_tie(g.get_current_game()):
        os.system('cls' if os.name == 'nt' else 'clear')
        g.make_grid(g.get_current_game())
        print("It's a tie!")
        break
    # checking if player 2 won
    check2 = g.check_win(g.get_current_game())
    try:
        if check2[0]==True:
            os.system('cls' if os.name == 'nt' else 'clear')
            g.make_grid(g.get_current_game())
            print(f"{players[check2[1]]} wins")
            win=True
            break
    except Exception:
        pass
    g.make_grid(g.get_current_game())
    choices.append(player2)
from customtkinter import *
from PIL import Image
 
class App(CTk):
    def __init__(self):
        super().__init__()
        self.title("Personal Gallery")
        self.iconbitmap("images\\gallery.ico")  
        self.configure(fg_color="#181b1f")
 
        # setting up counter and images
        self.counter = 0
        # getting all the images in a list
        # If you have a lot of them, I suggest store them in a different file
        self.images = [CTkImage(light_image=Image.open("images\\forest.jpg"),size=(496.9,331.3)), 
                       CTkImage(light_image=Image.open("images\\moon.jpg"),size=(390.6,260.4)), 
                       CTkImage(light_image=Image.open("images\\mountain.jpg"),size=(654.1,436.1)), 
                       CTkImage(light_image=Image.open("images\\stone.jpg"),size=(593.7,416)), 
                       CTkImage(light_image=Image.open("images\\tree.jpg"),size=(624,416))]
         
        # images for buttons (forward and backward buttons)
        self.forward_img = CTkImage(light_image=Image.open("images\\forward.png"), size=(50,50))
        self.backward_img = CTkImage(light_image=Image.open("images\\backward.png"), size=(50,50))
 
        # label to show images
        self.il = CTkLabel(self,text="",image=self.images[self.counter])
        self.il.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
 
        # buttons
        self.front = CTkButton(self, text="", image=self.forward_img, fg_color="transparent", hover_color="#181b1f", command=self.next_command)
        self.back = CTkButton(self, text="", image=self.backward_img, fg_color="transparent", hover_color="#181b1f", command=self.previous)
 
        self.front.grid(row=1, column=2, padx=10, pady=10)
        self.back.grid(row=1, column=0, padx=10, pady=10)
 
        # exit button
        self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
        self.qb.grid(row=1, column=1, padx=10, pady=10)
 
        # status bar
        self.status = CTkLabel(self, text=f"Image {self.counter + 1} of {len(self.images)}")
        self.status.grid(row=2, column=2, padx=25)
 
    def next_command(self):
        # To keep counter from being more than 4
        # (4+1)%5 = 0
        # ensures cycle
        self.counter = (self.counter + 1) % len(self.images)
        self.update()
 
    def previous(self):
        # To keep counter from being less than 0
        # (0-1)%5 = 4
        # ensures cycle
        self.counter = (self.counter - 1) % len(self.images)
        self.update()
 
    def update(self):
        # removes label from the grid
        self.il.grid_forget()
        # updating image
        self.il = CTkLabel(self,text="",image=self.images[self.counter])
        self.il.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
 
        # updating status bar
        self.status = CTkLabel(self, text=f"Image {self.counter + 1} of {len(self.images)}")
        self.status.grid(row=2, column=2, padx=25)
 
if __name__ == '__main__':
    app = App()
    app.mainloop()
import requests
import wikipedia
from customtkinter import *
from tkinter import Label
import tkinter.messagebox as messagebox
import tkinter.font as tkfont
import webbrowser


class WikipediaArticle(CTk):
    def __init__(self):
        """Initialize the WikipediaArticle application."""
        super().__init__()
        # font for link
        self.custom_font = tkfont.Font(size=10, underline=True)
        # setting an empty label to avoid errors
        self.link = CTkLabel(self, text="")
        # button for generating random article
        self.get_article = CTkButton(self, text="Random Stuff", command=self.random_article_t_summary)
        self.get_article.grid(row=3, column=1 ,padx=10,pady=10)
        # button to copy article link
        self.copy_t = CTkButton(self, text="Copy Link", command=self.copy_text, fg_color="transparent")
        self.copy_t.grid(row=3, column=2 ,padx=10,pady=10)
        # button to open link in browser
        self.open_i = CTkButton(self, text="Open in browser", command=self.open_link)
        self.open_i.grid(row=3, column=0 ,padx=10,pady=10)

    def random_article_t_summary(self):
        """Generate a random Wikipedia article and display its title, summary, and link.
        uses the self.summarize_wikipedia_article() method"""
        url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
        
        article_link = url.url
        title_and_summary = self.summarize_wikipedia_article(article_link)

        if title_and_summary:
            # getting link and title
            self.link = Label(self, text=article_link, fg="blue", font=self.custom_font)
            self.title = CTkLabel(self, text=title_and_summary[0])
            # getting summary
            self.random_article = CTkTextbox(self)
            self.random_article.insert("0.0", title_and_summary[1])
            self.random_article.configure(state="disabled")
            # packing title, summary, and link
            self.title.grid(row=0, column=1, padx=10)
            self.random_article.grid(row=1, column=1 ,padx=10,pady=10)
            self.link.grid(row=2, column=0, padx=10)
        
    def summarize_wikipedia_article(self,article_link):
        """
        Summarize a Wikipedia article based on its link.

        Args:
            article_link (str): The link to the Wikipedia article.

        Returns:
            list: A list containing the page title and summary of the article, or None if the article is not found.
        """
        # Extract the page title from the article link
        page_title = article_link.split("/")[-1]

        try:
            # Get the Wikipedia page based on the page title
            page = wikipedia.page(page_title)

            # Retrieve the summary of the page
            summary = page.summary

            return [page_title,summary]

        except wikipedia.exceptions.PageError:
            message = CTkLabel(self, text="Something went wrong! Try Again!")
            message.grid(row=4, column=1,padx=10, pady=10)
            return None
        
    def copy_text(self):
        # Get the text from the label
        text = self.link.cget("text")

        # Set the text to the clipboard
        self.clipboard_clear()
        self.clipboard_append(text)

        messagebox.showinfo("Copy", "Text copied to clipboard!")

    def open_link(self):
        try:
            webbrowser.open(self.link.cget("text"))
        except Exception:
            message = CTkLabel(self, text="Get the link first!")
            message.grid(row=4, column=1,padx=10, pady=10)
        
if __name__ == "__main__":
    app = WikipediaArticle()
    app.mainloop()
import random
import time
from os import system

#constants
MAX_ATTEMPTS = 10
MIN_NUMBER = 1
MAX_NUMBER = 50


def introduce() -> None:
    """Introduces player to the rules of the game."""
    print("You will get a total of 10 guesses.")
    time.sleep(2)
    print("In 10 guesses you have to guess the correct no. between 1 to 50.")
    time.sleep(2)
    print("READY???")
    for count in range(1, 4):
        print(count)
        time.sleep(1)
    print("GO")
    time.sleep(1)
    system("cls")

def play_number_guessing_game() -> None:
    """
    Plays the number guessing game.
    
    A random number is generated between MIN_NUMBER and MAX_NUMBER.

    The player is prompted to guess the number within a limited number of attempts.
    Feedback is provided after each guess.
    
    The game ends when the player guesses the correct number or exhausts all attempts.
    """
    num = random.randint(MIN_NUMBER, MAX_NUMBER)
    guess_list = []

    introduce()
    attempt = 1
    while attempt != (MAX_ATTEMPTS + 1):
        try:
            guess = int(input("Guess a no.:"))

        except ValueError:
            print("Enter a valid number!!")
            continue

        if guess == num:
            print(f"\n\nYou got it right in {attempt} attempts.\nThe no. is {num}")
            return
        elif guess in guess_list:
            print("You already guessed this no. before!")
        elif guess > num:
            print(f"The no. is less than {guess}")
            attempt += 1
            print(11-attempt,"Attempts left")
        elif guess < num:
            print(f"The no. is greater than {guess}")
            attempt += 1
            print(11-attempt,"Attempts left")
        guess_list.append(guess)

    if attempt>=10:
        system("cls")
        print("GAME OVER")
        print("The correct no. was",num)

if __name__ == "__main__":
    play_number_guessing_game()
# Calculator App
from customtkinter import CTk, CTkEntry, CTkButton

class App(CTk):
    def __init__(self):
        super().__init__()

        self.title("Calculator")
        # width
        self.evwidth = 400
        self.bwidth1 = self.evwidth/4 - 20

        # colors
        self.configure(fg_color="#181b1f")
        self.obc = "#fb2f64"
        self.obch = "#cc2753"
        self.nbc = "#181b1f"
        self.nbch= "#14161a"

        # values
        self.values = CTkEntry(master=self, width=self.evwidth)
        self.values.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

        # number buttons
        self.button_1 = CTkButton(master=self, text="1", command=lambda: self.g_num("1"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_2 = CTkButton(master=self, text="2", command=lambda: self.g_num("2"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_3 = CTkButton(master=self, text="3", command=lambda: self.g_num("3"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_4 = CTkButton(master=self, text="4", command=lambda: self.g_num("4"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_5 = CTkButton(master=self, text="5", command=lambda: self.g_num("5"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_6 = CTkButton(master=self, text="6", command=lambda: self.g_num("6"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_7 = CTkButton(master=self, text="7", command=lambda: self.g_num("7"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_8 = CTkButton(master=self, text="8", command=lambda: self.g_num("8"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_9 = CTkButton(master=self, text="9", command=lambda: self.g_num("9"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_0 = CTkButton(master=self, text="0", command=lambda: self.g_num("0"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)

        # displaying number buttons
        self.button_1.grid(row=3, column=0, pady=5, padx=10)
        self.button_2.grid(row=3, column=1, pady=5, padx=10)
        self.button_3.grid(row=3, column=2, pady=5, padx=10)

        self.button_4.grid(row=2, column=0, pady=5, padx=10)
        self.button_5.grid(row=2, column=1, pady=5, padx=10)
        self.button_6.grid(row=2, column=2, pady=5, padx=10)

        self.button_7.grid(row=1, column=0, pady=5, padx=10)
        self.button_8.grid(row=1, column=1, pady=5, padx=10)
        self.button_9.grid(row=1, column=2, pady=5, padx=10)
        self.button_0.grid(row=4, column=0, pady=5, padx=10)
    
        # operation buttons
        self.add = CTkButton(master=self, text="+", command=lambda: self.operate("+"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)
        self.sub = CTkButton(master=self, text="-", command=lambda: self.operate("-"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)
        self.div = CTkButton(master=self, text="/", command=lambda: self.operate("/"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)
        self.mul = CTkButton(master=self, text="*", command=lambda: self.operate("*"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)

        self.equal = CTkButton(master=self, text="=", command=self.evaluate, width=self.bwidth1)
        self.clear = CTkButton(master=self, text="clear", command=self.all_clear, width=self.bwidth1)

        # displaying operation buttons
        self.add.grid(row=1, column=3, pady=5, padx=10)
        self.sub.grid(row=2, column=3, pady=5, padx=10)
        self.div.grid(row=3, column=3, pady=5, padx=10)
        self.mul.grid(row=4, column=3, pady=5, padx=10)

        self.equal.grid(row=4, column=1, pady=5, padx=10)
        self.clear.grid(row=4, column=2, pady=5, padx=10)


    def g_num(self, n):
        new_n = self.values.get()+n
        self.values.delete(0, END)
        self.values.insert(0, new_n)

    def all_clear(self):
        self.values.delete(0, END)

    def operate(self, o):
        self.f_num = int(self.values.get())
        self.op = o
        self.values.delete(0, END)

    def evaluate(self):
        s_num = int(self.values.get())
        self.values.delete(0, END)

        if self.op == "+":
            self.values.insert(0, self.f_num + s_num)
        elif self.op == "-":
            self.values.insert(0, self.f_num - s_num)
        elif self.op == "*":
            self.values.insert(0, self.f_num * s_num)
        elif self.op == "/":
            self.values.insert(0, self.f_num / s_num)


if __name__ == "__main__":
    app = App()
    app.mainloop()
from PIL import Image
import os
from pathlib import Path

def compress_image(image_path:str) -> None:
    '''Takes up a PNG file, compresses it and converts it to a WEBP.
    Uses the pillow, pathlib and os module to do this.
    Args:
        image_path: The path to the image (str)'''
    try:
        compression_level = 6
        img_nm = Path(os.path.basename(image_path))
        compressed_png_path =Path(f"images_webp/{img_nm}")

        if not(os.path.exists(compressed_png_path.with_suffix(".webp"))):
            # opening image
            img = Image.open(Path(image_path))
            # compressing image
            img.save(compressed_png_path, format="png", optimize=True, compress_level=compression_level)
            # opening compressed image
            img_compressed = Image.open(compressed_png_path)
            # Convert the compressed PNG to WebP
            img_compressed.save(compressed_png_path.with_suffix(".webp"), format="webp")
            # removing the compressed PNG
            os.remove(compressed_png_path)
        else:
            print("File already exists")

    except FileNotFoundError as e:
        print(f"Error: {e}")

paths = Path("images").glob("**/*.png")
for path in paths:
    compress_image(str(path))
from customtkinter import *
import random
from PIL import Image

class Dice(CTk):
    def __init__(self):
        super().__init__()

        self.title("Dice Stimulator")

        # Getting images into CTk
        self.dice1 = CTkImage(light_image=Image.open("images/dice1.png"), size=(300,300))
        self.dice2 = CTkImage(light_image=Image.open("images/dice2.png"), size=(300,300))
        self.dice3 = CTkImage(light_image=Image.open("images/dice3.png"), size=(300,300))
        self.dice4 = CTkImage(light_image=Image.open("images/dice4.png"), size=(300,300))
        self.dice5 = CTkImage(light_image=Image.open("images/dice5.png"), size=(300,300))
        self.dice6 = CTkImage(light_image=Image.open("images/dice6.png"), size=(300,300))

        # putting them in a list for random choice
        self.image_list = [self.dice1, self.dice2, self.dice3, self.dice4, self.dice5, self.dice6]
        # Information
        label = CTkLabel(self, text="press enter or click the button")
        label.grid(row=0, padx=10, pady=10)
        # Button to roll the dice
        btn = CTkButton(self, text="Roll The Dice", command=self.roll)
        btn.grid(row=2, padx=10, pady=10)
        # Connecting button to the enter key
        self.bind("<Return>", lambda event: btn.invoke())

    def roll(self):
        # choosing a random die face
        img = random.choice(self.image_list)
        # displaying it on the label
        self.label = CTkLabel(self, text="", image=img)
        self.label.grid(row=1, padx=10, pady=10)

if __name__ == "__main__":
    app = Dice()
    app.mainloop()
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

from bs4 import BeautifulSoup
import requests

from customtkinter import *
from PIL import Image
from io import BytesIO

class Motivator(CTk):
    """A GUI application for displaying random motivational images. When you are sad."""
    def __init__(self) -> None:
        """
        Initialize the Motivator GUI.

        Sets up the main window, question label, image label, and "Show Motivation" button.
        """
        super().__init__()

        self.title("Random Motivation")
        self.geometry("600x600")
        # getting image
        self.question = CTkLabel(self, text="Are you sad? Click the button below.")
        self.question.grid(row=0, pady=10)
        self.sad_image = CTkImage(light_image=Image.open("images/sad.jpg"), size=(300,300))
        # making image label
        self.ilsad = CTkLabel(self, image=self.sad_image, text="")
        # displaying image label
        self.ilsad.grid(row=1, pady=10)
        # Button to get a random motivational image
        self.show_motivation = CTkButton(self, text="Show Motivation", command=self.show_image).grid(row=2, pady=10)

    def get_img_url(self) -> str:
        """
        Retrieve a random motivational image URL from Unsplash.

        Returns:
            str: The URL of the random motivational image.
        """
        print("Getting image...")
        print("Please wait...")
        print("It might take a while...")

        # configuring chrome options so that the browser doesn't open up
        chrome_options = Options()
        chrome_options.add_argument("--headless")  # Run Chrome in headless mode (no GUI)
        chrome_options.add_argument("--disable-gpu")  # Required on some systems to avoid issues

        # setting up selenium' chrome driver to get the web page
        chrome_driver_path = "C:\Development\chromedriver.exe"
        service = Service(executable_path=chrome_driver_path)
        driver = webdriver.Chrome(service=service, options=chrome_options)

        # getting the webpage
        driver.get("https://source.unsplash.com/random/1080x810?motivational+quote")
        # getting its source code
        source = driver.page_source
        # making a soup of the html code to parse through it well
        soup = BeautifulSoup(source, 'html.parser')
        # finding the source url of the image
        img_url = soup.find('img')['src']
        # quitting the driver (a good practice)
        driver.quit()

        print("Got the image showing it...")
        return img_url
    
    def show_image(self) -> None:
        """
        Fetch and display the image got from self.get_img_url.

        Uses the get_img_url method to fetch the image URL and displays it on the GUI.
        """
        # getting url from the above function
        img_url = self.get_img_url()
        # getting the source code of the image's web page
        response = requests.get(img_url)
        # converting code of image to an image readable by python
        image = Image.open(BytesIO(response.content))
        # getting the image in customtkinter
        img = CTkImage(image, size=(540,405))
        print("showing the image...")
        # showing the image with the use of label
        label = CTkLabel(self, image=img, text='')
        label.grid(row=1, pady=10)


if __name__ == "__main__":
    app = Motivator()
    app.mainloop()
# FILE: rock_paper_scissors_gui.py
from customtkinter import *
from PIL import Image
from rock_paper_scissors import game


class RPS(CTk):
    """
    A class representing the Rock Paper Scissors game GUI.

    Inherits from customtkinter.CTk.

    Attributes:
    None

    Methods:
    __init__: Initializes the GUI and sets up the game window.
    check: Function to handle the player's choice and display the game result.

    Usage:
    app = RPS()
    app.mainloop()
    """
    def __init__(self) -> None:
        """
        Initializes the Rock Paper Scissors GUI.

        Creates and configures the main game window.

        Parameters:
        None

        Returns:
        None
        """
        super().__init__()
        self.title("Rock Paper Scissors")
        self.geometry("500x600")

        self.Label = CTkLabel(self, text="Choose Rock Paper or Scissors").grid(row=0,column=2,padx=150)

        # Create an instance of the CTkImage class for the 'rock' choice image
        # using the light_image parameter to load the image file from the given path.
        # The size parameter is set to (100, 100) to resize the image to the specified dimensions.
        self.rock_img = CTkImage(light_image=Image.open("rock.png"), size=(100,100))
        # Create an instance of the CTkButton class for the 'rock' choice button.
        # The image parameter is set to the previously created CTkImage instance,
        # so the button will display the 'rock' image as its icon.
        # The text parameter is set to an empty string to hide any text on the button.
        # The fg_color parameter is set to "#242424", which represents the foreground color (text color) of the button.
        # The hover_color parameter is set to "#242424", which represents the background color of the button when hovered.
        # The command parameter is set to a lambda function that calls the 'self.check()' method with argument 0,
        # representing the 'rock' choice, when the button is clicked.
        self.ilr = CTkButton(self, image=self.rock_img, text="", fg_color="#242424", hover_color="#242424", command=lambda: self.check(0))
        # Position the 'rock' choice button in the grid layout at row 1 and column 2.
        # The padx parameter is set to 150 to add horizontal padding around the button to create spacing.
        self.ilr.grid(row=1,column=2,padx=150)

        self.paper_img = CTkImage(light_image=Image.open("paper.png"), size=(100,100))
        self.ilp = CTkButton(self, image=self.paper_img, text="", fg_color="#242424", hover_color="#242424", command=lambda: self.check(1))
        self.ilp.grid(row=2,column=2,padx=150)

        self.scissors_img = CTkImage(light_image=Image.open("scissors.png"), size=(100,100))
        self.ils = CTkButton(self, image=self.scissors_img, text="",fg_color="#242424", hover_color="#242424", command=lambda: self.check(2))
        self.ils.grid(row=3,column=2,padx=150)


        self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
        self.qb.grid(row=4,column=2,padx=150,pady=10)

    def check(self, player_choice: int) -> None:
        """
        Function to handle the player's choice and display the game result.

        Parameters:
        player_choice (int): The player's choice. Should be an integer between 0 and 2,
                             where 0 represents 'rock', 1 represents 'paper', and
                             2 represents 'scissors'.

        Returns:
        None
        """
        result = game(player_choice)
        res1 = CTkLabel(self, text=result[0],text_color ="#ADD8E6").grid(row=5,column=2,padx=150,pady=10)
        res2 = CTkLabel(self, text=result[1], text_color="pink").grid(row=6,column=2,padx=150,pady=10)
        res3 = CTkLabel(self, text=result[2]).grid(row=7,column=2,padx=150,pady=10)


if __name__ == "__main__":
    app = RPS()
    app.mainloop()
# FILE: rock_paper_scissors.py
import random

def game(your_choice: int) -> list:
    """
    Function to play a single round of Rock-Paper-Scissors game.

    Parameters:
    your_choice (int): The player's choice. Should be an integer between 0 and 2,
                       where 0 represents 'rock', 1 represents 'paper', and
                       2 represents 'scissors'.

    Returns:
    list: A list containing the results of the game round.
          The list elements are as follows:
          1. The player's choice.
          2. The computer's choice.
          3. The result of the round, which can be one of the following strings:
             - "Tie🤝" if the player and computer made the same choice.
             - "You won" if the player's choice beats the computer's choice.
             - "You lost" if the player's choice loses to the computer's choice.
    """
    choices = ["rock", "paper", "scissors"]
    computer_choice = random.randint(0, 2)
    
    # Create a dictionary to map the player's and computer's choices to outcomes
    outcomes = {
        (0, 0): "It's a Tie",
        (0, 1): "You lost",
        (0, 2): "You won",
        (1, 0): "You won",
        (1, 1): "It's a Tie",
        (1, 2): "You lost",
        (2, 0): "You lost",
        (2, 1): "You won",
        (2, 2): "It's a Tie",
    }

    result = [f"Your choice:\n{choices[your_choice]}", f"Computer's choice:\n{choices[computer_choice]}", outcomes[(your_choice, computer_choice)]]
    return result

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Well Done Champ</title>
</head>

<body>
    <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
    <lottie-player src="https://assets6.lottiefiles.com/packages/lf20_pKiaUR.json" background="transparent" speed="1" style="width: 300px; height: 300px;" loop autoplay></lottie-player>

</body>

</html>
import webbrowser
class TaskAlreadyExistsError(Exception):
    """Exception raised when a task already exists in the list."""
    def __init__(self, message):
        super().__init__(message)

class TaskNotFoundError(Exception):
    """Exception raised when a task is not found in the list."""
    def __init__(self, message):
        super().__init__(message)

class ToDo:
    """Class representing a to-do list."""

    def __init__(self) -> None:
        """Initialize an empty to-do list. Which is a dictionary"""
        self.tasks = {}

    def add_task(self, task:str, deadline:str) -> str:
        """Add a new task to the list.

        Args:
            task (str): The task description.
            deadline (str): The deadline in dd-mm-yy format.

        Returns:
            str: A confirmation message indicating that the task has been added.

        Raises:
            TaskAlreadyExistsError: If the task already exists in the list.
            TypeError: If the task parameter is not a string.
            ValueError: If the task parameter is an empty string.
        """
        if not isinstance(task, str):
            raise TypeError("Task must be a string.")
        if not task:
            raise ValueError("Task cannot be an empty string.")
        if task in self.tasks.keys():
            raise TaskAlreadyExistsError(f"{task} already exists in the list.")
        else:
            self.tasks[task] = {'status':False, 'deadline':deadline}
            print(self.tasks)
            return f"Task has been added to the list."
        
    def finish_task(self, task:str) -> str:
        """
        Mark a task as finished and open a web page for celebration.

        Args:
            task (str): The task to mark as finished.

        Returns:
            str: A message confirming that the task has been marked as finished.

        Raises:
            TypeError: If the task is not a string.
            TaskNotFoundError: If the task does not exist in the list.
        """
        try:
            if not isinstance(task, str):
                raise TypeError("Task must be a string.")
            self.tasks[task]['status'] = True
            webbrowser.open("well_done.html")
            return "Task finished"
        except Exception:
            raise TaskNotFoundError("No such task in the list.")
    
    def remove_task(self, task:str) ->str:
        """
        Remove a task from the task list.

        Args:
            task (str): The task to remove.

        Returns:
            str: A message confirming that the task has been removed.

        Raises:
            TypeError: If the task is not a string.
            TaskNotFoundError: If the task does not exist in the list.
        """
        try:
            if not isinstance(task, str):
                raise TypeError("Task must be a string.")
            del self.tasks[task]
            return "Task removed"
        except Exception:
            raise TaskNotFoundError("No such task in the list.")
    
    def update_task(self, task:str, new_deadline:str) -> str:
        """
        Update the status and deadline of a task.

        Args:
            task (str): The task to update.
            new_deadline (str): The new deadline for the task in dd-mm-yy format.

        Returns:
            str: A message confirming that the task has been updated.

        Raises:
            TypeError: If the task is not a string.
            TaskNotFoundError: If the task does not exist in the list.
        """
        try:
            if not isinstance(task, str):
                raise TypeError("Task must be a string.")
            self.tasks[task] = {'status': False, 'deadline': new_deadline}
            return "Task updated"
        except Exception:
            raise TaskNotFoundError("No such task in the list.")
    
    def view_tasks(self) -> list:
        """View the tasks in the list.

        Returns:
            list: A list of task descriptions and their status or completion.

        Raises:
            TaskNotFoundError: If there are no tasks in the list.
        """
        try:
            task_list = []
            for task in self.tasks:
                if self.tasks[task]['status'] == False:
                    task_list.append(f"{task} by {self.tasks[task]['deadline']}")
                if self.tasks[task]['status'] == True:
                    task_list.append(f"{task} finished")
            return task_list
        except Exception:
            raise TaskNotFoundError("There are no tasks in the list.")

if __name__ == "__main__":
    app = ToDo()
    while True:
        print("-------------------------------")
        print()
        print("1. Add task")
        print("2. View tasks")
        print("3. delete task")
        print("4. update task")
        print("5. finish task")
        print("6. exit app")
        print()
        print("-------------------------------")

        choice = int(input("Enter your choice: "))
        if choice == 1:
            task = input("Enter task: ")
            deadline = input("Enter task deadline: ")
            try:
                message = app.add_task(task, deadline)
                print(message)
            except TypeError as e:
                print(e)
            except ValueError as e:
                print(e)
            except TaskAlreadyExistsError as e:
                print(e)
        elif choice == 2:
            try:
                print("-------------------------------")
                task_list = app.view_tasks()
                for task in task_list:
                    print(task)
                print("-------------------------------")
            except TaskNotFoundError as e:
                print(e)
        elif choice == 3:
            try:
                task = input("Enter the task you want to remove: ")
                message = app.remove_task(task)
                print(message)
            except TypeError as e:
                print(e)
            except TaskNotFoundError as e:
                print(e)
        elif choice == 4:
            try:
                task = input("Enter the task you want to update: ")
                deadline = input("What is the new deadline? ")
                message = app.update_task(task,deadline)
                print(message)
            except TypeError as e:
                print(e)
            except TaskNotFoundError as e:
                print(e)
        elif choice == 5:
            try:
                task = input("Enter the task you have finised: ")
                message = app.finish_task(task)
                print(message)
            except TypeError as e:
                print(e)
            except TaskNotFoundError as e:
                print(e)
        elif choice == 6:
            print("Thanks for using")
            break
        else:
            print("Invalid choice!")
import webbrowser
import os
import speech_recognition as sr
import pyttsx3


class Doraemon:
    """This is a simple speech command bot. It is made with few functions and elif ladder. It can take speech input.
    It will perform two categories of tasks:
        1. searching through the web.
        2. opening some apps. Both on voice command. It will also reply to user by talking.
    It has four major methods:
        1. __init__: which is an empty constructor
        2. speak: that speaks the text input and also prints it on the console.
        3. takeCommand: It listens with the default microphone of the system and returns the spoken text
        4. run_bot: This is the interface user will get in the instance of this class. It has an infinite while loop to take commands and execute them until the user asks to stop.
    Libraries used:
        webbrowser: to browse through web
        os: to open applications
        speech_recognition: to take voice commands
        pyttsx3: to give voice outputs
    """
    def __init__(self):
        pass

    def speak(self, text:str) -> None:
        engine = pyttsx3.init()
        print(text)
        engine.say(text)
        engine.runAndWait()
        return None
    
    def takeCommand(self) -> str:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Listening...")
            r.pause_threshold = 1
            audio = r.listen(source)
        try:
            print("Recognizing...")    
            query = r.recognize_google(audio, language='en-in')
            return query

        except Exception:
            print("Say that again please...")
            return ""
    
    def open_youtube(self) -> None:
        self.speak("What should I search for? ")
        cm = input()
        self.speak(f"Searching in youtube {cm}")
        webbrowser.open(f"https://www.youtube.com/results?search_query={cm}")

    def open_google(self) -> None:
        self.speak("What should I search for? ")
        cm = input()
        self.speak(f"Searching in google {cm}")
        webbrowser.open(f"https://www.google.com/search?q={cm}")

    def open_notepad(self) -> None:
        self.speak("Opening Notepad")
        os.system("C:\\Windows\\notepad.exe")

    def open_vs_code(self) -> None:
        self.speak("Opening VS Code")
        os.startfile("C:\\Microsoft VS Code2\\Code.exe")

    def run_bot(self) -> None:
        self.speak("How can i help you buddy?")
        while True:
            instruction = self.takeCommand().lower()
            if instruction == "":
                continue
            elif "youtube" in instruction:
                self.open_youtube()

            elif "google" in instruction:
                self.open_google()

            elif "notepad" in instruction:
                self.open_notepad()

            elif "vs code" in instruction:
                self.open_vs_code()

            elif "quit" or "exit" in instruction:
                self.speak("Ok bye bye have a great time")
                break

            elif "thanks" in instruction:
                self.speak("NO thanks in friendship")
                
            else:
                self.speak("Invalid request")

my_buddy = Doraemon()
my_buddy.run_bot()
# Importing necessary classes from PyQt5 library
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QIcon
from PyQt5.QtWebEngineWidgets import *

class MyWebBrowser(): # Creating a class for the web browser
    """
    A simple web browser application using PyQt5.
    """
    def __init__(self):
        """
        Initialize the web browser.
        """
        self.window = QWidget() # Creating a QWidget instance
        self.window.setWindowTitle("My Web Browser") # Setting the window title

        # main layout: holds browser and horizontal layout
        self.layout = QVBoxLayout()
        # holds the buttons and url bar
        self.horizontal = QHBoxLayout()

        self.url_bar = QLineEdit()
        self.url_bar.setMaximumHeight(30)

        self.go_btn = QPushButton("Go")
        self.go_btn.setMinimumHeight(30)

        # to load a page when enter is pressed in the url bar
        self.url_bar.returnPressed.connect(self.go_btn.click)  # Connect the returnPressed signal to the go_btn click slot

        self.back_btn = QPushButton("<")
        self.back_btn.setMinimumHeight(30)

        self.forward_btn = QPushButton(">")
        self.forward_btn.setMinimumHeight(30)

        self.reload_btn = QPushButton()
        self.reload_btn.setIcon(QIcon('images/reload.png'))  # Set the icon using the image file path
        self.reload_btn.setMinimumHeight(30)

        # Adding the widgets to the horizontal layout
        self.horizontal.addWidget(self.reload_btn)
        self.horizontal.addWidget(self.url_bar)
        self.horizontal.addWidget(self.go_btn)
        self.horizontal.addWidget(self.back_btn)
        self.horizontal.addWidget(self.forward_btn)

        self.browser = QWebEngineView()

        # connecting buttons
        self.go_btn.clicked.connect(lambda: self.navigate(self.url_bar.text()))
        self.back_btn.clicked.connect(self.go_back)
        self.forward_btn.clicked.connect(self.go_forward)
        self.reload_btn.clicked.connect(self.browser.reload)

        self.layout.addLayout(self.horizontal)  # Adding the horizontal layout to the main layout
        self.layout.addWidget(self.browser) # Adding the browser to the main layout

        self.browser.setUrl(QUrl("https://google.com")) # Setting the initial URL for the browser

        self.window.setLayout(self.layout) # Setting the main layout for the window

        self.window.show()


    def navigate(self, url):
        """
        Navigate to the specified URL.

        Args:
            url (str): The URL to navigate to.
        """
        if not url.startswith("http"): # Checking if the URL does not start with "http"
            url = "https://" + url # Prepending "https://" to the URL
            self.url_bar.setText(url)  # Updating the URL bar text with the modified URL
        self.browser.setUrl(QUrl(url))  # Navigating the browser to the specified URL

    def go_back(self):
        """
        Go back to the previous page.
        """
        self.url_bar.setText("") 
        self.browser.back()

    def go_forward(self):
        """
        Go forward to the next page.
        """
        self.url_bar.setText("") 
        self.browser.forward()
    

app = QApplication([]) # Creating a QApplication instance
window = MyWebBrowser() # Creating an instance of the MyWebBrowser class
app.exec_() # Starting the application event loop
from customtkinter import *
from PIL import Image

class adventure_game(CTk):
    def __init__(self):
        super().__init__()

        self.images = [CTkImage(light_image=Image.open("Timages\\two roads.jpg"), size=(364,456)),
                       CTkImage(light_image=Image.open("Timages\\island.jpg"),size=(402,226)),
                       CTkImage(light_image=Image.open("Timages\\hole.jpg"),size=(595,396)),
                       CTkImage(light_image=Image.open("Timages\\Three doors.png"),size=(420,306)),
                       CTkImage(light_image=Image.open("Timages\\shark.jpg"),size=(400,266)),
                       CTkImage(light_image=Image.open("Timages\\fire.jpg"),size=(589,396)),
                       CTkImage(light_image=Image.open("Timages\\wolves.jpg"),size=(600,400)),
                    ]

        self.first_label = CTkLabel(self, text="You're at a cross road. Where do you want to go? Type \"left\" or \"right\"", font=("Arial", 16))
        self.first_label.pack()
        self.first_image = CTkLabel(self, image=self.images[0], text="")
        self.first_image.pack()

        self.choice1 = CTkEntry(self)
        self.choice1.pack()

        self.confirm = CTkButton(self, text="Confirm", command=self.choice_one)
        self.confirm.pack()

    def choice_one(self):
        ch1 = self.choice1.get()
        # Clear the app window
        for widget in self.winfo_children():
            widget.destroy()
        if ch1 == "left":
            self.second_label = CTkLabel(self, text="You've come to a lake. There is an island in the middle of the lake. Type \"wait\" to wait for a boat. Type \"swim\" to swim across.", font=("Arial", 16))
            self.second_label.pack()
            self.second_image = CTkLabel(self, image=self.images[1], text="")
            self.second_image.pack()

            self.choice2 = CTkEntry(self)
            self.choice2.pack()

            self.confirm = CTkButton(self, text="Confirm",command=self.choice_two)
            self.confirm.pack()
        else:
            self.second_label = CTkLabel(self, text="You fell into a hole. Game Over.", font=("Arial", 16))
            self.second_label.pack()
            self.second_image = CTkLabel(self, image=self.images[2], text="")
            self.second_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()

    def choice_two(self):
        ch2 = self.choice2.get()
        # Clear the app window
        for widget in self.winfo_children():
            widget.destroy()
        if ch2 == "wait":
            self.third_label = CTkLabel(self, text="You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose?", font=("Arial", 16))
            self.third_label.pack()
            self.third_image = CTkLabel(self, image=self.images[3], text="")
            self.third_image.pack()

            self.choice3 = CTkEntry(self)
            self.choice3.pack()

            self.confirm = CTkButton(self, text="Confirm",command=self.choice_three)
            self.confirm.pack()
        else:
            self.third_label = CTkLabel(self, text="You get attacked by an angry trout. Game Over.", font=("Arial", 16))
            self.third_label.pack()
            self.third_image = CTkLabel(self, image=self.images[4], text="")
            self.third_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()

    def choice_three(self):
        ch3 = self.choice3.get()
        # Clear the app window
        for widget in self.winfo_children():
            widget.destroy()

        if ch3=="yellow":
            self.fourth_label = CTkLabel(self, text="You win\nHere's the treasure:-\nIt's a comic website.\n-----------Happy Reading-----------")
            self.fourth_label.pack()
            import antigravity
            from time import sleep
            sleep(1)
            self.quit()

        elif ch3 == "red":
            self.fourth_label = CTkLabel(self, text="It's a room full of fire. Game Over.", font=("Arial", 16))
            self.fourth_label.pack()
            self.fourth_image = CTkLabel(self, image=self.images[5], text="")
            self.fourth_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()

        elif ch3 == "blue":
            self.fourth_label = CTkLabel(self, text="You enter a room of beasts. Game Over.", font=("Arial", 16))
            self.fourth_label.pack()
            self.fourth_image = CTkLabel(self, image=self.images[6], text="")
            self.fourth_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()
            
        else:
            self.fourth_label = CTkLabel(self, text="Game Over.", font=("Arial", 16))
            self.fourth_label.pack()
            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()


app = adventure_game()
app.mainloop()
def WordCounter(text:str) -> int:
    # getting sentences
    lines = text.split("\n")

    words = []
    for line in lines:
        # words from sentences
        print(line)
        for word in line.split(" "):
            words.append(word)
    return len(words)

# taking multiline input
lines = []
print("Please Enter your text: ")
while True:
    line = input()
    if not line:
        break
    lines.append(line)

# providing the string of input to the WordCounter function
words = WordCounter(str(lines))
print(f'Your text has {words} words.')
import mysql.connector
from customtkinter import *

class DatabaseMediator:
    """Handles the connection and interaction with the MySQL database."""
    def __init__(self, host, user, password, database, table_name,*columns):
        """
        Initializes the DatabaseMediator object.
        
        Args:
            host (str): The MySQL server host.
            user (str): The username for the database connection.
            password (str): The password for the database connection.
            database (str): The name of the database.
            table_name (str): The name of the table storing the passwords.
            *columns (str): Variable-length argument list of column names in the table.
        """
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.table_name = table_name
        self.columns = columns
        self.mydb = mysql.connector.connect(
        host=self.host,
        user=self.user,
        password=self.password,
        database=self.database
        )
        self.mycursor = self.mydb.cursor()

    def insert_data(self, *args):
        """
        Inserts data into the MySQL table.
        
        Args:
            *args: Variable-length argument list of values to be inserted.
        """
        self.mycursor.execute(f"INSERT INTO {self.table_name} ({', '.join(list(self.columns))}) VALUES {args}")
        self.mydb.commit()
        
    def retrieve_data(self):
        """
        Retrieves all data from the MySQL table.
        
        Returns:
            list: A list of tuples representing the retrieved data.
        """
        self.mycursor.execute(f"SELECT * FROM {self.table_name}")
        myresult = self.mycursor.fetchall()
        return myresult

class PasswordManager(CTk):
    """The main GUI class for the Password Manager application."""
    def __init__(self):
        """Initializes the PasswordManager GUI."""
        super().__init__()
        self.title("Password Manager")
		#change the host, username, and password to yours
        self.database_connection = DatabaseMediator("HOST", "USERNAME", "PASSWORD", "password_manager", "passwords", "account_name", "account_id", "account_password")
        
        self.frame = CTkFrame(self)
        self.frame.grid(row=0, columnspan=2, padx=10, pady=10)

        self.account_name = CTkEntry(self.frame, placeholder_text="Account name")
        self.account_name.pack(padx=10, pady=10)
        
        self.account_id = CTkEntry(self.frame, placeholder_text="Enter your user ID here")
        self.account_id.pack(padx=10, pady=10)

        self.account_password = CTkEntry(self.frame, placeholder_text="Enter your Password")
        self.account_password.pack(padx=10, pady=10)

        self.save_password = CTkButton(self, text="Save Password", command=self.save)
        self.save_password.grid(row=1, column=0, padx=10, pady=10)

        self.view_password = CTkButton(self, text="View Passwords", command=self.view)
        self.view_password.grid(row=1, column=1, padx=10, pady=10)

    def save(self):
        """Saves the password to the database."""
        acc_nm = self.account_name.get()
        acc_id = self.account_id.get()
        acc_password = self.account_password.get()
        self.database_connection.insert_data(acc_nm, acc_id, acc_password)
        label = CTkLabel(self, text="Passwords Saved successfully...")
        label.grid(row=2, columnspan=2, padx=10, pady=10)

    def view(self):
        """Retrieves and displays all passwords from the database."""
        passwords = self.database_connection.retrieve_data()
        result = ""
        for i in range(len(passwords)):
            result += f"\n{i+1}. {passwords[i]}"
        result_frame = CTkFrame(self)
        result_frame.grid(row=3, columnspan=2, padx=10, pady=10)
        res_label = CTkLabel(result_frame, text=result)
        res_label.pack()


app = PasswordManager()
app.mainloop()
import random
from os import system

# Word categories
categories = {
    "Coding": ["Python", "Variable", "Function", "Loop", "Algorithm", "Debugging", "Syntax", "Class", "Recursion", "Library"],
    "Gaming": ["Console", "Controller", "Quest", "Level", "Avatar", "Powerup", "Multiplayer", "Strategy", "Virtual", "Adventure"],
    "Movies": ["Action", "Comedy", "Thriller", "Drama", "Romance", "SciFi", "Fantasy", "Horror", "Animation", "Mystery"],
    "Travel": ["Beach", "Adventure", "Culture", "Explore", "Passport", "Destination", "Backpack", "Journey", "Sightseeing", "Vacation"]
}

# Get player name
player = input("Enter your name: ")

print()
print(f"\t\t\tWelcome to this word guessing game {player}.")
print("\t\t\tYou will get 10 chances to guess the word.")
print(f"\t\t\t\t\t\tAll The Best {player}")
print("\n\n")

# Print available categories
for i in categories.keys():
    print(f"{i}")

# Select category
category = input("Select category: ").title()
if category not in categories:
    print("Invalid category!")
    exit()

# Select a random word from the chosen category
word = random.choice(categories[category])

# Initialize guessed and wrong variables
guessed = len(word) * '_'
wrong = ""
chances = 10  # Total number of guesses

# Clear the console screen
system('cls')

# Display initial word with underscores
for i in word:
    print("_", end=" ")
print()
# Main game loop
while chances > 0:
    word = word.lower()
    guessed = guessed.lower()

    # Check if the player has guessed all the characters correctly
    if sorted(guessed) == sorted(word):
        print(f"Congrats {player}, you win!!")
        print(f"The correct word was, {word}")
        break

    # Ask the player to enter a character
    guess = input("Enter a character: ").lower()

    # Check if the guessed character is correct
    if guess in word:
        for i in range(len(word)):
            if word[i] == guess:
                tempg = list(guessed)
                tempg.pop(i)
                tempg.insert(i, guess)
                guessed = ''.join([elem for elem in tempg])
        
        # Display the current progress
        for i in range(len(word)):
            if word[i] == guessed[i]:
                print(word[i], end=" ")
            else:
                print("_", end=" ")
        
        print("\nYou are correct!!\n\n")
   
    # If the guessed character is incorrect
    elif guess not in word:
        wrong += guess
        print("\nYou are wrong!!\n\n")
        print(f"Chances left = {chances}")
        chances -= 1
        
# Player has used all the chances
if chances == 0:
    print(f"Alas {player}, You Lose!")
    print("Better luck next time...")
    print(f"The correct word was, {word}")
    print("Thanks for Playing, Have a nice day!")
from customtkinter import *
import pandas as pd

class LoginFrame(CTkFrame):
    """
    A frame for login functionality.
    """
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        """
        Initialize the LoginFrame.

        Args:
            master: The parent widget.
            kwargs: Additional keyword arguments for the frame.
        """
        # Create and grid the login label
        self.log = CTkLabel(self, text="LOG IN", text_color="#ffe9a6", font=("Verdana",20))
        self.log.grid(row=0, column=0,padx=10, pady=10)

        # Create and grid the username entry field
        self.user = CTkEntry(self, placeholder_text="Username", text_color="white", fg_color="#030126", border_color="#030126")
        self.user.grid(row=1, column=0,padx=10, pady=10)

        # Create and grid the password entry field
        self.password = CTkEntry(self, placeholder_text="Password", show="*", text_color="white", fg_color="#030126", border_color="#030126")
        self.password.grid(row=2, column=0,padx=10, pady=10)

        # Create and grid the submit button
        self.submit = CTkButton(self, text="Submit", fg_color="#fccc3d", text_color="#2e3140", hover=False, command=self.check, font=("arial",14))
        self.submit.grid(row=3, column=0,padx=10, pady=10)

    def check(self):
        """
        Check if the entered username and password are valid.
        """

        user = self.user.get()
        if self.find_user(user):
            passw = self.password.get()
            if self.match_password(user, passw):
                # Clear the app window and show success message
                for widget in app.winfo_children():
                    widget.destroy()
                label = CTkLabel(app, text="Successfully Logged In!!")
                label.grid(row=1, column=1, padx=10, pady=10)
            else:
                # Show invalid password message
                label = CTkLabel(app, text="Invalid Password")
                label.grid(row=1, column=1, padx=10, pady=10)
        else:
            # Show invalid username message
            label = CTkLabel(app, text="Invalid Username")
            label.grid(row=1, column=1, padx=10, pady=10)

    def find_user(self, username:str) -> bool:
        """
        Find if a user with the given username exists.

        Args:
            username: The username to search for.

        Returns:
            bool: True if the username exists, False otherwise.
        """
        df = pd.read_csv("users.csv")
        for i in range(len(df)):
            cuser = list(df.loc[i])[0]
            if username ==cuser:
                return True
        else:
            return False
        
    def match_password(self, username:str, password:str) -> bool:
        """
        Check if the given password matches the username.

        Args:
            username: The username to check.
            password: The password to match.

        Returns:
            bool: True if the password matches, False otherwise.
        """
        df = pd.read_csv("users.csv")
        for i in range(len(df)):
            cuser = list(df.loc[i])[0]
            passw = list(df.loc[i])[1]
            if username ==cuser:
                if password == passw:
                    return True
                return False


app = CTk()

frame = LoginFrame(master=app)
frame.grid(row=0, column=1,padx=10, pady=10)

app.mainloop()
#A YouTube Video Downloader GUI In Python
from customtkinter import *
from pytube import YouTube

def Download():
    """
    Function to download YouTube videos based on the provided link.
    """
    link = inp_link.get()
    try:
        # making object of the YouTube class from pytube
        youtubeObject = YouTube(link)
        # setting resolution to best
        youtubeObject = youtubeObject.streams.get_highest_resolution()
        # downloading the video
        youtubeObject.download()
        # clearing input widget after the download is successful
        inp_link.delete(0, 'end')
        # providing successfully downloaded message to the user provinding the location of video
        label = CTkLabel(app, text="The video's Download is completed successfully. You can check it in the same directory.")
        label.grid(row=2, column=0, columnspan=2)

    except Exception as e:
        # displaying errors if any
        label = CTkLabel(app, text=e)
        label.grid(row=2, column=0, columnspan=2)
    
# creating a GUI window
app = CTk()
# getting the link
inp_link = CTkEntry(app, placeholder_text="Enter your link here: ")
inp_link.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
# button to download the video at the given link
download = CTkButton(app, text="Download", command=Download)
download.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
app.mainloop()
from customtkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename

class Notepad(CTk):
    def __init__(self):
        """Initialize the Notepad application."""
        super().__init__()
        self.title("Notepad")
        self.iconbitmap("images/notepad.ico")
        self.geometry("600x600")
        self.configure(padx=10, pady=10)

        # file path
        self.file = None

         # Create a Frame for the menu and textarea
        self.frame = CTkFrame(self)
        self.frame.pack(fill="both", expand=True, padx=10, pady=10)

        # file menu
        self.File_var = StringVar(value="File")
        self.filemenu = CTkOptionMenu(self.frame,values=["File", "New", "Open", "Save"],
                                         command=self.file_menu_callback,
                                         variable=self.File_var,button_color="black", fg_color="black")
        
        self.filemenu.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        # Textbox to get text
        self.textarea = CTkTextbox(self.frame, font=("Consolas", 11))
        self.textarea.grid(row=1,column=0,columnspan=2, padx=10, pady=10, sticky="nsew")
        # create CTk scrollbar
        # It only appears in full screen mode
        ctk_textbox_scrollbar = CTkScrollbar(self.frame, command=self.textarea.yview)
        ctk_textbox_scrollbar.grid(row=1,column=1, sticky="ns")

        # connect textbox scroll event to CTk scrollbar
        self.textarea.configure(yscrollcommand=ctk_textbox_scrollbar.set)


        # Bind the <Configure> event to the resize_textarea function
        self.bind("<Configure>", self.resize_textarea)

    # event is needed to bind it to resize event
    def resize_textarea(self, event):
        """Adjust the size of the textarea based on the available space."""
        # Calculate the new width and height for the textarea based on the available space
        available_width = self.winfo_width() - 40  # Subtract the padding
        available_height = self.winfo_height() - 40  # Subtract the padding

        # Update the width and height of the textarea
        self.textarea.configure(width=available_width, height=available_height)

    def file_menu_callback(self,choice):
        """Handle the file menu commands."""
        if choice=='New':
            self.new()
        elif choice=='Open':
            self.open()
        elif choice=='Save':
            self.save()

    def new(self):
        """Create a new file."""
        self.file = None
        self.title("Notepad")
        self.textarea.focus_set()
        self.textarea.delete("0.0", 'end')

    def open(self):
        """Open an existing file."""
        self.file = askopenfilename(defaultextension=".txt",
                           filetypes=[("All Files", "*.*"),
                                     ("Text Documents", "*.txt")])
        if self.file == "":
            self.file = None
        else:
            self.title(os.path.basename(self.file))
            self.textarea.delete("0.0", 'end')
            with open(self.file, 'r') as f:
                self.textarea.insert("0.0", f.read())

    def save(self):
        """Save the current file."""
        if self.file == None:
            self.file = asksaveasfilename(initialfile = 'Untitled.txt', defaultextension=".txt",
                           filetypes=[("All Files", "*.*"),
                                     ("Text Documents", "*.txt")])
            if self.file =="":
                self.file = None
            else:
                with open(self.file, 'w') as f:
                    f.write(self.textarea.get("0.0", "end"))



if __name__ == '__main__':
    app = Notepad()
    app.mainloop()
star

Fri Sep 01 2023 10:29:09 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:26:10 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:24:25 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:23:13 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:22:02 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:20:44 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:15:03 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Sep 01 2023 10:12:32 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Sep 01 2023 10:06:47 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:02:42 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:00:57 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 09:59:21 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 09:56:34 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 09:51:37 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Sep 01 2023 09:50:22 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Sat Aug 26 2023 10:00:48 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:59:27 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:58:13 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:49:26 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:46:55 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:44:22 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:43:02 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:37:50 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:36:39 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:30:03 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Sat Aug 26 2023 09:28:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Aug 25 2023 11:20:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 11:19:45 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:56:25 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:54:10 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:50:48 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:40:30 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:39:25 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:38:35 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:36:42 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:35:40 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 15:31:16 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:30:22 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:29:31 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:28:38 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:27:33 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:22:30 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 15:18:08 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 14:24:12 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:23:05 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:22:01 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:20:40 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:19:26 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:18:20 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 15:00:52 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:59:56 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:58:47 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:55:07 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:16:44 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:15:28 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:13:58 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:12:46 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 13:00:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:58:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:56:38 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:53:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:52:15 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Jul 28 2023 11:41:34 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Fri Jul 28 2023 11:36:31 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Tue Jul 25 2023 13:07:16 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Tue Jul 25 2023 12:35:30 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Sat Jul 22 2023 11:26:52 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day21
star

Fri Jul 21 2023 12:33:53 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day20
star

Thu Jul 20 2023 13:22:11 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day19
star

Wed Jul 19 2023 15:00:17 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-10-your-own-gallery-in-python/

#python #python-hub #day10
star

Wed Jul 19 2023 14:58:30 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-9-a-random-wikipedia-article-generator-gui-in-python/

#python #python-hub #day9
star

Wed Jul 19 2023 14:57:02 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-8-a-number-guessing-game-in-python/

#python #python-hub #day8
star

Wed Jul 19 2023 14:55:28 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-7-mini-calculator-gui-with-python/

#python #python-hub #day7
star

Wed Jul 19 2023 14:53:32 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-6-a-png-to-webp-converter-with-python/

#python #python-hub #day6
star

Wed Jul 19 2023 14:51:05 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-5-dice-stimulator-python-ctk-gui/

#python #python-hub #day5
star

Wed Jul 19 2023 14:48:29 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-4-your-motivator-with-python-and-unsplash/

#python #python-hub #day4
star

Wed Jul 19 2023 14:45:44 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/rock-paper-scissors-gui-in-python-python-python-hub-day3/64b7f6af5d31ad00134f17c1#!

#python #python-hub #day3
star

Wed Jul 19 2023 14:43:59 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/rock-paper-scissors-gui-in-python-the-gui-code-python-python-hub-day3/64b7f7185d31ad00134f17c3

#python #python-hub #day3
star

Wed Jul 19 2023 14:40:58 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/to-do-list-interface-with-lottie-in-python-python-python-hub-day2/64b7f5735d31ad00134f17be

#python #python-hub #day2
star

Wed Jul 19 2023 14:38:43 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/to-do-list-interface-with-lottie-in-python-html-code-python-python-hub-day2/64b7f5fa5d31ad00134f17bf

#python #python-hub #day2
star

Wed Jul 19 2023 14:32:45 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day1
star

Tue Jul 18 2023 12:08:20 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day17
star

Mon Jul 17 2023 13:05:19 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-16-word-counter-in-python/

#python #python-hub #day16
star

Sun Jul 16 2023 11:46:19 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day15
star

Sat Jul 15 2023 15:20:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day11
star

Sat Jul 15 2023 15:19:13 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day12
star

Sat Jul 15 2023 15:17:09 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day13
star

Sat Jul 15 2023 10:26:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day14
star

Sat Jul 15 2023 04:02:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #yourexcellentfirstprogram in python
star

Sat Jul 15 2023 04:01:16 GMT+0000 (Coordinated Universal Time)

#python #python-hub #yourexcellentfirst program in python

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension