├── .gitignore ├── API-quote-GUI-app ├── background.png ├── main.py └── next.png ├── Amazon-price-tracker └── main.py ├── Automated-birthday-wishes-via-email ├── birthdays.csv ├── letter_templates │ ├── letter_1.txt │ ├── letter_2.txt │ └── letter_3.txt └── main.py ├── Automated-send-motivation_quote_via_email ├── quotes.txt ├── send_email_and_datetime_basic.py └── send_quote_weekly.py ├── Beautiful-soup-Hacker-News-Website └── main.py ├── Beautiful-soup-Spotify-playlist ├── main.py └── token.txt ├── Beautiful-soup-exercises ├── basic.py └── website.html ├── Beautiful-soup-top-100-movies-website ├── main.py └── must_watch_movies.txt ├── Bidder-and-winner ├── .upm │ └── store.json ├── __pycache__ │ └── art.cpython-38.pyc ├── art.py ├── main.py ├── poetry.lock └── pyproject.toml ├── Blackjack ├── Blackjack_Flowchart.pdf ├── art.py └── main.py ├── Coffee-machine ├── Coffee-Machine-Program-Requirements.pdf ├── __pycache__ │ └── menu.cpython-310.pyc ├── main.py └── menu.py ├── Color-art-turtle-module ├── generate a Spirograph, circle loop.py ├── generate a random wander turtle.py └── print a n-number of sides of polygon.py ├── Comprehension-exercises ├── Dictionary-comprehension │ ├── Celsius _to_Fahrenheit.py │ ├── basic.py │ └── split_string_into_list.py └── List-comprehension │ ├── basic.py │ ├── filtering_even number.py │ ├── find_same_number_in_both_files │ ├── file1.txt │ ├── file2.txt │ └── main.py │ └── squaring_number.py ├── Exception-handling-exercises ├── NATO_Phonetic.py ├── basic.py ├── index_error.py ├── key_error.py └── nato_phonetic_alphabet.csv ├── Extra Knowledge ├── intermediate level & method │ ├── __main__ │ │ ├── main.py │ │ └── module1.py │ ├── enumerate │ │ └── main.py │ ├── flask │ │ ├── __pycache__ │ │ │ └── main.cpython-310.pyc │ │ └── main.py │ ├── lambda │ │ └── main.py │ ├── map, filter, reduce │ │ ├── filter.py │ │ ├── main.py │ │ ├── map.py │ │ └── reduce.py │ ├── python_exercise │ │ ├── idex_of_last_1.py │ │ ├── increment_of_digit_list.py │ │ └── zero_reaplcec_to_5.py │ ├── read_file │ │ └── read_file.py │ ├── unpack_tuple_&_list │ │ └── main.py │ └── yield │ │ └── main.py └── modules │ ├── datetime │ └── date.py │ ├── openpyxl │ ├── example.xlsx │ ├── read_created_excel.py │ ├── sample.xlsx │ ├── start-up.py │ └── write_new_excel.py │ ├── pandas │ ├── dataframe.py │ ├── descriptive.py │ └── series.py │ ├── pyqt5 │ ├── datetime │ │ ├── current_date_time.py │ │ ├── difference_days.py │ │ └── number_of_day.py │ ├── event & signal │ │ ├── reimplementing_event.py │ │ └── signal_slots.py │ ├── layout │ │ ├── absolute.py │ │ ├── form.py │ │ ├── grid.py │ │ └── horizontal_vertical.py │ ├── menu & toolbar │ │ ├── check_menu.py │ │ ├── main_area.py │ │ ├── right_click_menu.py │ │ ├── simple_menu.py │ │ ├── status_bar.py │ │ ├── submenu.py │ │ └── toolbar.py │ ├── start_up.py │ ├── tooltip_&_logo.py │ └── widget │ │ ├── calendar.py │ │ ├── check_box.py │ │ ├── display_image.py │ │ ├── drop_down_list.py │ │ ├── input_dialog.py │ │ ├── input_edit.py │ │ ├── max.jpg │ │ ├── med.jpg │ │ ├── min.jpg │ │ ├── mute.jpg │ │ ├── progress_bar.py │ │ ├── quit_button_&_message_box.py │ │ ├── slider.py │ │ ├── splitter.py │ │ └── toggle_button.py │ ├── request │ ├── get.py │ ├── hello.txt │ └── response_method.py │ └── selenium │ └── start_up.py ├── Flask-server ├── decorator.py └── hello.py ├── Flight-deals-API ├── data_manager.py ├── flight_data.py ├── flight_search.py ├── main.py └── notification_manager.py ├── Google-sheet-workout-tracker └── main.py ├── Grading-system └── main.py ├── Guessing-Number-Game ├── art.py └── main.py ├── Habit-Tracker-with-Pixela-API └── main.py ├── Hangman-game ├── .upm │ └── store.json ├── __pycache__ │ ├── hangman_art.cpython-38.pyc │ └── hangman_words.cpython-38.pyc ├── hangman_art.py ├── hangman_words.py ├── main.py ├── poetry.lock └── pyproject.toml ├── Higher-lower-game ├── __pycache__ │ ├── art.cpython-310.pyc │ └── game_data.cpython-310.pyc ├── art.py ├── game_data.py └── main.py ├── How-many-days-in-a-month └── main.py ├── International-space-station-location └── main.py ├── Leap-year-generator └── main.py ├── Mail-merge-project ├── .DS_Store ├── Input │ ├── .DS_Store │ ├── Letters │ │ └── starting_letter.txt │ └── Names │ │ └── invited_names.txt ├── Output │ └── ReadyToSend │ │ └── example.txt └── main.py ├── Message-encode-and-decode-generator ├── .upm │ └── store.json ├── __pycache__ │ └── art.cpython-38.pyc ├── art.py ├── main.py ├── poetry.lock └── pyproject.toml ├── Miles-to-Kilometers-GUI-converter └── main.py ├── NATO-alphabet ├── main.py └── nato_phonetic_alphabet.csv ├── OOP-coffee-machine ├── __pycache__ │ ├── coffee_maker.cpython-310.pyc │ ├── menu.cpython-310.pyc │ └── money_machine.cpython-310.pyc ├── coffee_maker.py ├── main.py ├── menu.py └── money_machine.py ├── OOP-exercises ├── OOP-abstraction, polymorphism │ ├── __pycache__ │ │ ├── item.cpython-310.pyc │ │ ├── keyboard.cpython-310.pyc │ │ └── phone.cpython-310.pyc │ ├── abstraction_example.py │ ├── item.py │ ├── keyboard.py │ ├── phone.py │ └── polymophism_example.py ├── OOP-bacis-example │ └── main.py ├── OOP-class attribute vs instance attribute, __dict__ magic method │ └── main.py ├── OOP-construtor, instance, attribute, method, assert │ └── main.py ├── OOP-getter & setter, encapsulation │ ├── __pycache__ │ │ ├── item.cpython-310.pyc │ │ └── phone.cpython-310.pyc │ ├── item.py │ └── main.py ├── OOP-inheritance │ ├── __pycache__ │ │ ├── item.cpython-310.pyc │ │ └── phone.cpython-310.pyc │ ├── item.py │ ├── main.py │ ├── phone.py │ └── test.py ├── OOP-instantiate from CSV, class method, static method │ ├── item.csv │ └── main.py ├── OOP-save instance into class level list, __repr__ magic method │ └── main.py └── OOP-turtle-package │ └── main.py ├── OOP-quiz-game ├── .vscode │ └── settings.json ├── __pycache__ │ ├── data.cpython-310.pyc │ ├── question_model.cpython-310.pyc │ └── quiz_brain.cpython-310.pyc ├── data.py ├── main.py ├── question_model.py └── quiz_brain.py ├── Pandas-exercises ├── Pandas-iterate-over-dataframe.py ├── Pandas-read-column-from-csv │ ├── main.py │ └── weather_data.csv ├── Pandas-read-row, mean, max, write-csv-data │ ├── main.py │ ├── new_data.csv │ └── weather_data.csv └── Pandas-squirrel-dataset │ ├── 2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv │ ├── main.py │ └── squirrel_count.csv ├── Pizza-ordering └── main.py ├── Pomodoro-timer ├── main.py └── tomato.png ├── Pong-game ├── Difference between with inheritance and without inherintance Turtle class.png ├── ball.py ├── main.py ├── paddle.py └── scoreboard.py ├── Popcat-autoclicker └── main.py ├── Prime-number-generator └── main.py ├── Quizzler-API-quiz-app-GUI ├── data.py ├── images │ ├── false.png │ └── true.png ├── main.py ├── question_model.py ├── quiz_brain.py └── ui.py ├── Random-bill-payer └── main.py ├── Random-password-generator ├── .upm │ └── store.json └── main.py ├── Rock-paper-scissors ├── .upm │ └── store.json ├── README.md └── main.py ├── SMS-Weather-API ├── data.json └── main.py ├── Selenium-exercises ├── interaction.py └── search_element.py ├── Simple Calculator ├── __pycache__ │ └── art.cpython-38.pyc ├── art.py └── main.py ├── Sketch-game └── main.py ├── Snake-game-with-higest-score-text-file-record ├── food.py ├── highest_score_database.txt ├── main.py ├── read write file example │ ├── my_text.txt │ └── read_wirte_example.py ├── score_board.py └── snake.py ├── Snake-game ├── __pycache__ │ ├── food.cpython-310.pyc │ ├── score_board.cpython-310.pyc │ ├── screen.cpython-310.pyc │ └── snake.cpython-310.pyc ├── food.py ├── main.py ├── score_board.py └── snake.py ├── TSLA-stock-tracker-API ├── main.py └── three_articles_layout.py ├── Tip-calculator ├── .upm │ └── store.json ├── README.md └── main.py ├── Tkinter-exercises, unlimited arg, kwarg ├── label,button,entry,layout.py ├── optional-arguments │ ├── optinal_args_and_kwargs_playground.py │ ├── optional_args.py │ └── optional_kwargs.py └── text,spinkbox,scale,checkbox,radio button, listbox.py ├── Treasure-island-game ├── .upm │ └── store.json ├── README.md └── main.py ├── Turtle-crossing-road-game ├── car_manager.py ├── main.py ├── player.py └── scoreboard.py ├── Turtle-run-race-game └── main.py ├── US-state-quiz-game ├── 50_states.csv ├── States_that_not_guessed_correct.csv ├── blank_states_img.gif └── main.py └── Website-image-downloader-example ├── link.txt └── main.py /.gitignore: -------------------------------------------------------------------------------- 1 | .history/ 2 | .vscode/ 3 | __pycache__/ -------------------------------------------------------------------------------- /API-quote-GUI-app/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/API-quote-GUI-app/background.png -------------------------------------------------------------------------------- /API-quote-GUI-app/main.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import requests 3 | from random import choice 4 | 5 | 6 | def get_quote(): 7 | url = "https://type.fit/api/quotes" 8 | 9 | response = requests.get(url) # get the object from endpoint 10 | response.raise_for_status() # raise an error if failed to fetch data from API 11 | quote_dict = response.json() # get the json into a dictionary in a list 12 | random_quote = choice(quote_dict) # pick randomly a quote from the list 13 | canvas.itemconfig(quote_text, text=random_quote["text"]) # only get the text 14 | print(random_quote["text"]) 15 | 16 | 17 | 18 | window = Tk() 19 | window.title("Keep Motivating!") 20 | window.config(padx=50, pady=50) 21 | 22 | canvas = Canvas(width=300, height=414) 23 | background_img = PhotoImage(file="background.png") 24 | canvas.create_image(150, 207, image=background_img) 25 | quote_text = canvas.create_text(150, 207, text="", width=250, font=("Arial", 20, "bold"), fill="white") 26 | canvas.grid(row=0, column=0) 27 | 28 | next_image = PhotoImage(file="./next.png", width=30, height=30) 29 | next_button = Button(image=next_image, highlightthickness=0, command=get_quote) 30 | next_button.grid(row=1, column=0) 31 | 32 | 33 | 34 | window.mainloop() 35 | -------------------------------------------------------------------------------- /API-quote-GUI-app/next.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/API-quote-GUI-app/next.png -------------------------------------------------------------------------------- /Amazon-price-tracker/main.py: -------------------------------------------------------------------------------- 1 | import lxml 2 | import requests 3 | from bs4 import BeautifulSoup 4 | import telegram_send 5 | 6 | AMAZON_PRODUCT_URL = "https://www.amazon.com/OnePlus-10-Pro-Factory-Unlocked/dp/B09SKXXC87/ref=sr_1_1?keywords=oneplus+1&qid=1661664128&sprefix=oneplus+1-,aps,497&sr=8-1&language=en_US¤cy=MYR" 7 | 8 | headers = { 9 | "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0", 10 | "Accept-Language" : "en-US,en;q=0.5", 11 | } 12 | 13 | amazon_product_response = requests.post(url=AMAZON_PRODUCT_URL, headers=headers) 14 | amazon_product_response.raise_for_status() 15 | amazon_product_soup = BeautifulSoup(amazon_product_response.text, "lxml") 16 | 17 | product_price_whole_number = amazon_product_soup.find(name="span", class_="a-price-whole").getText().split(".")[0] 18 | product_price_decimal = amazon_product_soup.find(name="span", class_="a-price-fraction").getText() 19 | product_price = product_price_whole_number + "." + product_price_decimal 20 | print(float(product_price)) 21 | 22 | if float(product_price) < 850: 23 | telegram_send.send(messages=[f"Oneplus 10 pro is now on promotion! Hurry up! Access this link:\n{AMAZON_PRODUCT_URL}"]) -------------------------------------------------------------------------------- /Automated-birthday-wishes-via-email/birthdays.csv: -------------------------------------------------------------------------------- 1 | name,email,year,month,day 2 | Peter,peter@gmail.com,1997,4,5 3 | David,david@gmail.com,1990,11,30 4 | Simon,simon@gmail.com,1998,8,8 5 | Janet,janet@gmail.com,1998,12,15 -------------------------------------------------------------------------------- /Automated-birthday-wishes-via-email/letter_templates/letter_1.txt: -------------------------------------------------------------------------------- 1 | Dear [NAME], 2 | 3 | Happy birthday! 4 | 5 | All the best for the year! 6 | 7 | Simon -------------------------------------------------------------------------------- /Automated-birthday-wishes-via-email/letter_templates/letter_2.txt: -------------------------------------------------------------------------------- 1 | Hey [NAME], 2 | 3 | Happy birthday! Have a wonderful time today and eat lots of cake! 4 | 5 | Lots of love, 6 | 7 | Simon -------------------------------------------------------------------------------- /Automated-birthday-wishes-via-email/letter_templates/letter_3.txt: -------------------------------------------------------------------------------- 1 | Dear [NAME], 2 | 3 | It's your birthday! Have a great day! 4 | 5 | All my love, 6 | 7 | Simon -------------------------------------------------------------------------------- /Automated-send-motivation_quote_via_email/send_email_and_datetime_basic.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | import datetime as dt 3 | 4 | #* ------------------------------------------------- SEND EMAIL ------------------------------------------------- 5 | 6 | my_email = "your_email_here" 7 | my_password = "your_password_here" # this password is only for gaining access to the Google account 8 | recipient_email = "recipient_email_here" 9 | 10 | 11 | try: 12 | with smtplib.SMTP("smtp.gmail.com") as connection: # call the smtplib class, connect to Gmail SMTP server 13 | # Hotmail -> smtp.live.com 14 | # Yahoo -> smtp.mail.yahoo.com 15 | 16 | connection.starttls() # start TLS -> Transport Layer Security, securely connect to email server (encryption) 17 | connection.login(user=my_email, password=my_password) # login to your account 18 | connection.sendmail(from_addr=my_email, 19 | to_addrs=recipient_email, 20 | msg="Subject: Hello Simon\n\nThis is the content of email") 21 | except: 22 | print("Email sending failed") 23 | else: 24 | print("Email has been sent successfully") 25 | 26 | 27 | #! if you encountered this error, like so 28 | # raise SMTPAuthenticationError(code, resp) 29 | # smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials n14-20020a170902d2ce00b0016cbb46806asm6513208plc.278 - gsmtp') 30 | 31 | # you need go to your email setting 32 | #* turn off these settings: 33 | # --- Use your phone to sign in 34 | # --- 2-Step Verification 35 | 36 | #* and you need to have 2-step verification setting then get the app password 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | #* ------------------------------------------------- PRACTICING DATETIME MODULE ------------------------------------------------- 45 | 46 | now = dt.datetime.now() # get the current datetime 47 | 48 | print(now) 49 | # 2022-08-07 21:31:53.760751 50 | 51 | print(now.year) # integer type today is year 2022 52 | # 2022 53 | 54 | print(now.month) # integer type today is August 55 | # 8 56 | 57 | print(now.day) # integer type, today is 7th 58 | # 7 59 | 60 | print(now.date()) # integer type, today is 7th 61 | # 2022-08-07 62 | 63 | print(now.time()) 64 | # 21:44:10.336723 65 | 66 | print(now.weekday()) # return the current day in integer, Monday - Sunday (0 - 6), 7 days, start from 0 67 | # 6 # this means today is Sunday -------------------------------------------------------------------------------- /Automated-send-motivation_quote_via_email/send_quote_weekly.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | import datetime as dt 3 | from random import choice 4 | 5 | #* ------------------------------------------------- SEND A RANDOM MOTIVATION QUOTE EVERY SUNDAY ------------------------------------------------- 6 | 7 | my_email = "your_email_here" 8 | my_password = "your_password_here" # this password is only for gaining access to the Google account 9 | recipient_email = "recipient_email_here" 10 | 11 | 12 | # check today's day 13 | now = dt.datetime.now() # get the current datetime 14 | current_day = now.weekday() 15 | 16 | if current_day == 6: # if today is Sunday(6) 17 | with open("./quotes.txt") as quotes_file: # open the file in read mode 18 | quote = quotes_file.readlines() # read all lines in the file and save as a list 19 | 20 | random_quote = choice(quote) # randomly choose a quote from the quote list, if choices(), this will return a list instead of an item 21 | print(random_quote) 22 | 23 | 24 | try: # check if the email send out successfully without any errors 25 | with smtplib.SMTP("smtp.gmail.com") as connection: # call the smtplib class, connect to Gmail SMTP server 26 | # Hotmail -> smtp.live.com 27 | # Yahoo -> smtp.mail.yahoo.com 28 | 29 | connection.starttls() # start TLS -> Transport Layer Security, securely connect to email server (encryption) 30 | connection.login(user=my_email, password=my_password) # login to your account 31 | connection.sendmail(from_addr=my_email, 32 | to_addrs=recipient_email, 33 | msg=f"Subject: Be Motivated!\n\n{random_quote}") # send the email, space 2 lines after for a content writing 34 | except: 35 | print("Email sending failed") 36 | else: 37 | print(f"Email has been sent to {recipient_email} successfully") -------------------------------------------------------------------------------- /Beautiful-soup-Hacker-News-Website/main.py: -------------------------------------------------------------------------------- 1 | # this is a program to grab the article with highest vote from https://news.ycombinator.com/ by using Beautiful Soup 2 | 3 | import requests 4 | from bs4 import BeautifulSoup 5 | 6 | response = requests.get("https://news.ycombinator.com/") # grab the web page source from the website 7 | webpage_source = response.text # convert the object into string form 8 | # print(type(webpage_source)) 9 | # 10 | 11 | soup = BeautifulSoup(webpage_source, "html.parser") # convert the object into BeautifulSoup object 12 | # print(type(soup)) 13 | # 14 | 15 | article_tag = soup.find_all(name="a", class_="titlelink") # get all the element with tag and "titlelink" class 16 | 17 | # get_text() OR getText() 18 | article_titles = [article.get_text() for article in article_tag] # get the title of all articles and store into a list 19 | article_links = [article.get("href") for article in article_tag] # get tge link of all articles abd store into a list 20 | article_upvote_nums = [int(score.getText().split()[0]) for score in soup.find_all("span", "score")] # find the upvote number of each article 21 | 22 | 23 | 24 | print(article_titles) 25 | print(article_links) 26 | print(article_upvote_nums) 27 | 28 | # print(type(article_upvote_nums)) 29 | # 30 | 31 | highest_vote = max(article_upvote_nums) # find the highest vote 32 | highest_vote_index = article_upvote_nums.index(highest_vote) # find the index of highest vote among all articles from a list 33 | 34 | # print all info of the highest vote article 35 | print("-" * 150) 36 | print(article_titles[highest_vote_index]) 37 | print(article_links[highest_vote_index]) 38 | print(article_upvote_nums[highest_vote_index]) 39 | 40 | 41 | 42 | # ------------------------------------------------------- NOTE ----------------------------------------------------------------------- 43 | 44 | print(article_upvote_nums[0]) 45 | # 387 points 46 | 47 | # to extract the number out of the string, there are 2 ways to achieve 48 | 49 | # 1.replace " points" to a empty string 50 | # replace(" points", "") 51 | # 387 52 | 53 | # 2.split the string by space and only retrieve the first element 54 | # article_upvote_nums[0].split()[0] 55 | # 387 56 | -------------------------------------------------------------------------------- /Beautiful-soup-Spotify-playlist/token.txt: -------------------------------------------------------------------------------- 1 | # this is just an example, you will get this once you execute the program 2 | 3 | { 4 | "access_token": "BQB7dfgbm63hyXoK5VKOnghjvTJLPCyjcmyFrC2OcqYMxtwHxeBk9f3Q8bJ70fr6gAEUBhRKC1PoyECn1HJOGZFHuyk74vNzq2gLT9vRwdDXDI4x7Kt4Q2P_lFcH6NvjKpWtzsOffdxDXN0lepU74MHKfrmWPYkvXw8_fioQRZx7IObov31GHK2D8kptPFi13v5wubIB7j2M8YwlsNMo4v7N-ws52DhWq67FTfovqGGA", 5 | "token_type": "Bearer", 6 | "expires_in": 3600, 7 | "refresh_token": "AQA9qpmX8d46hH53ghjghjeZazIUKINtD-a_jF91EAzgSyWsZqP-aWvWHCM4fi31kZ3e86kbUcR9HXY0YeHL1BAELbBIdvsS4DalUGx93ubyTuQt87y-qjZxLJcO_calVWgQZfICM", 8 | "scope": "playlist-modify-private", 9 | "expires_at": 1661590342 10 | } -------------------------------------------------------------------------------- /Beautiful-soup-exercises/website.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Simon's Personal Site 7 | 8 | 9 | 10 |

Hello World

11 |

Simon Chong

12 |

Founder of The App Brewery.

13 |

I am an iOS and Web Developer. I ❤️ coffee and motorcycles.

14 |
15 |

Books and Teaching

16 | 21 |
22 |

Other Pages

23 | My Hobbies 24 | Contact Me 25 | 26 | 27 | -------------------------------------------------------------------------------- /Beautiful-soup-top-100-movies-website/main.py: -------------------------------------------------------------------------------- 1 | # this program is to get the top 100 must watch movies and save into a txt file 2 | # website -> https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/ 3 | 4 | import requests 5 | from bs4 import BeautifulSoup 6 | 7 | URL = "https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/" 8 | response = requests.get(URL) # get all the website page source 9 | soup = BeautifulSoup(response.text, "html.parser") # parse the data from a string form into a html object form 10 | 11 | movie_titles = soup.find_all(name="h3", class_="title") # get all movie titles with

tag and "title" class and save into a list 12 | 13 | with open("must_watch_movies.txt", "w", encoding="utf8") as movie_file: # create a text file, define the encoding format here 14 | for movie in movie_titles[::-1]: # reverse the movie list because it was number 100 to 1 descending order, we need 1 to 100 ascending order 15 | movie_file.write(f"{movie.getText()}\n") # write the title into a txt file -------------------------------------------------------------------------------- /Beautiful-soup-top-100-movies-website/must_watch_movies.txt: -------------------------------------------------------------------------------- 1 | 1) The Godfather 2 | 2) The Empire Strikes Back 3 | 3) The Dark Knight 4 | 4) The Shawshank Redemption 5 | 5) Pulp Fiction 6 | 6) Goodfellas 7 | 7) Raiders Of The Lost Ark 8 | 8) Jaws 9 | 9) Star Wars 10 | 10) The Lord Of The Rings: The Fellowship Of The Ring 11 | 11) Back To The Future 12 | 12: The Godfather Part II 13 | 13) Blade Runner 14 | 14) Alien 15 | 15) Aliens 16 | 16) The Lord Of The Rings: The Return Of The King 17 | 17) Fight Club 18 | 18) Inception 19 | 19) Jurassic Park 20 | 20) Die Hard 21 | 21) 2001: A Space Odyssey 22 | 22) Apocalypse Now 23 | 23) The Lord Of The Rings: The Two Towers 24 | 24) The Matrix 25 | 25) Terminator 2: Judgment Day 26 | 26) Heat 27 | 27) The Good, The Bad And The Ugly 28 | 28) Casablanca 29 | 29) The Big Lebowski 30 | 30) Seven 31 | 31) Taxi Driver 32 | 32) The Usual Suspects 33 | 33) Schindler's List 34 | 34) Guardians Of The Galaxy 35 | 35) The Shining 36 | 36) The Departed 37 | 37) The Thing 38 | 38) Mad Max: Fury Road 39 | 39) Saving Private Ryan 40 | 40) 12 Angry Men 41 | 41) Eternal Sunshine Of The Spotless Mind 42 | 42) There Will Be Blood 43 | 43) One Flew Over The Cuckoo's Nest 44 | 44) Gladiator 45 | 45) Drive 46 | 46) Citizen Kane 47 | 47) Interstellar 48 | 48) The Silence Of The Lambs 49 | 49) Trainspotting 50 | 50) Lawrence Of Arabia 51 | 51) It's A Wonderful Life 52 | 52) Once Upon A Time In The West 53 | 53) Psycho 54 | 54) Vertigo 55 | 55) Pan's Labyrinth 56 | 56) Reservoir Dogs 57 | 57) Whiplash 58 | 58) Inglourious Basterds 59 | 59) E.T. – The Extra Terrestrial 60 | 60) American Beauty 61 | 61) Forrest Gump 62 | 62) La La Land 63 | 63) Donnie Darko 64 | 64) L.A. Confidential 65 | 65) Avengers Assemble 66 | 66) Return Of The Jedi 67 | 67) Memento 68 | 68) Ghostbusters 69 | 69) Singin' In The Rain 70 | 70) The Lion King 71 | 71) Hot Fuzz 72 | 72) Rear Window 73 | 73) Seven Samurai 74 | 74) Mulholland Dr. 75 | 75) Fargo 76 | 76) A Clockwork Orange 77 | 77) Toy Story 78 | 78) Oldboy 79 | 79) Captain America: Civil War 80 | 15) Spirited Away 81 | 81) The Social Network 82 | 82) Some Like It Hot 83 | 83) True Romance 84 | 84) Rocky 85 | 85) Léon 86 | 86) Indiana Jones And The Last Crusade 87 | 87) Predator 88 | 88) The Exorcist 89 | 89) Shaun Of The Dead 90 | 90) No Country For Old Men 91 | 91) The Prestige 92 | 92) The Terminator 93 | 93) The Princess Bride 94 | 94) Lost In Translation 95 | 95) Arrival 96 | 96) Good Will Hunting 97 | 97) Titanic 98 | 98) Amelie 99 | 99) Raging Bull 100 | 100) Stand By Me 101 | -------------------------------------------------------------------------------- /Bidder-and-winner/.upm/store.json: -------------------------------------------------------------------------------- 1 | {"version":2,"languages":{"python-python3-poetry":{"specfileHash":"0cf8a58a652f21c221e2ae9bf2acf601","lockfileHash":"6c5001376a7f255d5962972a1a4efc40","guessedImports":["replit"],"guessedImportsHash":"2f1d64f65aaeefd4f2a4b8cf6714035c"}}} 2 | -------------------------------------------------------------------------------- /Bidder-and-winner/__pycache__/art.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Bidder-and-winner/__pycache__/art.cpython-38.pyc -------------------------------------------------------------------------------- /Bidder-and-winner/art.py: -------------------------------------------------------------------------------- 1 | logo = ''' 2 | ___________ 3 | \ / 4 | )_______( 5 | |"""""""|_.-._,.---------.,_.-._ 6 | | | | | | | ''-. 7 | | |_| |_ _| |_..-' 8 | |_______| '-' `'---------'` '-' 9 | )"""""""( 10 | /_________\\ 11 | .-------------. 12 | /_______________\\ 13 | ''' -------------------------------------------------------------------------------- /Bidder-and-winner/main.py: -------------------------------------------------------------------------------- 1 | from replit import clear 2 | from art import logo 3 | #HINT: You can call clear() to clear the output in the console. 4 | 5 | print(logo) 6 | 7 | more_bidders = True 8 | 9 | bidders = {} 10 | highest_price = 0 11 | 12 | while more_bidders == True: 13 | 14 | name = input("What is your name?: ") 15 | bid_amount = int(input("What's your bid? $")) 16 | 17 | bidders[name] = bid_amount 18 | 19 | if bid_amount > highest_price: 20 | highest_price = bid_amount 21 | 22 | anymore_bidders = input("Are there any other bidders? Type 'yes' or 'no'. ").lower() 23 | 24 | if anymore_bidders == 'no': 25 | more_bidders = False 26 | else: 27 | clear() 28 | 29 | for key in bidders: 30 | if bidders[key] == highest_price: 31 | print(f"The winner is {key} with bid of ${highest_price}") 32 | 33 | # winner_name = bidders[] 34 | # winner_price = -------------------------------------------------------------------------------- /Bidder-and-winner/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "repl_python3_blind-auction-start" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Your Name "] 6 | 7 | [tool.poetry.dependencies] 8 | python = "^3.8" 9 | replit = "^3.2.4" 10 | 11 | [tool.poetry.dev-dependencies] 12 | 13 | [build-system] 14 | requires = ["poetry-core>=1.0.0"] 15 | build-backend = "poetry.core.masonry.api" 16 | -------------------------------------------------------------------------------- /Blackjack/Blackjack_Flowchart.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Blackjack/Blackjack_Flowchart.pdf -------------------------------------------------------------------------------- /Blackjack/art.py: -------------------------------------------------------------------------------- 1 | logo = """ 2 | .------. _ _ _ _ _ 3 | |A_ _ |. | | | | | | (_) | | 4 | |( \/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __ 5 | | \ /|K /\ | | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ / 6 | | \/ | / \ | | |_) | | (_| | (__| <| | (_| | (__| < 7 | `-----| \ / | |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\ 8 | | \/ K| _/ | 9 | `------' |__/ 10 | """ -------------------------------------------------------------------------------- /Coffee-machine/Coffee-Machine-Program-Requirements.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Coffee-machine/Coffee-Machine-Program-Requirements.pdf -------------------------------------------------------------------------------- /Coffee-machine/__pycache__/menu.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Coffee-machine/__pycache__/menu.cpython-310.pyc -------------------------------------------------------------------------------- /Coffee-machine/main.py: -------------------------------------------------------------------------------- 1 | from menu import MENU, resources 2 | 3 | def is_resources_sufficient(order_ingredients): 4 | '''Return true is the resource is sufficient''' 5 | for item in order_ingredients: 6 | if order_ingredients[item] >= resources[item]: 7 | print(f"Sorry there is not enough {item}.") 8 | return False 9 | return True 10 | 11 | def process_coin(): 12 | '''Return the total coins from user input''' 13 | print("Please insert coin.") 14 | total = int(input("how many quarters: ")) * 0.25 15 | total += int(input("how many dimes: ")) * 0.10 16 | total += int(input("how many nickles: ")) * 0.05 17 | total += int(input("how many pennies: ")) * 0.01 18 | return total 19 | 20 | def is_transaction_successful(money_received, drink_cost): 21 | '''Return True when payment is accepted else return False''' 22 | if money_received >= drink_cost: 23 | change = round(money_received - drink_cost, 2) 24 | print(f"Here is ${change} in change.") 25 | global money_in_machine 26 | money_in_machine += drink_cost 27 | return True 28 | else: 29 | print("Sorry that's not enough money. Money has been refunded.") 30 | return False 31 | 32 | def make_coffee(drink_name, order_ingredients): 33 | '''Deduct the required ingredients from the resources.''' 34 | for item in order_ingredients: 35 | resources[item] -= order_ingredients[item] 36 | print(f"Here is your {drink_name} ☕") 37 | 38 | money_in_machine = 0 39 | is_machine_on = True 40 | 41 | while is_machine_on: 42 | choice = input("What would you like? (espresso/latte/cappuccino): ") 43 | if choice == "off": 44 | is_machine_on = False 45 | elif choice == "report": 46 | print(f"Water: {resources['water']}ml") 47 | print(f"Milk: {resources['milk']}ml") 48 | print(f"Coffee: {resources['coffee']}g") 49 | print(f"Money: ${money_in_machine}") 50 | else: 51 | drink = MENU[choice] 52 | if is_resources_sufficient(drink["ingredients"]): 53 | payment = process_coin() 54 | if is_transaction_successful(payment, drink["cost"]): 55 | make_coffee(choice, drink["ingredients"]) -------------------------------------------------------------------------------- /Coffee-machine/menu.py: -------------------------------------------------------------------------------- 1 | MENU = { 2 | "espresso": { 3 | "ingredients": { 4 | "water": 50, 5 | "coffee": 18, 6 | }, 7 | "cost": 1.5, 8 | }, 9 | "latte": { 10 | "ingredients": { 11 | "water": 200, 12 | "milk": 150, 13 | "coffee": 24, 14 | }, 15 | "cost": 2.5, 16 | }, 17 | "cappuccino": { 18 | "ingredients": { 19 | "water": 250, 20 | "milk": 100, 21 | "coffee": 24, 22 | }, 23 | "cost": 3.0, 24 | } 25 | } 26 | 27 | resources = { 28 | "water": 300, 29 | "milk": 200, 30 | "coffee": 100, 31 | } -------------------------------------------------------------------------------- /Color-art-turtle-module/generate a Spirograph, circle loop.py: -------------------------------------------------------------------------------- 1 | # generate a Spirograph, circle loop 2 | 3 | from turtle import Shape, Turtle, Screen 4 | from turtle import * 5 | from random import randint, choice 6 | 7 | turtle = Turtle() 8 | screen = Screen() 9 | 10 | def random_color(): 11 | r = randint(0, 255) 12 | g = randint(0, 255) 13 | b = randint(0, 255) 14 | return (r, g, b) # return a tuple 15 | 16 | turtle.shape("arrow") 17 | turtle.color("pink") 18 | # turtle.width(6) 19 | turtle.speed(0) # 1(slow) ... 10(fast), 0 is fastest 20 | screen.colormode(255) 21 | 22 | 23 | 24 | def draw_spirograph(angle_of_rotation): 25 | for _ in range(round(360/angle_of_rotation)): 26 | turtle.color(random_color()) 27 | turtle.circle(200) 28 | turtle.right(angle_of_rotation) 29 | print(_) 30 | 31 | draw_spirograph(5) 32 | 33 | 34 | turtle.hideturtle() # to hide the pen shape 35 | 36 | 37 | done() # keep the screen after the process is finish -------------------------------------------------------------------------------- /Color-art-turtle-module/generate a random wander turtle.py: -------------------------------------------------------------------------------- 1 | # generate a random wander turtle 2 | 3 | from turtle import Shape, Turtle, Screen 4 | from turtle import * 5 | from random import randint, choice 6 | 7 | turtle = Turtle() 8 | screen = Screen() 9 | 10 | def random_color(): 11 | r = randint(0, 255) 12 | g = randint(0, 255) 13 | b = randint(0, 255) 14 | return (r, g, b) # return a tuple 15 | 16 | turtle.shape("arrow") 17 | turtle.color("pink") 18 | turtle.width(6) 19 | turtle.speed(0) # 1(slow) ... 10(fast), 0 is fastest 20 | screen.colormode(255) 21 | 22 | # turtle.hideturtle() # to hide the pen shape 23 | 24 | directions = [0, 90, 180, 270] 25 | 26 | for _ in range(10000): 27 | turtle.color(random_color()) 28 | 29 | turtle.setheading(choice(directions)) # setheading() rotate in 0, 90, 180, 270 angle 30 | turtle.forward(30) 31 | print(_) 32 | 33 | 34 | 35 | done() # keep the screen after the process is finish -------------------------------------------------------------------------------- /Color-art-turtle-module/print a n-number of sides of polygon.py: -------------------------------------------------------------------------------- 1 | # print a n-number of sides of polygon 2 | 3 | from turtle import Shape, Turtle, Screen 4 | from turtle import * 5 | from random import randint 6 | 7 | turtle = Turtle() 8 | screen = Screen() 9 | 10 | turtle.shape("circle") 11 | turtle.color("pink") 12 | screen.colormode(255) 13 | 14 | # draw a square 15 | 16 | # for _ in range(4): 17 | # turtle.forward(100) 18 | # turtle.right(90) 19 | 20 | # # draw a dashed line 21 | # for _ in range(15): 22 | # turtle.forward(10) 23 | # turtle.penup() # draw nothing 24 | # turtle.forward(10) 25 | # turtle.pendown() # draw 26 | 27 | def draw_shape(num_sides): 28 | angle = 360 / num_sides 29 | for _ in range(num_sides): 30 | turtle.forward(20) 31 | turtle.right(angle) 32 | 33 | 34 | # turtle.hideturtle() # to hide the pen shape 35 | turtle.speed(0) 36 | turtle.penup() 37 | turtle.left(90) 38 | turtle.forward(450) 39 | turtle.left(90) 40 | turtle.forward(10) 41 | turtle.right(90) 42 | turtle.right(90) 43 | turtle.pendown() 44 | 45 | for num_sides in range(3, 1000): # 3 to 100 number of side 46 | r = randint(0, 255) 47 | g = randint(0, 255) 48 | b = randint(0, 255) 49 | turtle.color(r, g, b) 50 | draw_shape(num_sides) 51 | print(num_sides) 52 | 53 | turtle.done() -------------------------------------------------------------------------------- /Comprehension-exercises/Dictionary-comprehension/Celsius _to_Fahrenheit.py: -------------------------------------------------------------------------------- 1 | weather_c = { 2 | "Monday": 12, 3 | "Tuesday": 14, 4 | "Wednesday": 15, 5 | "Thursday": 14, 6 | "Friday": 21, 7 | "Saturday": 22, 8 | "Sunday": 24, 9 | } 10 | # 🚨 Don't change code above 👆 11 | 12 | 13 | # Write your code 👇 below: 14 | 15 | weather_f = {day:((celsius * 9 / 5) + 32) for day, celsius in weather_c.items()} 16 | 17 | print(weather_f) 18 | -------------------------------------------------------------------------------- /Comprehension-exercises/Dictionary-comprehension/basic.py: -------------------------------------------------------------------------------- 1 | # general code 2 | # `new_dict` = {`new_key`:`new_value` for `key`, `value` in `dict`.items() if `condition/test`} 3 | 4 | from random import randint 5 | 6 | #* ------------------------------------------------ using ordinary dictionary approach ------------------------------------ 7 | # the score is randomly set 8 | student_scores = { 9 | "Alex" : randint(0, 100), 10 | "Beth" : randint(0, 100), 11 | "Caroline" : randint(0, 100), 12 | "Dave" : randint(0, 100), 13 | "Eleanor" : randint(0, 100), 14 | "Freddie" : randint(0, 100), 15 | } 16 | 17 | #* ------------------------------------------------ using dictionary comprehension approach ------------------------------------ 18 | 19 | student_list = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"] 20 | student_scores2 = {student_name:randint(0, 100) for student_name in student_list} 21 | 22 | # add the student_scores dictionary into a new_dictionary 23 | student_scores3 = {student_name:score for student_name, score in student_scores.items()} 24 | 25 | # add condition, check who passed the exam 26 | passed_student = {student_name:score for (student_name, score) in student_scores2.items() if student_scores2[student_name] > 60} -------------------------------------------------------------------------------- /Comprehension-exercises/Dictionary-comprehension/split_string_into_list.py: -------------------------------------------------------------------------------- 1 | sentence = "What is the Airspeed Velocity of an Unladen Swallow?" 2 | # Don't change code above 👆 3 | 4 | # Write your code below: 5 | 6 | 7 | result = {word:len(word) for word in sentence.split()} 8 | 9 | 10 | print(result) -------------------------------------------------------------------------------- /Comprehension-exercises/List-comprehension/basic.py: -------------------------------------------------------------------------------- 1 | # general code 2 | # `new_list` = [`new_item` for `item` in `list` if `condition/test`] 3 | 4 | # python sequences (has a specific order): 5 | # list 6 | # string 7 | # range 8 | # tuple 9 | 10 | 11 | #* -------------------------------------- list ------------------------------------ 12 | # write a single line code to save a list into another list 13 | 14 | number_list = [1, 2, 3] 15 | 16 | # using for loop to iterate 17 | new_list = [] 18 | for number in number_list: 19 | add_1 = number + 1 20 | new_list.append(add_1) 21 | 22 | 23 | # using list comprehension to iterate 24 | new_list2 = [number + 1 for number in number_list] 25 | 26 | print(new_list) 27 | print(new_list2) 28 | 29 | 30 | #? list comprehension with condition/validation 31 | name_list = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"] 32 | 33 | short_name = [name for name in name_list if len(name) <= 4] 34 | upper_case_name = [name.upper() for name in name_list if len(name) > 5] 35 | 36 | 37 | 38 | 39 | 40 | #* -------------------------------------- string ------------------------------------ 41 | # this can be used in string as well 42 | 43 | name = "Simon" 44 | letter_list = [letter for letter in name] 45 | 46 | print(letter_list) 47 | 48 | 49 | 50 | #* -------------------------------------- range ------------------------------------ 51 | # this can be used in range as well 52 | 53 | number_range = [number * 2 for number in range(1,5)] -------------------------------------------------------------------------------- /Comprehension-exercises/List-comprehension/filtering_even number.py: -------------------------------------------------------------------------------- 1 | numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 2 | # 🚨 Do Not Change the code above 3 | 4 | #Write your 1 line code 👇 below: 5 | 6 | result = [number for number in numbers if number % 2 == 0] 7 | 8 | #Write your code 👆 above: 9 | 10 | print(result) 11 | 12 | -------------------------------------------------------------------------------- /Comprehension-exercises/List-comprehension/find_same_number_in_both_files/file1.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 6 3 | 5 4 | 8 5 | 33 6 | 12 7 | 7 8 | 4 9 | 72 10 | 2 11 | 42 12 | 13 13 | -------------------------------------------------------------------------------- /Comprehension-exercises/List-comprehension/find_same_number_in_both_files/file2.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 6 3 | 13 4 | 5 5 | 7 6 | 89 7 | 12 8 | 3 9 | 33 10 | 34 11 | 1 12 | 344 13 | 42 14 | -------------------------------------------------------------------------------- /Comprehension-exercises/List-comprehension/find_same_number_in_both_files/main.py: -------------------------------------------------------------------------------- 1 | 2 | # Write your code above 👆 3 | 4 | with open("./file1.txt") as file1: 5 | file1_number_list = file1.readlines() 6 | 7 | with open("./file2.txt") as file2: 8 | file2_number_list = file2.readlines() 9 | 10 | result = [int(number) for number in file1_number_list if number in file2_number_list] 11 | 12 | print(result) -------------------------------------------------------------------------------- /Comprehension-exercises/List-comprehension/squaring_number.py: -------------------------------------------------------------------------------- 1 | numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 2 | # 🚨 Do Not Change the code above 👆 3 | 4 | #Write your 1 line code 👇 below: 5 | 6 | squared_numbers = [number * number for number in numbers] 7 | # or 8 | squared_numbers2 = [number ** 2 for number in numbers] 9 | # or 10 | squared_numbers3 = [pow(number, 2) for number in numbers] 11 | 12 | #Write your code 👆 above: 13 | 14 | print(squared_numbers) -------------------------------------------------------------------------------- /Exception-handling-exercises/NATO_Phonetic.py: -------------------------------------------------------------------------------- 1 | # reference: Pandas-exercises\Pandas-iterate-over-dataframe.py 2 | 3 | import pandas as pd 4 | 5 | {"A": "Alfa", "B": "Bravo"} 6 | 7 | data = pd.read_csv("./nato_phonetic_alphabet.csv") 8 | 9 | alpha_dict = {row.letter : row.code for index, row in data.iterrows()} 10 | 11 | def user_input(): 12 | user_word = input("Input a word: ").upper() 13 | return user_word 14 | 15 | while True: 16 | try: 17 | result = [alpha_dict[letter] for letter in user_input()] 18 | except KeyError: 19 | print("Sorry, please insert alphabet only") 20 | user_input() 21 | else: 22 | print(result) 23 | break 24 | 25 | 26 | -------------------------------------------------------------------------------- /Exception-handling-exercises/index_error.py: -------------------------------------------------------------------------------- 1 | fruits = ["Apple", "Pear", "Orange"] 2 | 3 | #TODO: Catch the exception and make sure the code runs without crashing. 4 | def make_pie(index): 5 | try: 6 | fruit = fruits[index] 7 | except IndexError: 8 | print("Fruit pie") 9 | else: 10 | print(fruit + " pie") 11 | 12 | make_pie(2) 13 | -------------------------------------------------------------------------------- /Exception-handling-exercises/key_error.py: -------------------------------------------------------------------------------- 1 | facebook_posts = [ 2 | {'Likes': 21, 'Comments': 2}, 3 | {'Likes': 13, 'Comments': 2, 'Shares': 1}, 4 | {'Likes': 33, 'Comments': 8, 'Shares': 3}, 5 | {'Comments': 4, 'Shares': 2}, 6 | {'Comments': 1, 'Shares': 1}, 7 | {'Likes': 19, 'Comments': 3} 8 | ] 9 | 10 | total_likes = 0 11 | 12 | 13 | for post in facebook_posts: 14 | try: 15 | total_likes = total_likes + post['Likes'] 16 | except KeyError: 17 | pass 18 | 19 | 20 | print(total_likes) -------------------------------------------------------------------------------- /Exception-handling-exercises/nato_phonetic_alphabet.csv: -------------------------------------------------------------------------------- 1 | letter,code 2 | A,Alfa 3 | B,Bravo 4 | C,Charlie 5 | D,Delta 6 | E,Echo 7 | F,Foxtrot 8 | G,Golf 9 | H,Hotel 10 | I,India 11 | J,Juliet 12 | K,Kilo 13 | L,Lima 14 | M,Mike 15 | N,November 16 | O,Oscar 17 | P,Papa 18 | Q,Quebec 19 | R,Romeo 20 | S,Sierra 21 | T,Tango 22 | U,Uniform 23 | V,Victor 24 | W,Whiskey 25 | X,X-ray 26 | Y,Yankee 27 | Z,Zulu -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/__main__/main.py: -------------------------------------------------------------------------------- 1 | # reference: https://www.pythontutorial.net/python-basics/python-__name__/ 2 | 3 | import module1 4 | 5 | print(__name__) 6 | 7 | # module1 8 | # __main__ -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/__main__/module1.py: -------------------------------------------------------------------------------- 1 | def calculate_tax(price, tax): 2 | return price * tax 3 | 4 | def print_billing_doc(): 5 | tax_rate = 0.1 6 | products = [{'name': 'Book', 'price': 30}, 7 | {'name': 'Pen', 'price': 5}] 8 | 9 | # print billing header 10 | print(f'Name\tPrice\tTax') 11 | 12 | # print the billing item 13 | for product in products: 14 | tax = calculate_tax(product['price'], tax_rate) 15 | print(f"{product['name']}\t{product['price']}\t{tax}") 16 | 17 | def print_hello_world(): 18 | print("Hello World") 19 | 20 | if __name__ == "__main__": 21 | print(__name__) 22 | print_billing_doc() 23 | else: 24 | print_hello_world() -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/enumerate/main.py: -------------------------------------------------------------------------------- 1 | # reference: https://www.programiz.com/python-programming/methods/built-in/enumerate 2 | # reference: https://www.pythontutorial.net/python-built-in-functions/python-enumerate/ 3 | 4 | # enumerate when you wanna count the indices of the iterable item without defining the index counter 5 | 6 | grocery = ['bread', 'milk', 'butter'] 7 | enumerateGrocery = enumerate(grocery) 8 | 9 | print(type(enumerateGrocery)) 10 | # 11 | 12 | # converting to list since it is a enumerate object, can't access it directly 13 | print(list(enumerateGrocery)) 14 | # [(0, 'bread'), (1, 'milk'), (2, 'butter')] 15 | 16 | # changing the default counter 17 | enumerateGrocery = enumerate(grocery, 10) 18 | print(list(enumerateGrocery)) 19 | # [(10, 'bread'), (11, 'milk'), (12, 'butter')] 20 | 21 | for item in enumerateGrocery: 22 | print(item) 23 | # # (0, 'bread') 24 | # # (1, 'milk') 25 | # # (2, 'butter') 26 | 27 | 28 | for count, item in enumerateGrocery: 29 | print(count, item) 30 | # 0 bread 31 | # 1 milk 32 | # 2 butter 33 | 34 | print('\n') 35 | # changing default start value 36 | for count, item in enumerate(grocery, 100): 37 | print(count, item) 38 | # 100 bread 39 | # 101 milk 40 | # 102 butter -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/flask/__pycache__/main.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/intermediate level & method/flask/__pycache__/main.cpython-310.pyc -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/flask/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route("/") 7 | def hello_world(): 8 | return \ 9 | "

Hello World

" \ 10 | "

This is a paragraph" \ 11 | "" 12 | 13 | @app.route("/say_bye") 14 | def bye(): 15 | return "Bye" 16 | 17 | @app.route("/username//") 18 | def greet(name, number): 19 | return f"Hello {name}, you are {number} years old." 20 | 21 | if __name__ == "__main__": 22 | app.run(debug=True) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/lambda/main.py: -------------------------------------------------------------------------------- 1 | 2 | # --------------------------------------------- single variable --------------------------------------------- 3 | from turtle import title 4 | 5 | 6 | def double(x): 7 | return x*2 8 | 9 | # same as 10 | 11 | double = lambda x : x*2 12 | 13 | print(double(9)) 14 | 15 | 16 | # --------------------------------------------- multiple variables --------------------------------------------- 17 | 18 | def full_name(first_name, last_name): 19 | return f"{first_name.strip().title()} {last_name.strip().title()}" 20 | 21 | # same as ... 22 | # define the lambda function 23 | full_name = lambda first_name, last_name : f"{first_name.strip().title()} {last_name.strip().title()}" 24 | 25 | # call it 26 | print(full_name(" SImon ", " ChOnG")) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/map, filter, reduce/filter.py: -------------------------------------------------------------------------------- 1 | items = [ 2 | ("Product1", 10), 3 | ("Product2", 9), 4 | ("Product3", 12) 5 | ] 6 | 7 | filtered = [(item[0], item[1]) for item in items if item[1] >= 10] 8 | # same as ... 9 | filtered = list(filter(lambda item : item[1] >= 10, items)) # convert the filter object into a list 10 | 11 | print(filtered) 12 | # [('Product1', 10), ('Product3', 12)] -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/map, filter, reduce/main.py: -------------------------------------------------------------------------------- 1 | # this file is to apply map, filter, and reduce to get the ideal result which is the total price from list 2 | # I wanna to have the total price of all product which above 50 3 | 4 | from functools import reduce 5 | 6 | items = [ 7 | ("Product1", 95), 8 | ("Product2", 30), 9 | ("Product3", 12), 10 | ("Product4", 11), 11 | ("Product5", 99), 12 | ("Product6", 50), 13 | ] 14 | 15 | # map(), to retrieve price only from the list 16 | prices_list = list(map(lambda item : item[1], items)) 17 | print("Prices List:", prices_list) 18 | 19 | # filter(), to filter out the price above 50 20 | prices_above_50_list = list(filter(lambda price : price > 50, prices_list)) 21 | print("Prices above 50:", prices_above_50_list) 22 | 23 | # reduce(), to sum up all prices above 50 24 | total_price = reduce(lambda current_price, next_price : current_price + next_price, prices_above_50_list) 25 | print("Total price:", total_price) 26 | -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/map, filter, reduce/map.py: -------------------------------------------------------------------------------- 1 | items = [ 2 | ("Product1", 10), 3 | ("Product2", 9), 4 | ("Product3", 12) 5 | ] 6 | 7 | prices_only = list(map(lambda item : item[1], items)) 8 | print(prices_only) 9 | # [10, 9, 12] 10 | 11 | prices_only = list(map(lambda item : item[1] > 10, items)) # different from filter, this will return Boolean from the condition instead of filter out 12 | print(prices_only) 13 | # [False, False, True] -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/map, filter, reduce/reduce.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | items = [ 4 | (10), 5 | (8), 6 | (12) 7 | ] 8 | 9 | total_price = reduce(lambda current_item, next_item : current_item + next_item, items) 10 | 11 | print(total_price) 12 | # 30 -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/python_exercise/idex_of_last_1.py: -------------------------------------------------------------------------------- 1 | from operator import index 2 | 3 | 4 | def lastIndex(s): 5 | if not "1" in s: 6 | return -1 7 | current_index = 0 8 | index_of_last_1 = 0 9 | for digit in s: 10 | if digit == "1": 11 | index_of_last_1 = current_index 12 | current_index += 1 #1 13 | return index_of_last_1 14 | 15 | print(lastIndex("00000000001000")) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/python_exercise/increment_of_digit_list.py: -------------------------------------------------------------------------------- 1 | def increment(N): 2 | number = "".join(N) 3 | return number 4 | 5 | num_list = [1,2,3] 6 | print(increment(num_list)) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/python_exercise/zero_reaplcec_to_5.py: -------------------------------------------------------------------------------- 1 | def convertFive(n): 2 | str_n = str(n) 3 | # for char in str_n: 4 | # if char == 5 | replaced = str_n.replace("0", "5") 6 | return replaced 7 | 8 | print(convertFive(100405605)) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/read_file/read_file.py: -------------------------------------------------------------------------------- 1 | with open("./hello.txt", encoding='utf8') as f: # use encoding for read language other than ASCII language such as Chinese, Japanese, 2 | file = f.readlines() 3 | 4 | for line in file: 5 | print(line.strip()) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/unpack_tuple_&_list/main.py: -------------------------------------------------------------------------------- 1 | # reference = https://www.pythontutorial.net/python-basics/python-unpacking-tuple/ 2 | # unpack means to split each item in tuple into a single variable 3 | 4 | (x, y) = (1, 2) 5 | print(x, y) 6 | # 1 2 7 | 8 | # swap 2 item without a temporary variable. 9 | (x, y) = (y ,x) 10 | print(x, y) 11 | # 2 1 12 | 13 | (x, y) = (10, 20, 30) 14 | # ValueError: too many values to unpack (expected 2) 15 | 16 | (x, y, _) = (10, 20, 30) 17 | print(x, y, _) # may use "_" marks the variable is not important, it's a regular/dummy variable 18 | # 20 20 30 19 | 20 | (r, g, *other) = (192, 210, 100, 0.5, "hello") # only one * can be used 21 | print(r, g, other) 22 | # 192 210 [100, 0.5], 'hello' 23 | 24 | 25 | # unpack the tuple and merge into a single variable 26 | odd_numbers = (1, 3, 5) 27 | even_numbers = (2, 4, 6) 28 | numbers = (*odd_numbers, *even_numbers) 29 | # or 30 | # numbers = (odd_numbers+even_numbers) 31 | print(numbers) -------------------------------------------------------------------------------- /Extra Knowledge/intermediate level & method/yield/main.py: -------------------------------------------------------------------------------- 1 | # yield is used to pause the current statement and convert in into a iterable object 2 | #! the iterable object called as a generator, it only can be call iterated once 3 | 4 | def greeting(): 5 | print('Hi!') 6 | yield 1 7 | print('How are you?') 8 | yield 2 9 | print('Are you there?') 10 | yield 3 11 | 12 | iterator_greeting = greeting() 13 | 14 | print(type(iterator_greeting)) 15 | # 16 | 17 | print(next(iterator_greeting)) 18 | print(next(iterator_greeting)) 19 | print(next(iterator_greeting)) 20 | 21 | print("=" * 100) 22 | 23 | # you wont see any output from the code below because line 17, 18, 19 have done the interation 24 | # as mentioned it is agenerator so it only can be interated once 25 | for message in iterator_greeting: 26 | print("-----------", message) -------------------------------------------------------------------------------- /Extra Knowledge/modules/datetime/date.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | from datetime import datetime 3 | def main(): 4 | ##DATETIME OBJECTS 5 | #Get today's date from datetime class 6 | today=datetime.now() 7 | #print (today) 8 | # Get the current time 9 | #t = datetime.time(datetime.now()) 10 | #print "The current time is", t 11 | #weekday returns 0 (monday) through 6 (sunday) 12 | wd=date.weekday(today) 13 | #Days start at 0 for monday 14 | print(today) 15 | days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] 16 | print("Today is day number %d" % wd) 17 | print("which is a " + days[wd]) 18 | 19 | if __name__== "__main__": 20 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/openpyxl/example.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/modules/openpyxl/example.xlsx -------------------------------------------------------------------------------- /Extra Knowledge/modules/openpyxl/read_created_excel.py: -------------------------------------------------------------------------------- 1 | import openpyxl 2 | 3 | wb = openpyxl.load_workbook("example.xlsx") 4 | 5 | #getting all sheets names 6 | print(wb.sheetnames) 7 | 8 | #getting a particular sheet 9 | selected_sheet = wb["sheet2"] 10 | print(selected_sheet) 11 | 12 | #getting sheet title 13 | print(selected_sheet.title) 14 | 15 | #Getting the active sheet 16 | sheetactive = wb.active 17 | print(sheetactive) -------------------------------------------------------------------------------- /Extra Knowledge/modules/openpyxl/sample.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/modules/openpyxl/sample.xlsx -------------------------------------------------------------------------------- /Extra Knowledge/modules/openpyxl/start-up.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | wb = Workbook() 3 | 4 | # grab the active worksheet 5 | ws = wb.active 6 | 7 | # Data can be assigned directly to cells 8 | ws['A1'] = 42 9 | 10 | # Rows can also be appended 11 | ws.append([10, 2, 3, 4, 6, 7, 4, 5]) 12 | 13 | # Python types will automatically be converted 14 | import datetime 15 | ws['A3'] = datetime.datetime.now() 16 | 17 | import random 18 | for _ in range(20): 19 | ws.append([random.randint(100, 1000)]) 20 | 21 | # Save the file 22 | wb.save("sample.xlsx") -------------------------------------------------------------------------------- /Extra Knowledge/modules/openpyxl/write_new_excel.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook 2 | #creates a new workbook 3 | wb = Workbook() 4 | #Gets the first active worksheet 5 | ws = wb.active 6 | #creating new worksheets by using the create_sheet method 7 | 8 | ws1 = wb.create_sheet("sheet1", 0) #inserts at first position 9 | ws2 = wb.create_sheet("sheet2") #inserts at last position 10 | ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position 11 | ws4 = wb.create_sheet() 12 | ws5 = wb.create_sheet() 13 | 14 | #Renaming the sheet 15 | ws5.title = "Example" 16 | 17 | #save the workbook 18 | wb.save(filename = "example.xlsx") -------------------------------------------------------------------------------- /Extra Knowledge/modules/pandas/descriptive.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | 4 | #Create a Dictionary of series 5 | d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack', 6 | 'Lee','David','Gasper','Betina','Andres']), 7 | 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]), 8 | 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65]) 9 | } 10 | 11 | #Create a DataFrame 12 | df = pd.DataFrame(d) 13 | print(df) 14 | # Name Age Rating 15 | # 0 Tom 25 4.23 16 | # 1 James 26 3.24 17 | # 2 Ricky 25 3.98 18 | # 3 Vin 23 2.56 19 | # 4 Steve 30 3.20 20 | # 5 Smith 29 4.60 21 | # 6 Jack 23 3.80 22 | # 7 Lee 34 3.78 23 | # 8 David 40 2.98 24 | # 9 Gasper 30 4.80 25 | # 10 Betina 51 4.10 26 | # 11 Andres 46 3.65 27 | 28 | 29 | #Create a DataFrame 30 | print(df.sum()) 31 | # Name TomJamesRickyVinSteveSmithJackLeeDavidGasperBe... 32 | # Age 382 33 | # Rating 44.92 34 | # dtype: object -------------------------------------------------------------------------------- /Extra Knowledge/modules/pandas/series.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | 4 | 5 | # ------------------------------------------- Create a Series from ndarray ---------------------------------------- 6 | data = np.array(['a','b','c','d']) 7 | 8 | s = pd.Series(data) 9 | print(s) 10 | # 0 a 11 | # 1 b 12 | # 2 c 13 | # 3 d 14 | # dtype: object 15 | 16 | # user define the index number 17 | s = pd.Series(data, index=[100,101,102,103]) 18 | print(s) 19 | # 100 a 20 | # 101 b 21 | # 102 c 22 | # 103 d 23 | # dtype: object 24 | 25 | 26 | # ------------------------------------------- Create a Series from dict ---------------------------------------- 27 | # key of dictionary will be the index 28 | data = {'a' : 0., 'b' : 1., 'c' : 2.} 29 | s = pd.Series(data) #If index is passed, the values in data corresponding to the labels in the index will be pulled out 30 | print(s) 31 | # a 0.0 32 | # b 1.0 33 | # c 2.0 34 | # dtype: float64 35 | 36 | 37 | data = {'a' : 0., 'b' : 1., 'c' : 2.} 38 | s = pd.Series(data, index=['a', 'c']) #If index is passed, the values in data corresponding to the labels in the index will be pulled out 39 | print(s) 40 | # a 0.0 41 | # c 2.0 42 | # dtype: float64 43 | 44 | 45 | # ------------------------------------------- Create a Series from scalar ---------------------------------------- 46 | s = pd.Series(6, index=[0, 1, 2, 3]) 47 | print(s) 48 | # 0 6 49 | # 1 6 50 | # 2 6 51 | # 3 6 52 | 53 | 54 | # ---------------------------------------- Accessing Data from Series with Position ------------------------------------- 55 | s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e']) 56 | #retrieve the first element 57 | print(s[0]) 58 | # 1 59 | 60 | # get first three elements 61 | print(s[:3]) 62 | # a 1 63 | # b 2 64 | # c 3 65 | 66 | # get the last three elements 67 | print(s[-3:]) 68 | # c 3 69 | # d 4 70 | # e 5 71 | # dtype: int64 72 | 73 | # ---------------------------------------- Retrieve Data Using Label (Index) ------------------------------------- 74 | s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e']) 75 | 76 | #retrieve a single element 77 | print(s['e']) 78 | # 5 79 | 80 | #retrieve multiple elements 81 | print(s[['a','c','d']]) 82 | # a 1 83 | # c 3 84 | # d 4 85 | # dtype: int64 -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/datetime/current_date_time.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import QDate, QTime, QDateTime, Qt 2 | 3 | now = QDate.currentDate() 4 | 5 | print(now.toString(Qt.ISODate)) 6 | print(now.toString(Qt.DefaultLocaleLongDate)) 7 | 8 | datetime = QDateTime.currentDateTime() 9 | 10 | print(datetime.toString()) 11 | 12 | time = QTime.currentTime() 13 | 14 | print(time.toString(Qt.DefaultLocaleLongDate)) -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/datetime/difference_days.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import QDate 2 | 3 | xmas1 = QDate(2019, 12, 24) 4 | xmas2 = QDate(2022, 12, 24) 5 | 6 | now = QDate.currentDate() 7 | 8 | dayspassed = xmas1.daysTo(now) 9 | print(f'{dayspassed} days have passed since last XMas') 10 | 11 | nofdays = now.daysTo(xmas2) 12 | print(f'There are {nofdays} days until next XMas') -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/datetime/number_of_day.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import QDate, Qt 2 | 3 | now = QDate.currentDate() 4 | 5 | d = QDate(1998, 5, 7) 6 | 7 | print(f'Days in month: {d.daysInMonth()}') 8 | print(f'Days in year: {d.daysInYear()}') -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/event & signal/reimplementing_event.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtCore import Qt 3 | from PyQt5.QtWidgets import QWidget, QApplication 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | self.setGeometry(300, 300, 250, 150) 15 | self.setWindowTitle('Event handler') 16 | self.show() 17 | 18 | def keyPressEvent(self, e): 19 | if e.key() == Qt.Key_Escape: 20 | self.close() 21 | 22 | 23 | def main(): 24 | app = QApplication(sys.argv) 25 | ex = Example() 26 | sys.exit(app.exec_()) 27 | 28 | 29 | if __name__ == '__main__': 30 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/event & signal/signal_slots.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtCore import Qt 3 | from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider, 4 | QVBoxLayout, QApplication) 5 | 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.initUI() 13 | 14 | 15 | def initUI(self): 16 | 17 | lcd = QLCDNumber(self) 18 | sld = QSlider(Qt.Horizontal, self) 19 | 20 | vbox = QVBoxLayout() 21 | vbox.addWidget(lcd) 22 | vbox.addWidget(sld) 23 | 24 | self.setLayout(vbox) 25 | sld.valueChanged.connect(lcd.display) 26 | 27 | self.setGeometry(300, 300, 700, 700) 28 | self.setWindowTitle('Signal and slot') 29 | self.show() 30 | 31 | 32 | def main(): 33 | app = QApplication(sys.argv) 34 | ex = Example() 35 | sys.exit(app.exec_()) 36 | 37 | 38 | if __name__ == '__main__': 39 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/layout/absolute.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QWidget, QLabel, QApplication 3 | 4 | 5 | class Example(QWidget): 6 | 7 | def __init__(self): 8 | super().__init__() 9 | 10 | self.initUI() 11 | 12 | def initUI(self): 13 | lbl1 = QLabel('ZetCode', self) 14 | lbl1.move(15, 10) 15 | 16 | lbl2 = QLabel('tutorials', self) 17 | lbl2.move(35, 40) 18 | 19 | lbl3 = QLabel('for programmers', self) 20 | lbl3.move(55, 70) 21 | 22 | self.setGeometry(300, 300, 250, 150) 23 | self.setWindowTitle('Absolute') 24 | self.show() 25 | 26 | 27 | def main(): 28 | app = QApplication(sys.argv) 29 | ex = Example() 30 | sys.exit(app.exec_()) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/layout/form.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, 3 | QTextEdit, QGridLayout, QApplication) 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | title = QLabel('Title') 15 | author = QLabel('Author') 16 | review = QLabel('Review') 17 | 18 | titleEdit = QLineEdit() 19 | authorEdit = QLineEdit() 20 | reviewEdit = QTextEdit() 21 | 22 | grid = QGridLayout() 23 | grid.setSpacing(10) 24 | 25 | grid.addWidget(title, 1, 0) 26 | grid.addWidget(titleEdit, 1, 1) 27 | 28 | grid.addWidget(author, 2, 0) 29 | grid.addWidget(authorEdit, 2, 1) 30 | 31 | grid.addWidget(review, 3, 0) 32 | grid.addWidget(reviewEdit, 3, 1, 5, 1) 33 | 34 | self.setLayout(grid) 35 | 36 | self.setGeometry(300, 300, 350, 300) 37 | self.setWindowTitle('Review') 38 | self.show() 39 | 40 | 41 | def main(): 42 | app = QApplication(sys.argv) 43 | ex = Example() 44 | sys.exit(app.exec_()) 45 | 46 | 47 | if __name__ == '__main__': 48 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/layout/grid.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import (QWidget, QGridLayout, 3 | QPushButton, QApplication) 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | 15 | grid = QGridLayout() 16 | self.setLayout(grid) 17 | 18 | names = ['Cls', 'Bck', '', 'Close', 19 | '7', '8', '9', '/', 20 | '4', '5', '6', '*', 21 | '1', '2', '3', '-', 22 | '0', '.', '=', '+'] 23 | 24 | positions = [(i, j) for i in range(5) for j in range(4)] 25 | 26 | for position, name in zip(positions, names): 27 | 28 | if name == '': 29 | continue 30 | button = QPushButton(name) 31 | grid.addWidget(button, *position) 32 | 33 | self.move(300, 150) 34 | self.setWindowTitle('Calculator') 35 | self.show() 36 | 37 | 38 | def main(): 39 | app = QApplication(sys.argv) 40 | ex = Example() 41 | sys.exit(app.exec_()) 42 | 43 | 44 | if __name__ == '__main__': 45 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/layout/horizontal_vertical.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import (QWidget, QPushButton, 3 | QHBoxLayout, QVBoxLayout, QApplication) 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | 15 | okButton = QPushButton("OK") 16 | cancelButton = QPushButton("Cancel") 17 | 18 | hbox = QHBoxLayout() 19 | hbox.addStretch(1) 20 | hbox.addWidget(okButton) 21 | hbox.addWidget(cancelButton) 22 | 23 | vbox = QVBoxLayout() 24 | vbox.addStretch(1) 25 | vbox.addLayout(hbox) 26 | 27 | self.setLayout(vbox) 28 | 29 | self.setGeometry(300, 300, 300, 150) 30 | self.setWindowTitle('Buttons') 31 | self.show() 32 | 33 | 34 | def main(): 35 | app = QApplication(sys.argv) 36 | ex = Example() 37 | sys.exit(app.exec_()) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/check_menu.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, QAction, QApplication 3 | 4 | 5 | class Example(QMainWindow): 6 | 7 | def __init__(self): 8 | super().__init__() 9 | 10 | self.initUI() 11 | 12 | 13 | def initUI(self): 14 | 15 | self.statusbar = self.statusBar() 16 | self.statusbar.showMessage('Ready') 17 | 18 | menubar = self.menuBar() 19 | viewMenu = menubar.addMenu('View') 20 | 21 | viewStatAct = QAction('View statusbar', self, checkable=True) 22 | viewStatAct.setStatusTip('View statusbar') 23 | viewStatAct.setChecked(True) 24 | viewStatAct.triggered.connect(self.toggleMenu) 25 | 26 | viewMenu.addAction(viewStatAct) 27 | 28 | self.setGeometry(300, 300, 300, 200) 29 | self.setWindowTitle('Check menu') 30 | self.show() 31 | 32 | def toggleMenu(self, state): 33 | 34 | if state: 35 | self.statusbar.show() 36 | else: 37 | self.statusbar.hide() 38 | 39 | 40 | def main(): 41 | app = QApplication(sys.argv) 42 | ex = Example() 43 | sys.exit(app.exec_()) 44 | 45 | 46 | if __name__ == '__main__': 47 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/main_area.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication 3 | from PyQt5.QtGui import QIcon 4 | 5 | 6 | class Example(QMainWindow): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | 14 | def initUI(self): 15 | 16 | textEdit = QTextEdit() 17 | self.setCentralWidget(textEdit) 18 | 19 | exitAct = QAction(QIcon('exit24.png'), 'Exit', self) 20 | exitAct.setShortcut('Ctrl+Q') 21 | exitAct.setStatusTip('Exit application') 22 | exitAct.triggered.connect(self.close) 23 | 24 | self.statusBar() 25 | 26 | menubar = self.menuBar() 27 | fileMenu = menubar.addMenu('&File') 28 | fileMenu.addAction(exitAct) 29 | 30 | toolbar = self.addToolBar('Exit') 31 | toolbar.addAction(exitAct) 32 | 33 | self.setGeometry(300, 300, 350, 250) 34 | self.setWindowTitle('Main window') 35 | self.show() 36 | 37 | 38 | def main(): 39 | app = QApplication(sys.argv) 40 | ex = Example() 41 | sys.exit(app.exec_()) 42 | 43 | 44 | if __name__ == '__main__': 45 | main() 46 | 47 | -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/right_click_menu.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, qApp, QMenu, QApplication 3 | 4 | 5 | class Example(QMainWindow): 6 | 7 | def __init__(self): 8 | super().__init__() 9 | 10 | self.initUI() 11 | 12 | def initUI(self): 13 | self.setGeometry(300, 300, 300, 200) 14 | self.setWindowTitle('Context menu') 15 | self.show() 16 | 17 | def contextMenuEvent(self, event): 18 | cmenu = QMenu(self) 19 | 20 | newAct = cmenu.addAction("New") 21 | openAct = cmenu.addAction("Open") 22 | quitAct = cmenu.addAction("Quit") 23 | action = cmenu.exec_(self.mapToGlobal(event.pos())) 24 | 25 | if action == quitAct: 26 | qApp.quit() 27 | 28 | 29 | def main(): 30 | app = QApplication(sys.argv) 31 | ex = Example() 32 | sys.exit(app.exec_()) 33 | 34 | 35 | if __name__ == '__main__': 36 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/simple_menu.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication 3 | from PyQt5.QtGui import QIcon 4 | 5 | 6 | class Example(QMainWindow): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | 15 | exitAct = QAction(QIcon('exit.png'), '&Exit', self) 16 | exitAct.setShortcut('Ctrl+Q') 17 | exitAct.setStatusTip('Exit application') 18 | exitAct.triggered.connect(qApp.quit) 19 | 20 | self.statusBar() 21 | 22 | menubar = self.menuBar() 23 | fileMenu = menubar.addMenu('&File') 24 | fileMenu.addAction(exitAct) 25 | 26 | self.setGeometry(300, 300, 300, 200) 27 | self.setWindowTitle('Simple menu') 28 | self.show() 29 | 30 | 31 | def main(): 32 | app = QApplication(sys.argv) 33 | ex = Example() 34 | sys.exit(app.exec_()) 35 | 36 | 37 | if __name__ == '__main__': 38 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/status_bar.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, QApplication 3 | 4 | 5 | class Example(QMainWindow): 6 | 7 | def __init__(self): 8 | super().__init__() 9 | 10 | self.initUI() 11 | 12 | def initUI(self): 13 | self.statusBar().showMessage('Ready') 14 | self.setGeometry(300, 300, 250, 150) 15 | self.setWindowTitle('Statusbar') 16 | self.show() 17 | 18 | def main(): 19 | app = QApplication(sys.argv) 20 | ex = Example() 21 | sys.exit(app.exec_()) 22 | 23 | 24 | if __name__ == '__main__': 25 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/submenu.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, QAction, QMenu, QApplication 3 | 4 | 5 | class Example(QMainWindow): 6 | 7 | def __init__(self): 8 | super().__init__() 9 | 10 | self.initUI() 11 | 12 | def initUI(self): 13 | 14 | menubar = self.menuBar() 15 | fileMenu = menubar.addMenu('File') 16 | setting = menubar.addMenu('Setting') 17 | 18 | impMenu = QMenu('Import', self) # create a parent menu 19 | impAct = QAction('Import mail', self) 20 | impMenu.addAction(impAct) 21 | 22 | newAct = QAction('New', self) 23 | 24 | brightness_setting = QMenu('Adjust Brightness', self) 25 | 26 | fileMenu.addAction(newAct) 27 | fileMenu.addMenu(impMenu) 28 | setting.addMenu(brightness_setting) 29 | 30 | self.setGeometry(300, 300, 300, 200) 31 | self.setWindowTitle('Submenu') 32 | self.show() 33 | 34 | 35 | def main(): 36 | app = QApplication(sys.argv) 37 | ex = Example() 38 | sys.exit(app.exec_()) 39 | 40 | 41 | if __name__ == '__main__': 42 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/menu & toolbar/toolbar.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication 3 | from PyQt5.QtGui import QIcon 4 | 5 | 6 | class Example(QMainWindow): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | 14 | def initUI(self): 15 | 16 | exitAct = QAction(QIcon('./dog.png'), 'Exit', self) 17 | exitAct.setShortcut('Ctrl+Q') 18 | exitAct.triggered.connect(qApp.quit) 19 | 20 | self.toolbar = self.addToolBar('Exit') 21 | self.toolbar.addAction(exitAct) 22 | 23 | self.setGeometry(300, 300, 300, 200) 24 | self.setWindowTitle('Toolbar') 25 | self.show() 26 | 27 | 28 | def main(): 29 | app = QApplication(sys.argv) 30 | ex = Example() 31 | sys.exit(app.exec_()) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/start_up.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QApplication, QWidget 3 | 4 | 5 | def main(): 6 | 7 | app = QApplication(sys.argv) 8 | 9 | w = QWidget() 10 | w.resize(500, 500) 11 | w.move(500, 500) 12 | w.setWindowTitle('Testing Program') 13 | w.show() 14 | 15 | sys.exit(app.exec_()) 16 | 17 | 18 | if __name__ == '__main__': 19 | main() 20 | 21 | # reference: 22 | # https://zetcode.com/gui/pyqt5/firstprograms/ -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/tooltip_&_logo.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import (QWidget, QToolTip, QPushButton, QApplication) 3 | from PyQt5.QtGui import QFont 4 | from PyQt5.QtGui import QIcon 5 | 6 | 7 | 8 | class Example(QWidget): 9 | 10 | def __init__(self): 11 | super().__init__() 12 | 13 | self.initUI() 14 | 15 | 16 | def initUI(self): 17 | 18 | QToolTip.setFont(QFont('SansSerif', 10)) 19 | 20 | self.setToolTip('This is a QWidget widget') 21 | 22 | # create button and set tooltip for it 23 | btn = QPushButton('Button', self) 24 | btn.setToolTip('This is a QPushButton widget') 25 | btn.resize(btn.sizeHint()) # give a recommened size for it 26 | btn.move(50, 50) 27 | 28 | # set the window title and icon 29 | self.setWindowTitle('Icon') 30 | self.setWindowIcon(QIcon('dog.png')) 31 | 32 | # combination resive and move method 33 | # set the x, y position on screen, and width and height of the window 34 | # setGeometry(x, y, width, height) 35 | self.setGeometry(300, 300, 300, 200) 36 | self.setWindowTitle('Tooltips') 37 | 38 | 39 | self.show() 40 | 41 | 42 | def main(): 43 | 44 | app = QApplication(sys.argv) 45 | ex = Example() 46 | sys.exit(app.exec_()) 47 | 48 | 49 | if __name__ == '__main__': 50 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/calendar.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import (QWidget, QCalendarWidget, 2 | QLabel, QApplication, QVBoxLayout) 3 | from PyQt5.QtCore import QDate 4 | import sys 5 | 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.initUI() 13 | 14 | def initUI(self): 15 | vbox = QVBoxLayout(self) 16 | 17 | cal = QCalendarWidget(self) 18 | cal.setGridVisible(True) 19 | cal.clicked[QDate].connect(self.showDate) 20 | 21 | vbox.addWidget(cal) 22 | 23 | self.lbl = QLabel(self) 24 | date = cal.selectedDate() 25 | self.lbl.setText(date.toString()) 26 | 27 | vbox.addWidget(self.lbl) 28 | 29 | self.setLayout(vbox) 30 | 31 | self.setGeometry(300, 300, 350, 300) 32 | self.setWindowTitle('Calendar') 33 | self.show() 34 | 35 | def showDate(self, date): 36 | self.lbl.setText(date.toString()) 37 | 38 | 39 | def main(): 40 | app = QApplication(sys.argv) 41 | ex = Example() 42 | sys.exit(app.exec_()) 43 | 44 | 45 | if __name__ == '__main__': 46 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/check_box.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication 2 | from PyQt5.QtCore import Qt 3 | import sys 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | 15 | cb = QCheckBox('Show title', self) 16 | cb.move(20, 20) 17 | cb.toggle() 18 | cb.stateChanged.connect(self.changeTitle) 19 | 20 | self.setGeometry(300, 300, 350, 250) 21 | self.setWindowTitle('QCheckBox') 22 | self.show() 23 | 24 | def changeTitle(self, state): 25 | 26 | if state == Qt.Checked: 27 | self.setWindowTitle('Checked') 28 | else: 29 | self.setWindowTitle('Unchecked') 30 | 31 | 32 | def main(): 33 | app = QApplication(sys.argv) 34 | ex = Example() 35 | sys.exit(app.exec_()) 36 | 37 | 38 | if __name__ == '__main__': 39 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/display_image.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import (QWidget, QHBoxLayout, 2 | QLabel, QApplication) 3 | from PyQt5.QtGui import QPixmap 4 | import sys 5 | 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.initUI() 13 | 14 | def initUI(self): 15 | hbox = QHBoxLayout(self) 16 | pixmap = QPixmap('dog.png') 17 | 18 | lbl = QLabel(self) 19 | lbl.setPixmap(pixmap) 20 | 21 | hbox.addWidget(lbl) 22 | self.setLayout(hbox) 23 | 24 | self.setGeometry(300, 300, 350, 250) 25 | 26 | self.setWindowTitle('Sid') 27 | self.show() 28 | 29 | 30 | def main(): 31 | app = QApplication(sys.argv) 32 | ex = Example() 33 | sys.exit(app.exec_()) 34 | 35 | 36 | if __name__ == '__main__': 37 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/drop_down_list.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from PyQt5.QtWidgets import (QWidget, QLabel, 4 | QComboBox, QApplication) 5 | 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.initUI() 13 | 14 | def initUI(self): 15 | 16 | self.lbl = QLabel('Ubuntu', self) 17 | 18 | combo = QComboBox(self) 19 | combo.addItem('Ubuntu') 20 | combo.addItem('Mandriva') 21 | combo.addItem('Fedora') 22 | combo.addItem('Arch') 23 | combo.addItem('Gentoo') 24 | 25 | combo.move(50, 50) 26 | self.lbl.move(50, 150) 27 | 28 | combo.activated[str].connect(self.onActivated) 29 | 30 | self.setGeometry(300, 300, 450, 400) 31 | self.setWindowTitle('QComboBox') 32 | self.show() 33 | 34 | def onActivated(self, text): 35 | self.lbl.setText(text) 36 | self.lbl.adjustSize() 37 | 38 | 39 | def main(): 40 | app = QApplication(sys.argv) 41 | ex = Example() 42 | sys.exit(app.exec_()) 43 | 44 | 45 | if __name__ == '__main__': 46 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/input_dialog.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, 2 | QInputDialog, QApplication) 3 | import sys 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | self.btn = QPushButton('Dialog', self) 15 | self.btn.move(20, 20) 16 | self.btn.clicked.connect(self.showDialog) 17 | 18 | self.input_field = QLineEdit(self) 19 | self.input_field.move(130, 22) 20 | 21 | self.setGeometry(300, 300, 450, 350) 22 | self.setWindowTitle('Input dialog') 23 | self.show() 24 | 25 | def showDialog(self): 26 | text, ok = QInputDialog.getText(self, 'Input Dialog', 27 | 'Enter your name:') 28 | 29 | if ok: 30 | self.input_field.setText(str(text)) 31 | 32 | 33 | def main(): 34 | app = QApplication(sys.argv) 35 | ex = Example() 36 | sys.exit(app.exec_()) 37 | 38 | 39 | if __name__ == '__main__': 40 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/input_edit.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import (QWidget, QLabel, 3 | QLineEdit, QApplication) 4 | 5 | 6 | class Example(QWidget): 7 | 8 | def __init__(self): 9 | super().__init__() 10 | 11 | self.initUI() 12 | 13 | def initUI(self): 14 | self.label = QLabel(self) 15 | edit_field = QLineEdit(self) 16 | 17 | edit_field.move(60, 100) 18 | self.label.move(60, 40) 19 | 20 | edit_field.textChanged[str].connect(self.onChanged) 21 | 22 | self.setGeometry(300, 300, 350, 250) 23 | 24 | self.show() 25 | 26 | def onChanged(self, text): 27 | self.label.setText(text) 28 | self.label.adjustSize() 29 | self.setWindowTitle(text) 30 | 31 | 32 | def main(): 33 | app = QApplication(sys.argv) 34 | ex = Example() 35 | sys.exit(app.exec_()) 36 | 37 | 38 | if __name__ == '__main__': 39 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/max.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/modules/pyqt5/widget/max.jpg -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/med.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/modules/pyqt5/widget/med.jpg -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/min.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/modules/pyqt5/widget/min.jpg -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/mute.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Extra Knowledge/modules/pyqt5/widget/mute.jpg -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/progress_bar.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import (QWidget, QProgressBar, 2 | QPushButton, QApplication) 3 | from PyQt5.QtCore import QBasicTimer 4 | import sys 5 | 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.initUI() 13 | 14 | def initUI(self): 15 | 16 | self.pbar = QProgressBar(self) 17 | self.pbar.setGeometry(30, 40, 700, 25) 18 | 19 | self.btn = QPushButton('Start', self) 20 | self.btn.move(40, 80) 21 | self.btn.clicked.connect(self.doAction) 22 | 23 | self.timer = QBasicTimer() 24 | self.step = 0 25 | 26 | self.setGeometry(300, 300, 1000, 700) 27 | self.setWindowTitle('QProgressBar') 28 | self.show() 29 | 30 | def timerEvent(self, e): 31 | 32 | if self.step >= 100: 33 | self.timer.stop() 34 | self.btn.setText('Finished') 35 | return 36 | 37 | self.step = self.step + 1 38 | self.pbar.setValue(self.step) 39 | 40 | def doAction(self): 41 | 42 | if self.timer.isActive(): 43 | self.timer.stop() 44 | self.btn.setText('Start') 45 | else: 46 | self.timer.start(100, self) 47 | self.btn.setText('Stop') 48 | 49 | 50 | def main(): 51 | app = QApplication(sys.argv) 52 | ex = Example() 53 | sys.exit(app.exec_()) 54 | 55 | 56 | if __name__ == '__main__': 57 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/quit_button_&_message_box.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication, QPushButton 3 | 4 | 5 | class Example(QWidget): 6 | 7 | def __init__(self): 8 | super().__init__() 9 | 10 | self.initUI() 11 | 12 | def initUI(self): 13 | 14 | qbtn = QPushButton('Quit', self) 15 | qbtn.clicked.connect(QApplication.instance().quit) 16 | qbtn.resize(qbtn.sizeHint()) 17 | qbtn.move(50, 50) 18 | 19 | self.setGeometry(300, 300, 250, 150) 20 | self.setWindowTitle('Message box') 21 | self.show() 22 | 23 | def closeEvent(self, event): 24 | 25 | reply = QMessageBox.question(self, 'Message', 26 | "Are you sure to quit?", QMessageBox.Yes | 27 | QMessageBox.No, QMessageBox.No) 28 | 29 | if reply == QMessageBox.Yes: 30 | 31 | event.accept() 32 | else: 33 | 34 | event.ignore() 35 | 36 | 37 | def main(): 38 | app = QApplication(sys.argv) 39 | ex = Example() 40 | sys.exit(app.exec_()) 41 | 42 | 43 | if __name__ == '__main__': 44 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/slider.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import (QWidget, QSlider, 2 | QLabel, QApplication) 3 | from PyQt5.QtCore import Qt 4 | from PyQt5.QtGui import QPixmap 5 | import sys 6 | 7 | 8 | class Example(QWidget): 9 | 10 | def __init__(self): 11 | super().__init__() 12 | 13 | self.initUI() 14 | 15 | def initUI(self): 16 | 17 | sld = QSlider(Qt.Horizontal, self) 18 | sld.setFocusPolicy(Qt.NoFocus) 19 | sld.setGeometry(30, 40, 200, 30) 20 | sld.valueChanged[int].connect(self.changeValue) 21 | 22 | self.label = QLabel(self) 23 | self.label.setPixmap(QPixmap('mute.png')) 24 | self.label.setGeometry(250, 40, 80, 30) 25 | 26 | self.setGeometry(300, 300, 350, 250) 27 | self.setWindowTitle('QSlider') 28 | self.show() 29 | 30 | def changeValue(self, value): 31 | 32 | if value == 0: 33 | # the icon doesnt work here 34 | self.label.setPixmap(QPixmap('mute.jpg')) 35 | elif 0 < value <= 30: 36 | 37 | self.label.setPixmap(QPixmap('min.jpg')) 38 | elif 30 < value < 80: 39 | 40 | self.label.setPixmap(QPixmap('med.jpg')) 41 | else: 42 | 43 | self.label.setPixmap(QPixmap('max.jpg')) 44 | 45 | 46 | def main(): 47 | app = QApplication(sys.argv) 48 | ex = Example() 49 | sys.exit(app.exec_()) 50 | 51 | 52 | if __name__ == '__main__': 53 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/splitter.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from PyQt5.QtCore import Qt 4 | from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QFrame, 5 | QSplitter, QApplication) 6 | 7 | 8 | class Example(QWidget): 9 | 10 | def __init__(self): 11 | super().__init__() 12 | 13 | self.initUI() 14 | 15 | def initUI(self): 16 | 17 | hbox = QHBoxLayout(self) 18 | 19 | topleft = QFrame(self) 20 | topleft.setFrameShape(QFrame.StyledPanel) 21 | 22 | topright = QFrame(self) 23 | topright.setFrameShape(QFrame.StyledPanel) 24 | 25 | bottom = QFrame(self) 26 | bottom.setFrameShape(QFrame.StyledPanel) 27 | 28 | splitter1 = QSplitter(Qt.Horizontal) 29 | splitter1.addWidget(topleft) 30 | splitter1.addWidget(topright) 31 | 32 | splitter2 = QSplitter(Qt.Vertical) 33 | splitter2.addWidget(splitter1) 34 | splitter2.addWidget(bottom) 35 | 36 | hbox.addWidget(splitter2) 37 | self.setLayout(hbox) 38 | 39 | self.setGeometry(300, 300, 450, 400) 40 | self.setWindowTitle('QSplitter') 41 | self.show() 42 | 43 | 44 | def main(): 45 | app = QApplication(sys.argv) 46 | ex = Example() 47 | sys.exit(app.exec_()) 48 | 49 | 50 | if __name__ == '__main__': 51 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/pyqt5/widget/toggle_button.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import (QWidget, QPushButton, 2 | QFrame, QApplication) 3 | from PyQt5.QtGui import QColor 4 | import sys 5 | 6 | 7 | class Example(QWidget): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | 12 | self.initUI() 13 | 14 | def initUI(self): 15 | 16 | self.col = QColor(0, 0, 0) 17 | 18 | redb = QPushButton('Red', self) 19 | redb.setCheckable(True) 20 | redb.move(10, 10) 21 | 22 | redb.clicked[bool].connect(self.setColor) 23 | 24 | greenb = QPushButton('Green', self) 25 | greenb.setCheckable(True) 26 | greenb.move(10, 60) 27 | 28 | greenb.clicked[bool].connect(self.setColor) 29 | 30 | blueb = QPushButton('Blue', self) 31 | blueb.setCheckable(True) 32 | blueb.move(10, 110) 33 | 34 | blueb.clicked[bool].connect(self.setColor) 35 | 36 | self.square = QFrame(self) 37 | self.square.setGeometry(150, 20, 100, 100) 38 | self.square.setStyleSheet("QWidget { background-color: %s }" % 39 | self.col.name()) 40 | 41 | self.setGeometry(300, 300, 300, 250) 42 | self.setWindowTitle('Toggle button') 43 | self.show() 44 | 45 | def setColor(self, pressed): 46 | 47 | source = self.sender() 48 | 49 | if pressed: 50 | val = 255 51 | else: 52 | val = 0 53 | 54 | if source.text() == "Red": 55 | self.col.setRed(val) 56 | elif source.text() == "Green": 57 | self.col.setGreen(val) 58 | else: 59 | self.col.setBlue(val) 60 | 61 | self.square.setStyleSheet("QFrame { background-color: %s }" % 62 | self.col.name()) 63 | 64 | 65 | def main(): 66 | app = QApplication(sys.argv) 67 | ex = Example() 68 | sys.exit(app.exec_()) 69 | 70 | 71 | if __name__ == '__main__': 72 | main() -------------------------------------------------------------------------------- /Extra Knowledge/modules/request/get.py: -------------------------------------------------------------------------------- 1 | # importing the requests library 2 | import requests 3 | from pprint import pprint 4 | 5 | # api-endpoint 6 | URL = "http://maps.googleapis.com/maps/api/geocode/json?" 7 | 8 | # location given here 9 | location = "tun razak exchange kuala lumpur" 10 | 11 | # defining a params dict for the parameters to be sent to the API 12 | PARAMS = {'address':location} 13 | 14 | # sending get request and saving the response as response object 15 | response = requests.get(url = URL, params = PARAMS, verify=False) 16 | 17 | # extracting data in json format 18 | data = response.json() 19 | 20 | print(response.raise_for_status) 21 | pprint(data) 22 | 23 | dic = dict(key1='value1', key2='value2') 24 | print(dic) 25 | -------------------------------------------------------------------------------- /Extra Knowledge/modules/request/hello.txt: -------------------------------------------------------------------------------- 1 | haahaha 2 | haahaha 3 | haahaha 4 | haahaha 5 | haahaha 6 | haahaha 7 | haahaha -------------------------------------------------------------------------------- /Extra Knowledge/modules/request/response_method.py: -------------------------------------------------------------------------------- 1 | # reference: https://www.geeksforgeeks.org/python-requests-tutorial/ 2 | 3 | from dataclasses import dataclass 4 | import requests 5 | from pprint import pprint 6 | 7 | simon_github_URI = "https://api.github.com/users/simonnchong" 8 | response = requests.get(simon_github_URI, verify=False) 9 | print(response.headers) # returns a dictionary of response headers 10 | print(response.encoding) # returns the encoding used to decode response.content 11 | print(response.elapsed) # returns a timedelta object with the time elapsed from sending the request to the arrival of the response 12 | print(response.content) # returns the content of the response, in bytes 13 | print(response.cookies) # returns a CookieJar object with the cookies sent back from the server 14 | print(response.history) # returns a list of response objects holding the history of request (url) 15 | print(response.is_redirect) # returns True if the response was redirected, otherwise False 16 | print(response.is_permanent_redirect) # returns True if the response is the permanent redirected url, otherwise False 17 | print(response.iter_content() ) # iterates over the response.content 18 | print(response.url) # returns the URL of the response. 19 | print(response.text) # returns the content of the response, in unicode 20 | print(response.status_code) # returns a number that indicates the status 21 | print(response.request) # returns the request object that requested this response 22 | print(response.reason) # returns a text corresponding to the status code 23 | print(response.raise_for_status()) # returns an HTTPError object if an error has occurred during the process 24 | print(response.ok) # returns True if status_code is less than 200, otherwise False 25 | print(response.links) # returns the header links 26 | print(response.close()) # close the connection to the server 27 | pprint(response.json()) # returns a JSON object of the result (if the result was written in JSON format, if not it raises an error) 28 | print("-"*100) 29 | print(response.close()) # close the connection to the server 30 | 31 | 32 | 33 | 34 | #* ----------------------------------------------- NOTES --------------------------------------------------- 35 | 36 | # PUT vs PATCH 37 | 38 | # PUT - Replace the entire data 39 | # PATCH - Modify part of data 40 | 41 | -------------------------------------------------------------------------------- /Extra Knowledge/modules/selenium/start_up.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.by import By 3 | 4 | chrome_driver = "D:/chromedriver" 5 | driver = webdriver.Chrome(chrome_driver) 6 | 7 | 8 | driver.get("https://www.python.org/") 9 | 10 | driver.implicitly_wait(1) 11 | 12 | # Selenium Python provides two types of waits - implicit & explicit. An explicit wait makes selenium wait for a specific condition to occur before proceeding further with execution. 13 | # An implicit wait makes selenium python poll the DOM for a certain amount of time with a 300ms interval when trying to locate an element. 14 | 15 | latest_news = driver.find_elements(By.CLASS_NAME, value="widget-title") 16 | for section_title in latest_news: 17 | print(section_title.text) 18 | 19 | text_box = driver.find_element(by=By.CSS_SELECTOR, value="input#id-search-field") 20 | text_box.send_keys("selenium") 21 | 22 | submit_button = driver.find_element(by=By.NAME, value="submit") 23 | submit_button.click() 24 | 25 | driver.quit() 26 | 27 | -------------------------------------------------------------------------------- /Flask-server/decorator.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def delay_decorator(func): 4 | def wrapper_function(): 5 | time.sleep(2) 6 | # do something before 7 | func() 8 | # do something after 9 | return wrapper_function() 10 | 11 | # @ decorator wrap the function into it 12 | @delay_decorator 13 | def say_hello(): 14 | print("hello") 15 | 16 | @delay_decorator 17 | def say_bye(): 18 | print("bye") 19 | 20 | @delay_decorator 21 | def say_greeting(): 22 | print("greeting") 23 | 24 | # ------------------------------------------------------------ EXERCISE ------------------------------------------------------------ 25 | 26 | def speed_calc_decorator(function): 27 | def wrapper_function(): 28 | start_time = time.time() 29 | function() 30 | end_time = time.time() 31 | print(f"{function.__name__} run speed: {end_time - start_time}s") 32 | return wrapper_function 33 | 34 | @speed_calc_decorator 35 | def fast_function(): 36 | for i in range(10000000): 37 | i * i 38 | 39 | @speed_calc_decorator 40 | def slow_function(): 41 | for i in range(90000000): 42 | i * i 43 | 44 | fast_function() 45 | slow_function() -------------------------------------------------------------------------------- /Flask-server/hello.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | app = Flask(__name__) 3 | 4 | @app.route('/') #http://127.0.0.1:5000 5 | def hello_world(): 6 | return 'Hello, World!' 7 | 8 | @app.route('/second_page') #http://127.0.0.1:5000/second_page 9 | def hello_simon(): 10 | return 'Hello Simon!' 11 | 12 | if __name__ == "__main__": 13 | app.run() -------------------------------------------------------------------------------- /Flight-deals-API/data_manager.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | class DataManager: 4 | #This class is responsible for talking to the Google Sheet. 5 | def __init__(self): 6 | self.API_ENDPOINT = "YOUR_API_ENDPOINT_HERE" 7 | # { 8 | # 'prices': [ 9 | # {'city': 'Paris', 'iataCode': '', 'id': 2, 'lowestPrice': 54}, 10 | # {'city': 'Berlin', 'iataCode': '', 'id': 3, 'lowestPrice': 42}, 11 | # {'city': 'Tokyo', 'iataCode': '', 'id': 4, 'lowestPrice': 485}, 12 | # {'city': 'Sydney', 'iataCode': '', 'id': 5, 'lowestPrice': 551}, 13 | # {'city': 'Istanbul', 'iataCode': '', 'id': 6, 'lowestPrice': 95}, 14 | # {'city': 'Kuala Lumpur', 'iataCode': '', 'id': 7, 'lowestPrice': 414}, 15 | # {'city': 'New York', 'iataCode': '', 'id': 8, 'lowestPrice': 240}, 16 | # {'city': 'San Francisco', 'iataCode': '', 'id': 9, 'lowestPrice': 260}, 17 | # {'city': 'Cape Town', 'iataCode': '', 'id': 10, 'lowestPrice': 378} 18 | # ] 19 | # } 20 | 21 | def get_data(self): # return the value in "price" key 22 | get_response = requests.get(self.API_ENDPOINT) # request the data from sheety API 23 | get_response.raise_for_status() # raise error message if any error occurs 24 | self.data = get_response.json() # save the data into a dictionary 25 | return self.data["prices"] 26 | 27 | def update_data(self, iata_code_params, column_id): 28 | '''update the "IATA Code" column in Google sheet, iata_code_params, get the response from the FlightSearch class via main, column_id from main''' 29 | # define the data will be updated to Google sheet 30 | iata_code = { 31 | "price": { # "price" will be singular here, get the name from last word in API address 32 | "iataCode": iata_code_params, # update the "IATA Code" column in Google sheet, Sheety requires the column in Camel case, so -> "iataCode" 33 | } 34 | } 35 | put_response = requests.put(f"{self.API_ENDPOINT}/{str(column_id)}", json=iata_code) # put request to the Google sheet 36 | print(put_response.json()) # to see the response message -------------------------------------------------------------------------------- /Flight-deals-API/flight_data.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | import requests 3 | 4 | class FlightData: 5 | #This class is responsible for structuring the flight data. 6 | def __init__(self, destination): 7 | self.price = 0 8 | self.departure_airport_code = "LON" 9 | self.departure_city = "" 10 | self.destination = destination 11 | date_from = datetime.now() + timedelta(days=1) 12 | date_to = datetime.now() + timedelta(days=180) 13 | self.formatted_date_from = date_from.strftime("%d%m%Y") 14 | self.formatted_date_to = date_to.strftime("%d%m%Y") 15 | return_from = date_from + timedelta(days=7) 16 | return_to = date_to + timedelta(days=28) 17 | self.formatted_return_from = return_from.strftime("%d%m%Y") 18 | self.formatted_return_to = return_to.strftime("%d%m%Y") 19 | self.API_ENDPOINT = "YOUR_API_ENDPOINT_HERE" 20 | 21 | self.headers = { 22 | "apikey" : "YOUR_API_KEY_HERE", 23 | } 24 | 25 | self.api_params = { 26 | "fly_from" : self.departure_airport_code, 27 | "fly_to" : self.destination, 28 | "date_from" : self.formatted_date_from, 29 | "date_to" : self.formatted_date_to, 30 | "return_from" : self.formatted_return_from, 31 | "return_to" : self.formatted_return_to, 32 | } 33 | 34 | self.response = requests.get(self.API_ENDPOINT, params=self.api_params, headers=self.headers) 35 | self.response.raise_for_status() 36 | print("done") -------------------------------------------------------------------------------- /Flight-deals-API/flight_search.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | class FlightSearch: 4 | #This class is responsible for talking to the Flight Search API. 5 | def __init__(self, city): 6 | self.city = city 7 | self.API_ENDPOINT = "YOUR_API_ENDPOINT_HERE" 8 | self.API_KEY = "YOUR_API_KEY_HERE" 9 | 10 | def search_for_IATA_code(self): 11 | headers = { 12 | "apikey" : self.API_KEY, 13 | } 14 | 15 | params = { 16 | "term" : self.city 17 | } 18 | 19 | response = requests.get(self.API_ENDPOINT, params=params, headers=headers) 20 | response.raise_for_status() 21 | city_code = response.json()["locations"][0]["code"] 22 | return city_code -------------------------------------------------------------------------------- /Flight-deals-API/main.py: -------------------------------------------------------------------------------- 1 | #This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements. 2 | 3 | from data_manager import DataManager 4 | from flight_search import FlightSearch 5 | from flight_data import FlightData 6 | from pprint import pprint 7 | 8 | data_manager = DataManager() 9 | sheet_data = data_manager.get_data() 10 | 11 | # get the data from Google sheet 12 | # pprint(sheet_data.get_data()) 13 | # [ 14 | # {'city': 'Paris', 'iataCode': '', 'id': 2, 'lowestPrice': 54}, 15 | # {'city': 'Berlin', 'iataCode': '', 'id': 3, 'lowestPrice': 42}, 16 | # {'city': 'Tokyo', 'iataCode': '', 'id': 4, 'lowestPrice': 485}, 17 | # {'city': 'Sydney', 'iataCode': '', 'id': 5, 'lowestPrice': 551}, 18 | # {'city': 'Istanbul', 'iataCode': '', 'id': 6, 'lowestPrice': 95}, 19 | # {'city': 'Kuala Lumpur', 'iataCode': '', 'id': 7, 'lowestPrice': 414}, 20 | # {'city': 'New York', 'iataCode': '', 'id': 8, 'lowestPrice': 240}, 21 | # {'city': 'San Francisco', 'iataCode': '', 'id': 9, 'lowestPrice': 260}, 22 | # {'city': 'Cape Town', 'iataCode': '', 'id': 10, 'lowestPrice': 378} 23 | # ] 24 | 25 | for item in sheet_data: # iterate over "sheet_data" list 26 | # if item["iataCode"] == "": # check if the content in "iataCode" column is empty, then update the column 27 | # flight_search = FlightSearch(item["city"]) # get the data in "city" column 28 | # flight_search_result = flight_search.search_for_IATA_code() # get the iata_code 29 | # item["iataCode"] = flight_search_result # save the iata_code into the dictionary 30 | # data_manager.update_data(flight_search_result, item["id"]) 31 | FlightData(item["city"]) -------------------------------------------------------------------------------- /Flight-deals-API/notification_manager.py: -------------------------------------------------------------------------------- 1 | class NotificationManager: 2 | #This class is responsible for sending notifications with the deal flight details. 3 | pass -------------------------------------------------------------------------------- /Grading-system/main.py: -------------------------------------------------------------------------------- 1 | student_scores = { 2 | "Harry": 81, 3 | "Ron": 78, 4 | "Hermione": 99, 5 | "Draco": 74, 6 | "Neville": 62, 7 | } 8 | # 🚨 Don't change the code above 👆 9 | 10 | #TODO-1: Create an empty dictionary called student_grades. 11 | student_grades = {} 12 | 13 | #TODO-2: Write your code below to add the grades to student_grades.👇 14 | grade = "" 15 | for key in student_scores: 16 | score = student_scores[key] 17 | if 90 < score <= 100: 18 | grade = "Outstanding" 19 | elif 80 < score <= 90: 20 | grade = "Exceeds Expectations" 21 | elif 70 < score <= 80: 22 | grade = "Acceptable" 23 | else: 24 | grade="Fail" 25 | student_grades[key] = grade 26 | 27 | # 🚨 Don't change the code below 👇 28 | print(student_grades) 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Guessing-Number-Game/art.py: -------------------------------------------------------------------------------- 1 | logo = ''' 2 | ███████╗██╗███╗ ███╗ ██████╗ ███╗ ██╗ ██████╗ ██╗ ██╗███████╗███████╗███████╗██╗███╗ ██╗ ██████╗ ██████╗ █████╗ ███╗ ███╗███████╗ 3 | ██╔════╝██║████╗ ████║██╔═══██╗████╗ ██║ ██╔════╝ ██║ ██║██╔════╝██╔════╝██╔════╝██║████╗ ██║██╔════╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ 4 | ███████╗██║██╔████╔██║██║ ██║██╔██╗ ██║ ██║ ███╗██║ ██║█████╗ ███████╗███████╗██║██╔██╗ ██║██║ ███╗ ██║ ███╗███████║██╔████╔██║█████╗ 5 | ╚════██║██║██║╚██╔╝██║██║ ██║██║╚██╗██║ ██║ ██║██║ ██║██╔══╝ ╚════██║╚════██║██║██║╚██╗██║██║ ██║ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ 6 | ███████║██║██║ ╚═╝ ██║╚██████╔╝██║ ╚████║ ╚██████╔╝╚██████╔╝███████╗███████║███████║██║██║ ╚████║╚██████╔╝ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ 7 | ╚══════╝╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ 8 | 9 | ''' 10 | -------------------------------------------------------------------------------- /Guessing-Number-Game/main.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | from art import logo 3 | #Number Guessing Game Objectives: 4 | 5 | # Include an ASCII art logo. 6 | # Allow the player to submit a guess for a number between 1 and 100. 7 | # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. 8 | # If they got the answer correct, show the actual answer to the player. 9 | # Track the number of turns remaining. 10 | # If they run out of turns, provide feedback to the player. 11 | # Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode). 12 | 13 | print(logo) 14 | 15 | EASY_LEVEL = 10 16 | HARD_LEVEL = 5 17 | 18 | number_of_attempts = 0 19 | random_number = randint(1,100) 20 | 21 | print("Welcome to Simon's Guessing Number Game!") 22 | print("I'm thinking of a number between 1 and 100") 23 | print(f"The answer is {random_number}") 24 | 25 | def difficulty_level(): 26 | difficulty_level = input("Choose a difficulty level. Type 'easy' or 'hard': ") 27 | 28 | if difficulty_level == "easy": 29 | return EASY_LEVEL 30 | else: 31 | return HARD_LEVEL 32 | 33 | number_of_attempts = difficulty_level() 34 | 35 | repeat = True 36 | while repeat: 37 | print(f" You have {number_of_attempts} attempts remaining to guess") 38 | user_guess = int(input("Make a guess ----> ")) 39 | 40 | if (user_guess == random_number): 41 | print(f"You got it! The answer is {random_number}") 42 | repeat = False #or => break 43 | elif (user_guess < random_number): 44 | print("Too low, guess a higher number") 45 | number_of_attempts -= 1 46 | elif (user_guess > random_number): 47 | print("Too high, guess a lower number") 48 | number_of_attempts -= 1 49 | 50 | if number_of_attempts == 0: 51 | print("You lose the game, out of lives") 52 | repeat = False #or => break 53 | -------------------------------------------------------------------------------- /Hangman-game/.upm/store.json: -------------------------------------------------------------------------------- 1 | {"version":2,"languages":{"python-python3-poetry":{"specfileHash":"3f35379456299b96e2c9ab6a6ea323a2","lockfileHash":"8684d0af28309091d9216e1f02a7e5ba","guessedImportsHash":"42d8c8961523c25b27e29c68bc6fe62e"}}} 2 | -------------------------------------------------------------------------------- /Hangman-game/__pycache__/hangman_art.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Hangman-game/__pycache__/hangman_art.cpython-38.pyc -------------------------------------------------------------------------------- /Hangman-game/__pycache__/hangman_words.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Hangman-game/__pycache__/hangman_words.cpython-38.pyc -------------------------------------------------------------------------------- /Hangman-game/hangman_art.py: -------------------------------------------------------------------------------- 1 | stages = [''' 2 | +---+ 3 | | | 4 | O | 5 | /|\ | 6 | / \ | 7 | | 8 | ========= 9 | ''', ''' 10 | +---+ 11 | | | 12 | O | 13 | /|\ | 14 | / | 15 | | 16 | ========= 17 | ''', ''' 18 | +---+ 19 | | | 20 | O | 21 | /|\ | 22 | | 23 | | 24 | ========= 25 | ''', ''' 26 | +---+ 27 | | | 28 | O | 29 | /| | 30 | | 31 | | 32 | =========''', ''' 33 | +---+ 34 | | | 35 | O | 36 | | | 37 | | 38 | | 39 | ========= 40 | ''', ''' 41 | +---+ 42 | | | 43 | O | 44 | | 45 | | 46 | | 47 | ========= 48 | ''', ''' 49 | +---+ 50 | | | 51 | | 52 | | 53 | | 54 | | 55 | ========= 56 | '''] 57 | 58 | logo = ''' 59 | _ 60 | | | 61 | | |__ __ _ _ __ __ _ _ __ ___ __ _ _ __ 62 | | '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ 63 | | | | | (_| | | | | (_| | | | | | | (_| | | | | 64 | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| 65 | __/ | 66 | |___/ ''' 67 | 68 | 69 | -------------------------------------------------------------------------------- /Hangman-game/main.py: -------------------------------------------------------------------------------- 1 | #Step 5 2 | 3 | from replit import clear 4 | import random 5 | import hangman_words 6 | from hangman_art import stages, logo 7 | 8 | #TODO-1: - Update the word list to use the 'word_list' from hangman_words.py 9 | #Delete this line: word_list = ["ardvark", "baboon", "camel"] 10 | chosen_word = random.choice(hangman_words.word_list) 11 | word_length = len(chosen_word) 12 | 13 | end_of_game = False 14 | lives = 6 15 | 16 | #TODO-3: - Import the logo from hangman_art.py and print it at the start of the game. 17 | print(logo) 18 | #Testing code 19 | print(f'Pssst, the solution is {chosen_word}.') 20 | 21 | #Create blanks 22 | display = [] 23 | for _ in range(word_length): 24 | display += "_" 25 | 26 | while not end_of_game: 27 | guess = input("Guess a letter: ").lower() 28 | clear() 29 | 30 | #TODO-4: - If the user has entered a letter they've already guessed, print the letter and let them know. 31 | if guess in display: 32 | print("You've already guessed it") 33 | 34 | #Check guessed letter 35 | for position in range(word_length): 36 | letter = chosen_word[position] 37 | if letter == guess: 38 | display[position] = letter 39 | 40 | #Check if user is wrong. 41 | if guess not in chosen_word: 42 | #TODO-5: - If the letter is not in the chosen_word, print out the letter and let them know it's not in the word. 43 | print("You guessed " + guess + ", that's not in the word, You lose a life") 44 | lives -= 1 45 | if lives == 0: 46 | end_of_game = True 47 | print("You lose.") 48 | 49 | #Join all the elements in the list and turn it into a String. 50 | print(f"{' '.join(display)}") 51 | 52 | #Check if user has got all letters. 53 | if "_" not in display: 54 | end_of_game = True 55 | print("You win.") 56 | 57 | #TODO-2: - Import the stages from hangman_art.py and make this error go away. 58 | print(stages[lives]) -------------------------------------------------------------------------------- /Hangman-game/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "repl_python3_Day-7-Hangman-5-Start" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Your Name "] 6 | 7 | [tool.poetry.dependencies] 8 | python = "^3.8" 9 | replit = "^3.2.4" 10 | 11 | [tool.poetry.dev-dependencies] 12 | 13 | [build-system] 14 | requires = ["poetry-core>=1.0.0"] 15 | build-backend = "poetry.core.masonry.api" 16 | -------------------------------------------------------------------------------- /Higher-lower-game/__pycache__/art.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Higher-lower-game/__pycache__/art.cpython-310.pyc -------------------------------------------------------------------------------- /Higher-lower-game/__pycache__/game_data.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Higher-lower-game/__pycache__/game_data.cpython-310.pyc -------------------------------------------------------------------------------- /Higher-lower-game/art.py: -------------------------------------------------------------------------------- 1 | logo = """ 2 | __ ___ __ 3 | / / / (_)___ _/ /_ ___ _____ 4 | / /_/ / / __ `/ __ \/ _ \/ ___/ 5 | / __ / / /_/ / / / / __/ / 6 | /_/ ///_/\__, /_/ /_/\___/_/ 7 | / / /____/_ _____ _____ 8 | / / / __ \ | /| / / _ \/ ___/ 9 | / /___/ /_/ / |/ |/ / __/ / 10 | /_____/\____/|__/|__/\___/_/ 11 | """ 12 | 13 | vs = """ 14 | _ __ 15 | | | / /____ 16 | | | / / ___/ 17 | | |/ (__ ) 18 | |___/____(_) 19 | """ -------------------------------------------------------------------------------- /Higher-lower-game/main.py: -------------------------------------------------------------------------------- 1 | from art import logo, vs 2 | from random import choice 3 | from game_data import data 4 | from os import system 5 | 6 | def check_who_has_higher_follower(): 7 | if celebrity_A_follower_count > celebrity_B_follower_count: 8 | return "A" 9 | else: 10 | return "B" 11 | 12 | score = 0 13 | correct_message = "" 14 | incorrect_message = "" 15 | 16 | celebrity_A = choice(data) 17 | celebrity_A_name = celebrity_A["name"] 18 | celebrity_A_follower_count = celebrity_A["follower_counts"] 19 | celebrity_A_description = celebrity_A["description"] 20 | celebrity_A_country = celebrity_A["countries"] 21 | 22 | is_correct_answer = True 23 | while is_correct_answer: 24 | print(logo) 25 | print(correct_message) 26 | 27 | print(f"Compare A: {celebrity_A_name}, a {celebrity_A_description}, from {celebrity_A_country}") 28 | 29 | print(vs) 30 | 31 | celebrity_B = choice(data) 32 | celebrity_B_name = celebrity_B["name"] 33 | celebrity_B_follower_count = celebrity_B["follower_count"] 34 | celebrity_B_description = celebrity_B["description"] 35 | celebrity_B_country = celebrity_B["country"] 36 | 37 | print(f"Against B: {celebrity_B_name}, a {celebrity_B_description}, from {celebrity_B_country}") 38 | print("The answer is: ", check_who_has_higher_follower()) 39 | 40 | user_ans = input("Who have more followers? Type 'A' or 'B': ").upper() 41 | 42 | answer = check_who_has_higher_follower() 43 | 44 | if user_ans== answer: 45 | score += 1 46 | correct_message = f"You're right, current score: {score}" 47 | celebrity_A_name = celebrity_B["name"] 48 | celebrity_A_follower_count = celebrity_B["follower_count"] 49 | celebrity_A_description = celebrity_B["description"] 50 | celebrity_A_country = celebrity_B["country"] 51 | system("cls") 52 | else: 53 | is_correct_answer = False # or break 54 | incorrect_message = f"Sorry, that's wrong. Final score: {score}" 55 | system("cls") 56 | print(logo) 57 | print(incorrect_message) -------------------------------------------------------------------------------- /How-many-days-in-a-month/main.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | if year % 4 == 0: 3 | if year % 100 == 0: 4 | if year % 400 == 0: 5 | return True 6 | else: 7 | return False 8 | else: 9 | return True 10 | else: 11 | return False 12 | 13 | def days_in_month(year, month): 14 | month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 15 | if is_leap(year): 16 | days = 29 17 | else: 18 | days = month_days[month - 1] 19 | return days 20 | 21 | # ------------------------------------ OR --------------------------------- 22 | 23 | # if is_leap(year) and month == 2: 24 | # return 29 25 | # return month_days[month - 1] 26 | 27 | #🚨 Do NOT change any of the code below 28 | year = int(input("Enter a year: ")) 29 | month = int(input("Enter a month: ")) 30 | days = days_in_month(year, month) 31 | print(days) -------------------------------------------------------------------------------- /Leap-year-generator/main.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | year = int(input("Which year do you want to check? ")) 3 | # 🚨 Don't change the code above 👆 4 | 5 | #Write your code below this line 👇 6 | 7 | 8 | if year % 4 == 0: 9 | if year % 100 == 0: 10 | if year % 400 == 0: 11 | print("Leap Year.") 12 | else: 13 | print("Not leap year.") 14 | else: 15 | print("Leap year.") 16 | else: 17 | print("Not leap year.") 18 | -------------------------------------------------------------------------------- /Mail-merge-project/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Mail-merge-project/.DS_Store -------------------------------------------------------------------------------- /Mail-merge-project/Input/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Mail-merge-project/Input/.DS_Store -------------------------------------------------------------------------------- /Mail-merge-project/Input/Letters/starting_letter.txt: -------------------------------------------------------------------------------- 1 | Dear [name], 2 | 3 | You are invited to my birthday this Saturday. 4 | 5 | Hope you can make it! 6 | 7 | Angela 8 | -------------------------------------------------------------------------------- /Mail-merge-project/Input/Names/invited_names.txt: -------------------------------------------------------------------------------- 1 | Aang 2 | Zuko 3 | Appa 4 | Katara 5 | Sokka 6 | Momo 7 | Uncle Iroh 8 | Toph -------------------------------------------------------------------------------- /Mail-merge-project/Output/ReadyToSend/example.txt: -------------------------------------------------------------------------------- 1 | Dear [name], 2 | 3 | You are invited to my birthday this Saturday. 4 | 5 | Hope you can make it! 6 | 7 | Angela 8 | -------------------------------------------------------------------------------- /Message-encode-and-decode-generator/.upm/store.json: -------------------------------------------------------------------------------- 1 | {"version":2,"languages":{"python-python3-poetry":{"specfileHash":"23f1c8dc4b89e4cb52eaed7f30442b82","lockfileHash":"6bbb90b43e65890ea3697deec62d917c","guessedImportsHash":"2c5f64ab07ccb3e410aa97fc09687cc3"}}} 2 | -------------------------------------------------------------------------------- /Message-encode-and-decode-generator/__pycache__/art.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Message-encode-and-decode-generator/__pycache__/art.cpython-38.pyc -------------------------------------------------------------------------------- /Message-encode-and-decode-generator/art.py: -------------------------------------------------------------------------------- 1 | logo = """ 2 | ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, 3 | a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8 4 | 8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 5 | "8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 6 | `"Ybbd8"' `"8bbdP"Y8 `"Ybbd8"' `"YbbdP"' `"8bbdP"Y8 88 7 | 88 88 8 | "" 88 9 | 88 10 | ,adPPYba, 88 8b,dPPYba, 88,dPPYba, ,adPPYba, 8b,dPPYba, 11 | a8" "" 88 88P' "8a 88P' "8a a8P_____88 88P' "Y8 12 | 8b 88 88 d8 88 88 8PP""""""" 88 13 | "8a, ,aa 88 88b, ,a8" 88 88 "8b, ,aa 88 14 | `"Ybbd8"' 88 88`YbbdP"' 88 88 `"Ybbd8"' 88 15 | 88 16 | 88 17 | """ -------------------------------------------------------------------------------- /Message-encode-and-decode-generator/main.py: -------------------------------------------------------------------------------- 1 | import art 2 | 3 | alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 4 | print(len(alphabet)) 5 | print(999%26) 6 | 7 | def caesar(start_text, shift_amount, cipher_direction): 8 | end_text = "" 9 | if cipher_direction == "decode": 10 | shift_amount *= -1 # to get a negative number if user choose decode 11 | for char in start_text: 12 | #TODO-3: What happens if the user enters a number/symbol/space? 13 | #Can you fix the code to keep the number/symbol/space when the text is encoded/decoded? 14 | #e.g. start_text = "meet me at 3" 15 | #end_text = "•••• •• •• 3" 16 | if char in alphabet: 17 | position = alphabet.index(char) 18 | new_position = position + shift_amount 19 | end_text += alphabet[new_position] 20 | else: 21 | end_text += char 22 | 23 | print(f"Here's the {cipher_direction}d result: {end_text}") 24 | 25 | #TODO-1: Import and print the logo from art.py when the program starts. 26 | print(art.logo) 27 | 28 | #TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program? 29 | #e.g. Type 'yes' if you want to go again. Otherwise type 'no'. 30 | #If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again? 31 | #Hint: Try creating a while loop that continues to execute the program if the user types 'yes'. 32 | should_continue = True 33 | while should_continue: 34 | direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") 35 | text = input("Type your message:\n").lower() 36 | shift = int(input("Type the shift number:\n")) 37 | 38 | #TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet? 39 | #Try running the program and entering a shift number of 45. 40 | #Add some code so that the program continues to work even if the user enters a shift number greater than 26. 41 | #Hint: Think about how you can use the modulus (%). 42 | shift = shift % 26 43 | caesar(start_text = text, shift_amount = shift, cipher_direction = direction) 44 | 45 | result = input("Do you wanna continue to enter a new text?\n") 46 | if result == "no": 47 | should_continue = False 48 | print("Good Bye!!!") -------------------------------------------------------------------------------- /Message-encode-and-decode-generator/poetry.lock: -------------------------------------------------------------------------------- 1 | [[package]] 2 | name = "logo" 3 | version = "1.0.0" 4 | description = "" 5 | category = "main" 6 | optional = false 7 | python-versions = "*" 8 | 9 | [metadata] 10 | lock-version = "1.1" 11 | python-versions = "^3.8" 12 | content-hash = "25e62697c36eede5648df592a5522298d9e2f11784d27167cf6241e63d6d9f49" 13 | 14 | [metadata.files] 15 | logo = [ 16 | {file = "logo-1.0.0-py3-none-any.whl", hash = "sha256:77fdcc292c40a50bf74946a8fddb990c6f3a1437c91822786f48a46c06e779fc"}, 17 | ] 18 | -------------------------------------------------------------------------------- /Message-encode-and-decode-generator/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "repl_python3_caesar-cipher-4-start" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Your Name "] 6 | 7 | [tool.poetry.dependencies] 8 | python = "^3.8" 9 | logo = "^1.0.0" 10 | 11 | [tool.poetry.dev-dependencies] 12 | 13 | [build-system] 14 | requires = ["poetry-core>=1.0.0"] 15 | build-backend = "poetry.core.masonry.api" 16 | -------------------------------------------------------------------------------- /Miles-to-Kilometers-GUI-converter/main.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import * 3 | 4 | window = tk.Tk() 5 | window.title("Mile to KM Converter") 6 | window.minsize(width = 350, height = 320) # responsive to padding size on next line 7 | window.config(padx = 70, pady = 100) 8 | 9 | 10 | 11 | #? ----------------------------------- entry for miles ----------------------------------- 12 | miles_entry = tk.Entry(width = 10) 13 | miles_entry.insert(END, string = "0") 14 | miles_entry.grid(row = 0, column = 1) 15 | 16 | 17 | 18 | #? ----------------------------------- label for Miles ----------------------------------- 19 | mile_label = tk.Label(text = "Miles") 20 | mile_label.grid(row = 0, column = 2) 21 | 22 | 23 | 24 | #? ----------------------------------- label for is equal to ----------------------------------- 25 | is_equal_to_label = tk.Label(text = "is equal to") 26 | is_equal_to_label.grid(row = 1, column = 0) 27 | 28 | 29 | 30 | #? ----------------------------------- label for result ----------------------------------- 31 | result_label = tk.Label(text = "0") 32 | result_label.grid(row = 1, column = 1) 33 | 34 | 35 | 36 | #? ----------------------------------- label for km ----------------------------------- 37 | km_label = tk.Label(text = "Km") 38 | km_label.grid(row = 1, column = 2) 39 | 40 | 41 | #? ----------------------------------- button for calculate ----------------------------------- 42 | def convert(): 43 | # check if the input is integer 44 | try: 45 | result = float(miles_entry.get()) * 1.60934 # calculate the result from the entry input 46 | result_label.config(text = result) # write the calculation result into the result label 47 | error_label.config(text = "") # reset the error label if input is correct 48 | except: 49 | error_label.config(text = "*Please insert \n a valid number") 50 | 51 | 52 | calculate_button = tk.Button(text = "Calculate", command = convert) 53 | calculate_button.grid(row = 2, column = 1) 54 | 55 | 56 | #? ----------------------------------- label for input type error ----------------------------------- 57 | error_label = tk.Label(fg = 'red') 58 | error_label.grid(row = 3, column = 1) 59 | 60 | 61 | window.mainloop() -------------------------------------------------------------------------------- /NATO-alphabet/main.py: -------------------------------------------------------------------------------- 1 | # reference: Pandas-exercises\Pandas-iterate-over-dataframe.py 2 | 3 | from sys import stdlib_module_names 4 | import pandas as pd 5 | #TODO 1. Create a dictionary in this format: 6 | {"A": "Alfa", "B": "Bravo"} 7 | 8 | data = pd.read_csv("./nato_phonetic_alphabet.csv") 9 | 10 | # store the dataframe from csv file and convert into a new dictionary by using dictionary comprehension 11 | alpha_dict = {row.letter : row.code for index, row in data.iterrows()} 12 | 13 | 14 | #TODO 2. Create a list of the phonetic code words from a word that the user inputs. 15 | 16 | user_word = input("Input a word: ").upper() 17 | 18 | # find the user input from dictionary by letter 19 | result = [alpha_dict[letter] for letter in user_word] 20 | 21 | # #* in traditional way 22 | # result = [] 23 | # for letter in user_word: 24 | # result.append(alpha_dict[letter]) 25 | 26 | 27 | print(result) 28 | 29 | 30 | # example output: 31 | # input -> simon 32 | # output -> ['Sierra', 'India', 'Mike', 'Oscar', 'November'] -------------------------------------------------------------------------------- /NATO-alphabet/nato_phonetic_alphabet.csv: -------------------------------------------------------------------------------- 1 | letter,code 2 | A,Alfa 3 | B,Bravo 4 | C,Charlie 5 | D,Delta 6 | E,Echo 7 | F,Foxtrot 8 | G,Golf 9 | H,Hotel 10 | I,India 11 | J,Juliet 12 | K,Kilo 13 | L,Lima 14 | M,Mike 15 | N,November 16 | O,Oscar 17 | P,Papa 18 | Q,Quebec 19 | R,Romeo 20 | S,Sierra 21 | T,Tango 22 | U,Uniform 23 | V,Victor 24 | W,Whiskey 25 | X,X-ray 26 | Y,Yankee 27 | Z,Zulu -------------------------------------------------------------------------------- /OOP-coffee-machine/__pycache__/coffee_maker.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-coffee-machine/__pycache__/coffee_maker.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-coffee-machine/__pycache__/menu.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-coffee-machine/__pycache__/menu.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-coffee-machine/__pycache__/money_machine.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-coffee-machine/__pycache__/money_machine.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-coffee-machine/coffee_maker.py: -------------------------------------------------------------------------------- 1 | class CoffeeMaker: 2 | """Models the machine that makes the coffee""" 3 | def __init__(self): 4 | self.resources = { 5 | "water": 300, 6 | "milk": 200, 7 | "coffee": 100, 8 | } 9 | 10 | def report(self): 11 | """Prints a report of all resources.""" 12 | print(f"Water: {self.resources['water']}ml") 13 | print(f"Milk: {self.resources['milk']}ml") 14 | print(f"Coffee: {self.resources['coffee']}g") 15 | 16 | def is_resource_sufficient(self, drink): 17 | """Returns True when order can be made, False if ingredients are insufficient.""" 18 | can_make = True 19 | for item in drink.ingredients: 20 | if drink.ingredients[item] > self.resources[item]: 21 | print(f"Sorry there is not enough {item}.") 22 | can_make = False 23 | return can_make 24 | 25 | def make_coffee(self, order): 26 | """Deducts the required ingredients from the resources.""" 27 | for item in order.ingredients: 28 | self.resources[item] -= order.ingredients[item] 29 | print(f"Here is your {order.name} ☕️. Enjoy!") 30 | -------------------------------------------------------------------------------- /OOP-coffee-machine/main.py: -------------------------------------------------------------------------------- 1 | from menu import Menu, MenuItem 2 | from coffee_maker import CoffeeMaker 3 | from money_machine import MoneyMachine 4 | 5 | money_machine = MoneyMachine() 6 | coffee_maker = CoffeeMaker() 7 | menu = Menu() 8 | 9 | is_machine_on = True 10 | 11 | while is_machine_on: 12 | options = menu.get_items() 13 | choice = input(f"What would you like? ({options})") 14 | if choice == "off": 15 | is_machine_on = False 16 | elif choice == "report": 17 | coffee_maker.report() 18 | money_machine.report() 19 | else: 20 | drink = menu.find_drink(choice) 21 | if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost): 22 | coffee_maker.make_coffee(drink) -------------------------------------------------------------------------------- /OOP-coffee-machine/menu.py: -------------------------------------------------------------------------------- 1 | class MenuItem: 2 | """Models each Menu Item.""" 3 | def __init__(self, name, water, milk, coffee, cost): 4 | self.name = name 5 | self.cost = cost 6 | self.ingredients = { 7 | "water": water, 8 | "milk": milk, 9 | "coffee": coffee 10 | } 11 | 12 | 13 | class Menu: 14 | """Models the Menu with drinks.""" 15 | def __init__(self): 16 | self.menu = [ 17 | MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5), 18 | MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5), 19 | MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3), 20 | ] 21 | 22 | def get_items(self): 23 | """Returns all the names of the available menu items""" 24 | options = "" 25 | for item in self.menu: 26 | options += f"{item.name}/" 27 | return options 28 | 29 | def find_drink(self, order_name): 30 | """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None""" 31 | for item in self.menu: 32 | if item.name == order_name: 33 | return item 34 | print("Sorry that item is not available.") 35 | -------------------------------------------------------------------------------- /OOP-coffee-machine/money_machine.py: -------------------------------------------------------------------------------- 1 | class MoneyMachine: 2 | 3 | CURRENCY = "$" 4 | 5 | COIN_VALUES = { 6 | "quarters": 0.25, 7 | "dimes": 0.10, 8 | "nickles": 0.05, 9 | "pennies": 0.01 10 | } 11 | 12 | def __init__(self): 13 | self.profit = 0 14 | self.money_received = 0 15 | 16 | def report(self): 17 | """Prints the current profit""" 18 | print(f"Money: {self.CURRENCY}{self.profit}") 19 | 20 | def process_coins(self): 21 | """Returns the total calculated from coins inserted.""" 22 | print("Please insert coins.") 23 | for coin in self.COIN_VALUES: 24 | self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin] 25 | return self.money_received 26 | 27 | def make_payment(self, cost): 28 | """Returns True when payment is accepted, or False if insufficient.""" 29 | self.process_coins() 30 | if self.money_received >= cost: 31 | change = round(self.money_received - cost, 2) 32 | print(f"Here is {self.CURRENCY}{change} in change.") 33 | self.profit += cost 34 | self.money_received = 0 35 | return True 36 | else: 37 | print("Sorry that's not enough money. Money refunded.") 38 | self.money_received = 0 39 | return False 40 | -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/__pycache__/item.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-abstraction, polymorphism/__pycache__/item.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/__pycache__/keyboard.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-abstraction, polymorphism/__pycache__/keyboard.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/__pycache__/phone.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-abstraction, polymorphism/__pycache__/phone.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/abstraction_example.py: -------------------------------------------------------------------------------- 1 | from item import Item 2 | from phone import Phone 3 | 4 | 5 | item1 = Item("Item 1", 500, 5) 6 | 7 | # abstraction example 8 | # this three methods are not accessible because they are private 9 | item1.__connect_smtp("A") 10 | item1.__write_email() 11 | item1.__upload_image() 12 | 13 | # but ou can call the public method that calls the private methods 14 | item1.send_email() 15 | 16 | -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/item.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | class Item: 4 | pay_rate = 0.8 5 | 6 | def __init__(self, name: str, price: float, quantity = 0): 7 | 8 | assert price >= 0, f"Price {price} cannot be negative value" 9 | assert quantity >= 0, f"Quantity {quantity} cannot be negative value" 10 | 11 | self.__name = name 12 | self.__price = price 13 | self.quantity = quantity 14 | 15 | def apply_discount(self): 16 | self.__price = self.__price * self.pay_rate # if no instance level pay_rate being assigned, it will get it from class level, line 5 17 | 18 | @property 19 | def price(self): 20 | return self.__price 21 | -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/keyboard.py: -------------------------------------------------------------------------------- 1 | from item import Item 2 | 3 | class Keyboard(Item): 4 | 5 | pay_rate = 0.5 # redefine the pay_rate in Item (parent class) because of polymorphism 6 | 7 | def __init__(self, name: str, price: float, quantity = 0): 8 | super().__init__(name, price, quantity) -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/phone.py: -------------------------------------------------------------------------------- 1 | from item import Item 2 | 3 | class Phone(Item): 4 | 5 | def __init__(self, name: str, price: float, quantity = 0, broken_phone = 0): 6 | # call for super() function to access all attributes and methods parent class 7 | super().__init__(name, price, quantity) 8 | 9 | # add some code only for this class but not existed in parent class 10 | assert quantity >= 0, f"Broken phone {broken_phone} cannot be negative value" 11 | self.broken_phone = broken_phone -------------------------------------------------------------------------------- /OOP-exercises/OOP-abstraction, polymorphism/polymophism_example.py: -------------------------------------------------------------------------------- 1 | name = "Simon" 2 | from keyboard import Keyboard 3 | 4 | 5 | print(len(name)) 6 | 7 | list = ["Hello", "World"] 8 | print(len(list)) 9 | 10 | # see the len(), a built-in function can received different data type as its arguments 11 | # or we say it can handle different kinds of objects 12 | 13 | ########################################################################## 14 | item1 = Keyboard("Keyboard 1", 10, 2) 15 | 16 | # instance of Keyboard class can access `apply_discount()` method in Item class and redefine the pay_rate because of polymorphism 17 | print(item1.price) 18 | item1.apply_discount() 19 | print(item1.price) -------------------------------------------------------------------------------- /OOP-exercises/OOP-bacis-example/main.py: -------------------------------------------------------------------------------- 1 | class User: 2 | def __init__(self, user_id, user_name): 3 | print("New user has been created....") 4 | self.id = user_id 5 | self.name = user_name 6 | self.followers = 0 7 | self.following = 0 8 | 9 | 10 | def follow(self, user): 11 | self.following += 1 12 | user.followers += 1 13 | 14 | user_1 = User("001", "simon") 15 | user_2 = User("002", "chong") 16 | 17 | user_1.follow(user_2) 18 | 19 | print(user_1.followers) 20 | print(user_1.following) 21 | print(user_2.followers) 22 | print(user_2.following) 23 | -------------------------------------------------------------------------------- /OOP-exercises/OOP-class attribute vs instance attribute, __dict__ magic method/main.py: -------------------------------------------------------------------------------- 1 | class Item: 2 | pay_rate = 0.8 # The pay rate after 20% discount, this is a class attribute that not belong to any instance/object 3 | # but still it still can be accessed via an instance 4 | def __init__(self, name: str, price: float, quantity = 0): 5 | # self is the created instance itself like in line 27 => item1 6 | # "name: str" is to set the datatype of parameter to avoid int as the argument input mistake 7 | # "quantity = 0" is also to set the datatype and initialize the parameter value at the same time 8 | 9 | # in order to avoid unwanted data, e.g: a negative value being passed into parameter price and quantity, 10 | # use "assert" to do a data validation before it get processed 11 | # the string is the error message will be show if unwanted data being passed into this class constructor 12 | assert price >= 0, f"Price {price} cannot be negative value" 13 | assert quantity >= 0, f"Quantity {quantity} cannot be negative value" 14 | 15 | self.name = name 16 | self.price = price 17 | self.quantity = quantity 18 | 19 | def calculated_total_price(self): 20 | return self.price * self.quantity 21 | 22 | def apply_discount(self): 23 | self.price = self.price * self.pay_rate # instead od using "Item.pay_rate", since item2 has its own discount rate, 24 | # so we can use self here, item1 will retrieve the pay_rate from class level because it doesn't has 1 25 | 26 | item1 = Item("Phone", 100, 10) 27 | 28 | # use this magic method to debug 29 | # print all attribute in class level 30 | print(Item.__dict__) 31 | # print all attribute in instance level 32 | print(item1.__dict__) 33 | 34 | # to access class level attribute 35 | print(Item.pay_rate) 36 | # item1 is still able to access class attribute when they cannot find their own attribute in their own instance 37 | print(item1.pay_rate) 38 | 39 | print(item1.name, "Before discount RM", item1.calculated_total_price()) 40 | item1.apply_discount() 41 | print(item1.name, "After discounted RM", item1.calculated_total_price()) 42 | 43 | # let say you have a different discount rate for item2, so we can specify the pay_rate for its own instance only 44 | item2 = Item("Laptop", 400, 2) 45 | item2.pay_rate = 0.7 46 | print(item2.name, "Before discount RM", item2.calculated_total_price()) 47 | item2.apply_discount() 48 | print(item2.name, "After discounted RM", item2.calculated_total_price()) 49 | -------------------------------------------------------------------------------- /OOP-exercises/OOP-construtor, instance, attribute, method, assert/main.py: -------------------------------------------------------------------------------- 1 | class Item: 2 | def __init__(self, name: str, price: float, quantity = 0): 3 | # self is the created instance itself like in line 22 => item1 4 | # "name: str" is to set the datatype of parameter to avoid int as the argument input mistake 5 | # "quantity = 0" is also to set the datatype and initialize the parameter value at the same time 6 | 7 | # in order to avoid unwanted data, e.g: a negative value being passed into parameter price and quantity, 8 | # use "assert" to do a data validation before it get processed 9 | # the string is the error message will be show if unwanted data being passed into this class constructor 10 | assert price >= 0, f"Price {price} cannot be negative value" 11 | assert quantity >= 0, f"Quantity {quantity} cannot be negative value" 12 | 13 | self.name = name 14 | self.price = price 15 | self.quantity = quantity 16 | 17 | def calculated_total_price(self): 18 | return self.price * self.quantity 19 | 20 | item1 = Item("Phone", 100, 7) 21 | #*same as .... 22 | # item1.name = "Phone" 23 | # item1.price = 100 24 | # item1.quantity = 5 25 | 26 | item2 = Item("Laptop", 400, 2) 27 | # same as .... 28 | # item2.name = "Laptop" 29 | # item2.price = 400 30 | # item2.quantity = 2 31 | item2.has_numpad = True # we still can create and assign an new attribute to an existing instance although 32 | # it is not been initialized in the __init__ class, for example here, we wanna see does the laptop has a 33 | # numpad, but phone doesn't have this stuff, so it is better to create and assign it to a single 34 | # instance -> item2 which is laptop only 35 | 36 | print(item1.name) 37 | print(item2.name) 38 | print(item1.price) 39 | print(item2.price) 40 | print(item1.quantity) 41 | print(item2.quantity) 42 | 43 | print(item1.calculated_total_price()) 44 | print(item2.calculated_total_price()) -------------------------------------------------------------------------------- /OOP-exercises/OOP-getter & setter, encapsulation/__pycache__/item.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-getter & setter, encapsulation/__pycache__/item.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-getter & setter, encapsulation/__pycache__/phone.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-getter & setter, encapsulation/__pycache__/phone.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-getter & setter, encapsulation/main.py: -------------------------------------------------------------------------------- 1 | from item import Item 2 | 3 | item1 = Item("My Item", 750) 4 | 5 | #! can't access this attribute because it is private 6 | # print(item1.__name) 7 | 8 | #! but you can access via its getter 9 | print(item1.name) # this is the getter method, line 29 @property -> `name()` 10 | 11 | #! can't edit this attribute because it is private 12 | # item1.__name = "New name" 13 | # print(item1.__name) 14 | 15 | #! but you can edit it via its setter 16 | item1.name = "New name" # this is the setter method, line 36 @name.setter-> `name()` 17 | print(item1.name) -------------------------------------------------------------------------------- /OOP-exercises/OOP-inheritance/__pycache__/item.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-inheritance/__pycache__/item.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-inheritance/__pycache__/phone.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-exercises/OOP-inheritance/__pycache__/phone.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-exercises/OOP-inheritance/item.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | class Item: 4 | 5 | def __init__(self, name: str, price: float, quantity = 0): 6 | # self is the created instance itself 7 | # "name: str" is to set the datatype of parameter to avoid int as the argument input mistake 8 | # "quantity = 0" is also to set the datatype and initialize the parameter value at the same time 9 | 10 | # in order to avoid unwanted data, e.g: a negative value being passed into parameter price and quantity, 11 | # use "assert" to do a data validation before it get processed 12 | # the fstring is the error message will be show if unwanted data being passed into this class constructor 13 | assert price >= 0, f"Price {price} cannot be negative value" 14 | assert quantity >= 0, f"Quantity {quantity} cannot be negative value" 15 | 16 | self.name = name 17 | self.price = price 18 | self.quantity = quantity 19 | -------------------------------------------------------------------------------- /OOP-exercises/OOP-inheritance/main.py: -------------------------------------------------------------------------------- 1 | from item import Item 2 | from phone import Phone 3 | 4 | 5 | # we still can set/use the attributes in Item (parent class) by its constructor through Phone (child class) instance 6 | phone1 = Phone("jscPhone10", 500, 5, 1) 7 | 8 | # we still can access the attributes in Item (parent class) by the Phone instance 9 | print(phone1.price) 10 | print(phone1.name) -------------------------------------------------------------------------------- /OOP-exercises/OOP-inheritance/phone.py: -------------------------------------------------------------------------------- 1 | from item import Item 2 | 3 | class Phone(Item): 4 | 5 | def __init__(self, name: str, price: float, quantity = 0, broken_phone = 0): 6 | # call for super() function to access all attributes and methods parent class 7 | super().__init__(name, price, quantity) 8 | 9 | # add some code only for this class but not existed in parent class 10 | assert quantity >= 0, f"Broken phone {broken_phone} cannot be negative value" 11 | self.broken_phone = broken_phone -------------------------------------------------------------------------------- /OOP-exercises/OOP-inheritance/test.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def __init__(self) -> None: 3 | # print("A") 4 | pass 5 | 6 | def fun(self): 7 | print("A function") 8 | 9 | class B(A): 10 | def __init__(self) -> None: 11 | super().__init__() 12 | # print("B") 13 | pass 14 | 15 | def fun(self): 16 | super().fun() 17 | print("B function") 18 | 19 | a = A() 20 | b = B() 21 | 22 | b.fun() -------------------------------------------------------------------------------- /OOP-exercises/OOP-instantiate from CSV, class method, static method/item.csv: -------------------------------------------------------------------------------- 1 | name,price,quantity 2 | "Phone",100,1 3 | "Laptop",1000.5,3 4 | "Cable",10.5,5 5 | "Mouse",50,5 6 | "Keyboard",75.5,5 -------------------------------------------------------------------------------- /OOP-exercises/OOP-save instance into class level list, __repr__ magic method/main.py: -------------------------------------------------------------------------------- 1 | class Item: 2 | pay_rate = 0.8 # The pay rate after 20% discount, this is a class attribute that not belong to any instance/object 3 | # but still it still can be accessed via an instance 4 | all_items = [] 5 | 6 | 7 | def __init__(self, name: str, price: float, quantity = 0): 8 | # self is the created instance itself like in line 27 => item1 9 | # "name: str" is to set the datatype of parameter to avoid int as the argument input mistake 10 | # "quantity = 0" is also to set the datatype and initialize the parameter value at the same time 11 | 12 | # in order to avoid unwanted data, e.g: a negative value being passed into parameter price and quantity, 13 | # use "assert" to do a data validation before it get processed 14 | # the string is the error message will be show if unwanted data being passed into this class constructor 15 | assert price >= 0, f"Price {price} cannot be negative value" 16 | assert quantity >= 0, f"Quantity {quantity} cannot be negative value" 17 | 18 | self.name = name 19 | self.price = price 20 | self.quantity = quantity 21 | 22 | # adding all the item into a class level list 23 | Item.all_items.append(self) 24 | 25 | 26 | def calculated_total_price(self): 27 | return self.price * self.quantity 28 | 29 | 30 | def apply_discount(self): 31 | self.price = self.price * self.pay_rate # if no instance level pay_rate being assigned, it will get it from class level, line 2 32 | 33 | def __repr__(self): # an iterate => representing magic method, return all the existing instances in string form instead of like the result in line 44 34 | return f"...line 34...Item('{self.name}', {self.price}, {self.quantity}" 35 | 36 | 37 | item1 = Item("Phone", 100, 1) 38 | item2 = Item("Laptop", 1000, 3) 39 | item3 = Item("Cable", 10, 5) 40 | item4 = Item("Mouse", 50, 5) 41 | item5 = Item("Keyboard", 75, 5) 42 | 43 | # check if all items instance have been passed into the list, line 23 44 | print(Item.all_items) 45 | 46 | # print all instance attribute from all_items list that has been assigned in line 21 47 | for instance in Item.all_items: 48 | print(f"\n----Item name: {instance.name}") 49 | print(f" Item price: {instance.price}") 50 | print(f" Item quantity: {instance.quantity}") -------------------------------------------------------------------------------- /OOP-exercises/OOP-turtle-package/main.py: -------------------------------------------------------------------------------- 1 | # from turtle import Turtle, Screen 2 | 3 | # new_turtle = Turtle() 4 | # print(new_turtle) 5 | # new_turtle.shape("turtle") 6 | # new_turtle.color("black", "chartreuse") 7 | # new_turtle.forward(100) 8 | 9 | # my_screen = Screen() 10 | # print(my_screen.canvheight) 11 | # my_screen.exitonclick() 12 | 13 | 14 | from prettytable import PrettyTable 15 | 16 | new_table = PrettyTable() 17 | new_table.add_column("Pokemon Name", ["Pikachu", "Squirtle", "Charmander"]) 18 | new_table.add_column("Type", ["Electirc", "Water", "Fire"]) 19 | new_table.align = "l" 20 | 21 | print(new_table.get_string()) # convert into string form 22 | print(new_table) # print in ASCII form -------------------------------------------------------------------------------- /OOP-quiz-game/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "Backrub" 4 | ] 5 | } -------------------------------------------------------------------------------- /OOP-quiz-game/__pycache__/data.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-quiz-game/__pycache__/data.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-quiz-game/__pycache__/question_model.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-quiz-game/__pycache__/question_model.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-quiz-game/__pycache__/quiz_brain.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/OOP-quiz-game/__pycache__/quiz_brain.cpython-310.pyc -------------------------------------------------------------------------------- /OOP-quiz-game/data.py: -------------------------------------------------------------------------------- 1 | question_data = [ 2 | {"text": "A slug's blood is green.", "answer": "True"}, 3 | {"text": "The loudest animal is the African Elephant.", "answer": "False"}, 4 | {"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"}, 5 | {"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"}, 6 | {"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", "answer": "True"}, 7 | {"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.", "answer": "False"}, 8 | {"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"}, 9 | {"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"}, 10 | {"text": "Google was originally called 'Backrub'.", "answer": "True"}, 11 | {"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"}, 12 | {"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"}, 13 | {"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"} 14 | ] -------------------------------------------------------------------------------- /OOP-quiz-game/main.py: -------------------------------------------------------------------------------- 1 | from question_model import Question 2 | from data import question_data 3 | from quiz_brain import QuizBrain 4 | from quiz_brain import QuizBrain 5 | 6 | question_bank= [] 7 | 8 | for question in question_data: 9 | text = question["text"] 10 | answer = question["answer"] 11 | new_question = Question(text, answer) 12 | question_bank.append(new_question) 13 | 14 | quiz = QuizBrain(question_bank) 15 | 16 | while quiz.still_has_questions(): 17 | quiz.next_question() 18 | quiz.print_final_score() -------------------------------------------------------------------------------- /OOP-quiz-game/question_model.py: -------------------------------------------------------------------------------- 1 | class Question: 2 | def __init__(self, text, answer): 3 | self.text = text 4 | self.answer = answer -------------------------------------------------------------------------------- /OOP-quiz-game/quiz_brain.py: -------------------------------------------------------------------------------- 1 | class QuizBrain: 2 | def __init__(self, questions): 3 | self.question_number = 0 4 | self.question_list = questions 5 | self.score = 0 6 | 7 | def next_question(self): 8 | current_question = self.question_list[self.question_number] 9 | self.question_number += 1 10 | user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False): ") 11 | self.check_answer(user_answer, current_question.answer) 12 | 13 | def still_has_questions(self): 14 | return self.question_number < len(self.question_list) 15 | 16 | def check_answer(self, user_answer, correct_answer): 17 | if user_answer.lower() == correct_answer.lower(): 18 | print("You got it right!") 19 | self.score += 1 20 | else: 21 | print("That's wrong, sorry.") 22 | print(f"The correct answer was: {correct_answer}") 23 | print(f"Your current score is {self.score} / {self.question_number}") 24 | print("\n") 25 | 26 | def print_final_score(self): 27 | print("Congratulation! You've completed the quiz") 28 | print(f"Your final score was: {self.score} / {self.question_number}") 29 | 30 | -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-iterate-over-dataframe.py: -------------------------------------------------------------------------------- 1 | student_dict = { 2 | "student" : ["Simon", "James", "Lily"], 3 | "score" : [56, 76, 98] 4 | } 5 | 6 | # # ------------------------------------------------------------- loop through dictionary ----------------------------------------------- 7 | for key, value in student_dict.items(): 8 | print(key, value) 9 | # student ['Simon', 'James', 'Lily'] 10 | # score [56, 76, 98] 11 | 12 | import pandas as pd 13 | student_dataframe = pd.DataFrame(student_dict) 14 | 15 | print(student_dataframe) 16 | # student score 17 | # 0 Simon 56 18 | # 1 James 76 19 | # 2 Lily 98 20 | 21 | # # #------------------------------------------------------------- loop through data frame ------------------------------------------------------------- 22 | for key, value in student_dataframe.items(): 23 | print(key) 24 | # student 25 | # score 26 | 27 | print(value) 28 | # 0 Simon 29 | # 1 James 30 | # 2 Lily 31 | # Name: student, dtype: object 32 | # 0 56 33 | # 1 76 34 | # 2 98 35 | # Name: score, dtype: int64 36 | 37 | 38 | # # ------------------------------------------------------------- loop through rows of dataframe ------------------------------------------------------------- 39 | for index, row in student_dataframe.iterrows(): 40 | print(row) 41 | # student Simon 42 | # score 56 43 | # Name: 0, dtype: object 44 | # student James 45 | # score 76 46 | # Name: 1, dtype: object 47 | # student Lily 48 | # score 98 49 | # Name: 2, dtype: object 50 | 51 | print(row.student) 52 | # Simon 53 | # James 54 | # Lily 55 | 56 | print(row.score) 57 | # 56 58 | # 76 59 | # 98 60 | 61 | if (row.student == "Simon"): 62 | print(row.score) 63 | # 56 -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-read-column-from-csv/weather_data.csv: -------------------------------------------------------------------------------- 1 | day,temp,condition 2 | Monday,12,Sunny 3 | Tuesday,14,Rain 4 | Wednesday,15,Rain 5 | Thursday,14,Cloudy 6 | Friday,21,Sunny 7 | Saturday,22,Sunny 8 | Sunday,24,Sunny -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-read-row, mean, max, write-csv-data/main.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | data = pd.read_csv("./weather_data.csv") # the data will be in both dictionary and object forms 4 | # print(data["day"]) 5 | # 0 Monday 6 | # 1 Tuesday 7 | # 2 Wednesday 8 | # 3 Thursday 9 | # 4 Friday 10 | # 5 Saturday 11 | # 6 Sunday 12 | # Name: day, dtype: object 13 | 14 | # # convert into dictionary 15 | # data_dict = data.to_dict() 16 | # print(data_dict) 17 | # # {'day': {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}, 'temp': {0: 12, 1: 14, 2: 15, 3: 14, 4: 21, 5: 22, 6: 24}, 'condition': {0: 'Sunny', 1: 'Rain', 2: 'Rain', 3: 'Cloudy', 4: 'Sunny', 5: 'Sunny', 6: 'Sunny'}} 18 | 19 | # #* you are allow convert the data under "temp" column into list 20 | # temp_list = data["temp"].to_list() 21 | #* or 22 | # print(temp_list) 23 | 24 | #? get data in column 25 | # read all data under "temp" column 26 | # print(data["temp"]) # in dictionary form 27 | # #* or 28 | # print(data.temp) # in object form 29 | 30 | # print(data["temp"].mean()) # calculate the mean 31 | # print(data["temp"].max()) # get the max 32 | 33 | #? get data in row 34 | # read the row where day="monday" 35 | # print(data[data["day"] == "Monday"]) 36 | #* or 37 | print(data[data.day == "Monday"]) 38 | 39 | # get the row with the max temperature 40 | print(data[data.temp == data.temp.max()]) 41 | 42 | # get condition data on Monday 43 | monday = data[data.day == "Monday"] # get the row of Monday 44 | print(monday.condition) # get the condition data on Monday 45 | 46 | # convert temperature on Wednesday from celsius into fahrenheit 47 | wednesday = data[data.day == "Wednesday"] # get the row of Wednesday 48 | wednesday_temp = int(wednesday.temp) # convert into integer 49 | wednesday_temp_in_fahrenheit = wednesday_temp * 9 / 5 + 32 # converting formula 50 | print(wednesday_temp_in_fahrenheit) 51 | 52 | 53 | #? create dataframe from scratch 54 | data_dict = { 55 | "students" : ["Simon", "Peter", "Janet"], 56 | "scores": [76, 56, 65] 57 | } 58 | new_data = pd.DataFrame(data_dict) 59 | print(new_data) 60 | 61 | #? convert into csv file 62 | new_data.to_csv("new_data.csv") -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-read-row, mean, max, write-csv-data/new_data.csv: -------------------------------------------------------------------------------- 1 | ,students,scores 2 | 0,Simon,76 3 | 1,Peter,56 4 | 2,Janet,65 5 | -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-read-row, mean, max, write-csv-data/weather_data.csv: -------------------------------------------------------------------------------- 1 | day,temp,condition 2 | Monday,12,Sunny 3 | Tuesday,14,Rain 4 | Wednesday,15,Rain 5 | Thursday,14,Cloudy 6 | Friday,21,Sunny 7 | Saturday,22,Sunny 8 | Sunday,24,Sunny -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-squirrel-dataset/main.py: -------------------------------------------------------------------------------- 1 | # this program is to count the number of squirrel in different number from the dataset 2 | 3 | import pandas as pd 4 | 5 | squirrel_data_set = pd.read_csv("./2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv") 6 | 7 | fur_color = squirrel_data_set["Primary Fur Color"] # extract all the data under "Primary Fur Color" column 8 | grey_fur_color = squirrel_data_set[fur_color == "Gray"] # look for all the rows with the "Gray" from "Primary Fur Color" column 9 | # grey_fur_color["Primary Fur Color"] # get the all rows only for "Primary Fur Color" column 10 | grey_squirrel_count = len(grey_fur_color) 11 | 12 | red_fur_color = squirrel_data_set[fur_color == "Cinnamon"] 13 | red_squirrel_count = len(red_fur_color) 14 | 15 | black_fur_color = squirrel_data_set[fur_color == "Black"] 16 | black_squirrel_count = len(black_fur_color) 17 | 18 | print(grey_squirrel_count) 19 | print(red_squirrel_count) 20 | print(black_squirrel_count) 21 | 22 | # construct dataframe and save into a csv file 23 | data_dict = { 24 | "Fur Color" : ["Gray", "Cinnamon", "Black"], 25 | "Count" : [grey_squirrel_count, red_squirrel_count, black_squirrel_count] 26 | } 27 | 28 | squirrel_dataframe = pd.DataFrame(data_dict) # construct it into a dataframe 29 | squirrel_dataframe.to_csv("squirrel_count.csv") # convert into csv file -------------------------------------------------------------------------------- /Pandas-exercises/Pandas-squirrel-dataset/squirrel_count.csv: -------------------------------------------------------------------------------- 1 | ,Fur Color,Count 2 | 0,Gray,2473 3 | 1,Cinnamon,392 4 | 2,Black,103 5 | -------------------------------------------------------------------------------- /Pizza-ordering/main.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | print("Welcome to Python Pizza Deliveries!") 3 | size = input("What size pizza do you want? S, M, or L ") 4 | add_pepperoni = input("Do you want pepperoni? Y or N ") 5 | extra_cheese = input("Do you want extra cheese? Y or N ") 6 | # 🚨 Don't change the code above 👆 7 | 8 | #Write your code below this line 👇 9 | 10 | bill = 0 11 | 12 | if size == "S": 13 | bill += 15 14 | elif size == "M": 15 | bill += 20 16 | elif size == "L": 17 | bill += 25 18 | 19 | if add_pepperoni == "Y": 20 | if size == "S": 21 | bill += 2 22 | else: 23 | bill += 3 24 | 25 | if extra_cheese == "Y": 26 | bill += 1 27 | 28 | print(f"Your final bill is: ${bill}") -------------------------------------------------------------------------------- /Pomodoro-timer/tomato.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Pomodoro-timer/tomato.png -------------------------------------------------------------------------------- /Pong-game/Difference between with inheritance and without inherintance Turtle class.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Pong-game/Difference between with inheritance and without inherintance Turtle class.png -------------------------------------------------------------------------------- /Pong-game/ball.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | from random import randint 3 | 4 | 5 | 6 | class Ball(Turtle): 7 | def __init__(self): 8 | super().__init__() 9 | self.shape("circle") 10 | self.color("white") 11 | self.penup() 12 | self.x_move = 0.1 # initialize the x axis moving speed of the ball 13 | self.y_move = 0.1 # initialize the y axis moving speed of the ball 14 | 15 | def move(self): 16 | new_x = self.xcor() + self.x_move # updated the x moving direction 17 | new_y = self.ycor() + self.y_move # updated the y moving direction 18 | self.goto(new_x, new_y) 19 | 20 | def bounce_x(self): 21 | self.x_move *= -1 # reverse the x direction, negative to positive, vice versa 22 | 23 | def bounce_y(self): 24 | self.y_move *= -1 # reverse the y direction, negative to positive, vice versa 25 | 26 | def reset_position(self): 27 | self.goto(0, 0) 28 | self.bounce_x() -------------------------------------------------------------------------------- /Pong-game/main.py: -------------------------------------------------------------------------------- 1 | from turtle import Screen, done 2 | from paddle import Paddle 3 | from ball import Ball 4 | from scoreboard import ScoreBoard 5 | 6 | screen = Screen() 7 | screen.bgcolor("black") 8 | screen.setup(width = 1200, height = 800) 9 | screen.title("Pong Pong Pong!!!") 10 | screen.tracer(0) # turn off the animation when paddle moving to edge/initial position 11 | 12 | left_paddle = Paddle((-550, 0)) # pass the x and y coordinate in a tuple 13 | right_paddle = Paddle((550, 0)) # pass the x and y coordinate in a tuple 14 | 15 | screen.listen() 16 | screen.onkey(left_paddle.go_up, "w") # call go_up function without the parentheses 17 | screen.onkey(left_paddle.go_down, "s") # call go_down function without the parentheses 18 | screen.onkey(right_paddle.go_up, "Up") # call go_up function without the parentheses 19 | screen.onkey(right_paddle.go_down, "Down") # call go_down function without the parentheses 20 | 21 | ball = Ball() 22 | score_board = ScoreBoard() 23 | 24 | is_game_on = True 25 | while is_game_on: 26 | screen.update() # update the paddle after moving to a new position 27 | ball.move() 28 | 29 | # bounce the ball if touch the top and bottom wall 30 | current_x_coordinate = ball.xcor() 31 | current_y_coordinate = ball.ycor() 32 | if current_y_coordinate > 390 or current_y_coordinate < -390: # check if the ball hit the bottom and top wall -> y-wall/edge 33 | ball.bounce_y() 34 | 35 | # bounce the ball if touch the both paddles 36 | if ball.distance(left_paddle) < 50 and ball.xcor() < -540 or ball.distance(right_paddle) < 50 and ball.xcor() > 540: # check if the distance of center of ball and the center of paddle is less than 50, AND before it move over the paddles area 37 | ball.bounce_x() 38 | 39 | # detect if the ball move over the left wall, if so, reset the game 40 | if ball.xcor() > 570: 41 | ball.reset_position() 42 | score_board.left_point() 43 | 44 | # detect if the ball move over the left wall, if so, reset the game 45 | if ball.xcor() < -570: 46 | ball.reset_position() 47 | score_board.right_point() 48 | 49 | 50 | done() -------------------------------------------------------------------------------- /Pong-game/paddle.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | MOVING_STEP = 40 4 | 5 | class Paddle(Turtle): 6 | def __init__(self, position : tuple): # receive the x and y coordinate in a tuple for initializing the starting position 7 | super().__init__() 8 | self.shape("square") 9 | self.color("white") 10 | self.shapesize(stretch_wid = 5, stretch_len = 1) 11 | self.penup() 12 | self.goto(position) # receive initial position from "position" tuple, then move the paddle to the edge of screen, for both left and right paddle 13 | 14 | def go_up(self): 15 | if self.ycor() < 350: 16 | new_y = self.ycor() + MOVING_STEP # get the current paddle y position and + 20 when press "w" arrow key 17 | self.goto(self.xcor(), new_y) # remain the x coordinate, we only wanna move its y coordinate position 18 | 19 | def go_down(self): 20 | if self.ycor() > -350: 21 | new_y = self.ycor() - MOVING_STEP # get the current paddle y position and - 20 when press "s" arrow key 22 | self.goto(self.xcor(), new_y) # remain the x coordinate, we only wanna move its y coordinate position -------------------------------------------------------------------------------- /Pong-game/scoreboard.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | class ScoreBoard(Turtle): 4 | def __init__(self): 5 | super().__init__() 6 | self.color("white") 7 | self.penup() 8 | self.hideturtle() 9 | self.left_score = 0 10 | self.colon = ":" 11 | self.right_score = 0 12 | self.update_score_board() 13 | 14 | def update_score_board(self): 15 | self.clear() 16 | self.goto(-70, 280) 17 | self.write(self.left_score, align = "center", font = ("Courier", 70, "normal")) 18 | self.goto(0, 300) 19 | self.write(self.colon, align = "center", font = ("Courier", 50, "normal")) 20 | self.goto(70, 280) 21 | self.write(self.right_score, align = "center", font = ("Courier", 70, "normal")) 22 | 23 | # plus 1 point for left paddle if right paddle miss out the ball 24 | def left_point(self): 25 | self.left_score += 1 26 | self.update_score_board() 27 | 28 | # plus 1 point for right paddle if left paddle miss out the ball 29 | def right_point(self): 30 | self.right_score += 1 31 | self.update_score_board() 32 | -------------------------------------------------------------------------------- /Popcat-autoclicker/main.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.by import By 3 | 4 | service = webdriver.ChromeService() 5 | driver = webdriver.Chrome(service=service) 6 | 7 | driver.get("https://popcat.click/") 8 | 9 | cat_image = driver.find_element(By.ID, "app") 10 | 11 | while True: 12 | cat_image.click() 13 | -------------------------------------------------------------------------------- /Prime-number-generator/main.py: -------------------------------------------------------------------------------- 1 | #Write your code below this line 👇 2 | def prime_checker(number): 3 | is_prime = True 4 | for i in range(2, number): 5 | if number % i == 0: 6 | is_prime = False 7 | if is_prime and number != 0 and number != 1: 8 | print("It's a prime number") 9 | else: 10 | print("It's not a prime number") 11 | 12 | #Write your code above this line 👆 13 | 14 | #Do NOT change any of the code below👇 15 | n = int(input("Check this number: ")) 16 | prime_checker(number=n) 17 | -------------------------------------------------------------------------------- /Quizzler-API-quiz-app-GUI/data.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | Trivia_api = "https://opentdb.com/api.php" 4 | 5 | # this api receive some parameters such as "amount" and "type" 6 | # here is the complete api address https://opentdb.com/api.php?amount=10&type=boolean 7 | api_parameter = { 8 | "amount" : 20, 9 | "type" : "boolean", 10 | "category" : 18 11 | } 12 | 13 | response = requests.get(Trivia_api, api_parameter) 14 | response.raise_for_status() # raise an error if connection to API is failed 15 | data = response.json() # get all the data in a dictionary form 16 | 17 | question_data = data["results"] # get the value with "results" key 18 | -------------------------------------------------------------------------------- /Quizzler-API-quiz-app-GUI/images/false.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Quizzler-API-quiz-app-GUI/images/false.png -------------------------------------------------------------------------------- /Quizzler-API-quiz-app-GUI/images/true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonnchong/Python-Projects-and-Exercises/e3320b98c80bec6eecdca867f72bd64a11258ef6/Quizzler-API-quiz-app-GUI/images/true.png -------------------------------------------------------------------------------- /Quizzler-API-quiz-app-GUI/main.py: -------------------------------------------------------------------------------- 1 | from question_model import Question 2 | from data import question_data 3 | from quiz_brain import QuizBrain 4 | from ui import QuizInterface 5 | 6 | question_bank = [] # save the generated questions in a list 7 | for question in question_data: 8 | question_text = question["question"] # get the question from the question dictionary 9 | question_answer = question["correct_answer"] # get the correct answer form the question dictionary 10 | new_question = Question(question_text, question_answer) # pass the new question and answer to the Question class constructor and save the object into the list 11 | question_bank.append(new_question) 12 | 13 | 14 | quiz = QuizBrain(question_bank) # pass the question_bank list to the QuizBrain constructor to process 15 | quiz_ui = QuizInterface(quiz) # generate GUI 16 | 17 | 18 | print("You've completed the quiz") 19 | print(f"Your final score was: {quiz.score}/{quiz.current_question_number}") -------------------------------------------------------------------------------- /Quizzler-API-quiz-app-GUI/question_model.py: -------------------------------------------------------------------------------- 1 | class Question: 2 | 3 | def __init__(self, q_text, q_answer): 4 | self.text = q_text 5 | self.answer = q_answer 6 | -------------------------------------------------------------------------------- /Quizzler-API-quiz-app-GUI/quiz_brain.py: -------------------------------------------------------------------------------- 1 | import html 2 | 3 | class QuizBrain: 4 | 5 | def __init__(self, q_list): # receive question_bank list from main 6 | self.current_question_number = 0 # initialize current question number 7 | self.score = 0 # initialize 8 | self.question_list = q_list # save the question_bank list into a new list 9 | self.current_question = None # initialize current question object 10 | 11 | def still_has_questions(self): # check if still has question in the list when user answering questions 12 | return self.current_question_number < len(self.question_list) 13 | 14 | def next_question(self): # produce next question 15 | self.current_question = self.question_list[self.current_question_number] # get the next question by accessing next index in a list 16 | self.current_question_number += 1 # increase 1 index for the list 17 | q_text = html.unescape(self.current_question.text) # unescape from html entities, reference: https://stackoverflow.com/questions/2087370/decode-html-entities-in-python-string 18 | return f"Q.{self.current_question_number}: {q_text}" # return the question number and text 19 | 20 | 21 | def check_answer(self, user_answer): # check if user's answers is correct 22 | correct_answer = self.current_question.answer # get the correct for the current question from 23 | if user_answer.lower() == correct_answer.lower(): # compare user's answer and real answer 24 | self.score += 1 # plus 1 score if user's answer is correct 25 | print(f"{self.current_question_number}, You got it right!") 26 | return True # return True for true_button() method in ui.py 27 | else: 28 | print(f"{self.current_question_number}, You got it wrong!") 29 | return False # return False for true_button() method in ui.py 30 | 31 | -------------------------------------------------------------------------------- /Random-bill-payer/main.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # 🚨 Don't change the code below 👇 4 | test_seed = int(input("Create a seed number: ")) 5 | random.seed(test_seed) 6 | 7 | # Split string method 8 | names_string = input("Give me everybody's names, separated by a comma. ") 9 | names = names_string.split(", ") 10 | # 🚨 Don't change the code above 👆 11 | 12 | #Write your code below this line 👇 13 | 14 | total_participant = len(names) 15 | 16 | random_number = random.randint(0, total_participant-1) 17 | who_pay_for_the_meal = names[random_number] 18 | 19 | print(who_pay_for_the_meal + " is going to buy the meal today!") 20 | -------------------------------------------------------------------------------- /Random-password-generator/.upm/store.json: -------------------------------------------------------------------------------- 1 | {"version":2,"languages":{"python-python3-poetry":{"guessedImportsHash":"7ddf32e17a6ac5ce04a8ecbf782ca509"}}} 2 | -------------------------------------------------------------------------------- /Random-password-generator/main.py: -------------------------------------------------------------------------------- 1 | #Password Generator Project 2 | import random 3 | 4 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 5 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 6 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 7 | 8 | # print("Welcome to the PyPassword Generator!") 9 | num_letters= int(input("How many letters would you like in your password?\n")) 10 | num_symbols = int(input(f"How many symbols would you like?\n")) 11 | num_numbers = int(input(f"How many numbers would you like?\n")) 12 | 13 | # #Eazy Level - Order not randomised: 14 | # #e.g. 4 letter, 2 symbol, 2 number = JduE&!91 15 | 16 | generated_password = "" 17 | 18 | for letter in range(0, num_letters): 19 | generated_password += random.choice(letters) 20 | # same as: 21 | # random_number = random.randint(0, len(letters) - 1) 22 | # generated_password += letters[random_number] 23 | 24 | for symbol in range(0, num_symbols): 25 | generated_password += random.choice(symbols) 26 | # same as: 27 | # random_number = random.randint(0, len(symbols) - 1) 28 | # generated_password += symbols[random_number] 29 | 30 | for number in range(0, num_numbers): 31 | generated_password += random.choice(numbers) 32 | # same as: 33 | # random_number = random.randint(0, len(numbers) - 1) 34 | # generated_password += numbers[random_number] 35 | 36 | print(generated_password) 37 | 38 | 39 | 40 | #Hard Level - Order of characters randomised: 41 | #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P 42 | 43 | # random.sample return a list, so use join to join them as a string, "" means join with no space 44 | # use "random.shuffle" insted if your data is a list 45 | randomised_order_password = "".join(random.sample(generated_password, len(generated_password))) 46 | print("Your password is : " + randomised_order_password) 47 | 48 | 49 | 50 | 51 | # notes 52 | 53 | # for letter in letters: //assign each of the item from letters into letter in each loop 54 | # print(letter) 55 | 56 | # ------------------------- same as -------------------------------- 57 | 58 | # for letter in range(0, len(letters)): //letter will be 0, 1, 2, 3..... to len(letters), //assign each of the item from the range into letter in each loop 59 | # print(letters[letter]) 60 | -------------------------------------------------------------------------------- /Rock-paper-scissors/.upm/store.json: -------------------------------------------------------------------------------- 1 | {"version":2,"languages":{"python-python3-poetry":{"guessedImportsHash":"7ddf32e17a6ac5ce04a8ecbf782ca509"}}} 2 | -------------------------------------------------------------------------------- /Rock-paper-scissors/README.md: -------------------------------------------------------------------------------- 1 | ## Rock Paper Scissors 2 | 3 | # Instructions 4 | 5 | Make a rock, paper, scissors game. 6 | 7 | Inside the `main.py` file, you'll find the ASCII art for the hand signals already saved to a corresponding variable: `rock`, `paper`, and `scissors`. This will make it easy to print them out to the console. 8 | 9 | Start the game by asking the player: 10 | 11 | *"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors."* 12 | 13 | From there you will need to figure out: 14 | * How you will store the user's input. 15 | * How you will generate a random choice for the computer. 16 | * How you will compare the user's and the computer's choice to determine the winner (or a draw). 17 | * And also how you will give feedback to the player. 18 | 19 | You can find the "official" rules of the game on [the World Rock Paper Scissors Association website.](https://wrpsa.com/the-official-rules-of-rock-paper-scissors/) 20 | 21 | 22 | # Solution 23 | 24 | [https://replit.com/@appbrewery/rock-paper-scissors-end](https://replit.com/@appbrewery/rock-paper-scissors-end) 25 | -------------------------------------------------------------------------------- /Rock-paper-scissors/main.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | rock = ''' 4 | _______ 5 | ---' ____) 6 | (_____) 7 | (_____) 8 | (____) 9 | ---.__(___) 10 | ''' 11 | 12 | paper = ''' 13 | _______ 14 | ---' ____)____ 15 | ______) 16 | _______) 17 | _______) 18 | ---.__________) 19 | ''' 20 | 21 | scissors = ''' 22 | _______ 23 | ---' ____)____ 24 | ______) 25 | __________) 26 | (____) 27 | ---.__(___) 28 | ''' 29 | 30 | #Write your code below this line 👇 31 | 32 | gesture_image = [rock, paper, scissors] 33 | 34 | user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper, 2 for Scissors \n")) 35 | 36 | if (user_choice > 2): 37 | print("Invalid Input!") 38 | else: 39 | print(gesture_image[user_choice]) 40 | 41 | computer_choice = random.randint(0,2) 42 | 43 | print("\nComputer chose:") 44 | print(gesture_image[computer_choice]) 45 | 46 | if (user_choice == computer_choice): 47 | print("Tie") 48 | elif (user_choice == 0 and computer_choice == 1): 49 | print("You lose") 50 | elif (user_choice == 1 and computer_choice == 2): 51 | print("You lose") 52 | elif (user_choice == 2 and computer_choice == 0): 53 | print("You lose") 54 | else: 55 | print("You win") 56 | 57 | -------------------------------------------------------------------------------- /Selenium-exercises/interaction.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.common.by import By 3 | from selenium.webdriver.common.keys import Keys # this is use to click keyboard 4 | 5 | chrome_driver_path = "C:\Other\chromedriver.exe" # can be either "/" or "\" 6 | driver = webdriver.Chrome(executable_path=chrome_driver_path) 7 | 8 | driver.get("https://en.wikipedia.org/wiki/Main_Page") 9 | 10 | 11 | # ------------------------------------------------------------ CLICK A LINK ------------------------------------------------------------ 12 | 13 | total_articles = driver.find_element(By.CSS_SELECTOR, "#articlecount a") 14 | print(total_articles.text) 15 | total_articles.click() # to auto click the link 16 | 17 | # if you wanna click base on a link name 18 | view_history = driver.find_element(By.LINK_TEXT, "View history") 19 | view_history.click() 20 | 21 | 22 | 23 | 24 | # ------------------------------------------------------------ CLICK A BUTTON ------------------------------------------------------------ 25 | 26 | language_setting_button = driver.find_element(By.CSS_SELECTOR, "button.uls-settings-trigger") # look for a