├── .dccache ├── .gitignore ├── 100 Days of Code ├── 1-day_Band_Name_generator │ └── 1-day_Band_Name_generator.py ├── 2-day_tip-calculator │ └── 2-day_tip-calculator.py ├── 3-day_interactive-story │ └── 3-day_interactive-story.py ├── 4-day_rock-paper-scissors │ └── 4-day_rock-paper-scissors.py ├── 5-day_password-generator │ └── 5-day_password-generator.py ├── 6-day_reeborgs_world │ ├── day6-nick.json │ └── solution.py ├── 7-day_hangman │ ├── __pycache__ │ │ └── arts.cpython-39.pyc │ ├── arts.py │ ├── dictionary.json │ └── main.py └── _preparations │ ├── 1-day-PRE.py │ ├── 2-day-PRE.py │ ├── 2-day-PRE2.py │ ├── 3-day-PRE-leap-year.py │ ├── 3-day-PRE-love-calc.py │ ├── 3-day-PRE.py │ ├── 4-day-PRE-random-name-list.py │ ├── 4-day-PRE-random-name-list_alternate.py │ ├── 4-day-PRE-treasure-map.py │ ├── 5-day-PRE-FizzBuzz.py │ ├── 5-day-PRE-average-size.py │ ├── 5-day-PRE-for-loop-range.py │ ├── 5-day-PRE-highest-score.py │ ├── 7-Day_Hangman-Step 2.py │ ├── 7-Day_Hangman-Step 3.py │ ├── 7-Day_Hangman-Step 4.py │ └── 7-day-hangman_progress.py ├── Advanced Application ├── API-Obfuscator │ ├── Data │ │ └── security │ │ │ └── API │ └── main.py ├── Self_Destructor.py ├── Simple_API_study.py ├── XOR Cipher │ ├── Data │ │ └── security │ │ │ └── .KEY.nclmE │ ├── Decryptor.py │ └── Encryptor.py ├── fast-api-study │ ├── __pycache__ │ │ └── fast_api_study.cpython-39.pyc │ └── fast_api_study.py ├── json-reader │ ├── json-reader.py │ └── sample-json.json ├── password_generator.py ├── phone_number_details.py ├── stock_data_driven_web_app.py └── website_link_extractor.py ├── Conversion Scripts ├── Image-Optimizer │ ├── image-optimizer.py │ ├── original_images │ │ └── sampleOriginal.jpg │ └── sampleOriginal.jpg ├── OrdinalNum2Roman.py ├── PNG-and-JPG-to-WebP │ ├── original_images │ │ └── sampleOptimized-converted.jpg.webp │ ├── png_jpg_to_webp.py │ └── sampleOriginal.jpg ├── days_hours_minutes_to_seconds.py ├── minutes_to_years.py ├── seconds_to_days_hours_minutes.py └── temperature_conversion.py ├── LICENSE ├── Math Scripts ├── math-circle_area.py ├── math-fibonacci.py ├── math-rectangle_area_equation.py └── math-trapeze_area.py ├── OLD-REPO.md ├── Problem Solving Scripts ├── CNPJ_Checker.py ├── CPF_Checker.py ├── CPF_Generator.py ├── __pycache__ │ └── CPF_Checker.cpython-39.pyc ├── basic_investment_calc.py ├── bonus_and_salary.py ├── medicine_box.py ├── movie-food-decider │ ├── food.json │ ├── movie-food.py │ └── movies.json ├── price_quantity_calc.py └── q-min_jumps_array.py ├── README.md ├── String Based Scripts ├── basic_input.py ├── clipboard_time_defs.py ├── downloadsOrganizer.py ├── hideJPG │ ├── photo copy.jpg │ └── photo.jpg ├── hide_jpg_message.py └── reverse_string.py └── sample.svg /.dccache: -------------------------------------------------------------------------------- 1 | {"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Math Scripts/math-circle_area.py":[642,1635526561684.2175,"a7cc0dacdadafc03af2aa20f6a4dbdb48d0a96bbe47ca1fa6146f5d271724b2b"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Math Scripts/math-fibonacci.py":[818,1635526561684.3499,"58f2981810dec65fcc9d7572af5a985b7039f77b95e5dc78d82d245f1296b9f6"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Math Scripts/math-rectangle_area_equation.py":[1601,1635526561684.459,"3fad1d76b8cc61a1e8375e582f12ead61f080a34e4386bd1d903741dd246a342"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Math Scripts/math-trapeze_area.py":[877,1635526561684.5464,"5465fc93f5ef41616fa91e1a713917dd36d4e0fd828c83a106fd283752f0d5ce"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/OrdinalNum2Roman.py":[1017,1635526561652.343,"ff5be3ccbb4ead68861197fed7e70b09e29ede4711893a39b1dc97602396fc23"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/days_hours_minutes_to_seconds.py":[300,1635526561683.3042,"8786607eeb102cb94856b520ab134cc2879c148c9ddb30154140faed4cb3f502"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/minutes_to_years.py":[113,1635526561683.4163,"868be2052403e2e0e9473920c024c3d5a9c996604166f797ac630209023168a9"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/seconds_to_days_hours_minutes.py":[359,1635526561683.575,"f2ab7a13deb5aff231285dd0e30877ec29991af698447fc29641ac90d9cce485"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/temperature_conversion.py":[571,1635526561683.704,"86916e45422f180ff5b12bdf0ec6a8c3e67983881e0170191cce1051d2b3b2b8"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Problem Solving Scripts/basic_investment_calc.py":[1147,1635526561684.709,"897cc928bc056deac049d7dc39645aa3d1e2f07b45cd8a957c5964d7e11624b2"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Problem Solving Scripts/bonus_and_salary.py":[721,1635526561684.8423,"6371d64d602d715e8cc3512f9c750038afa7a7c7e9a5ab80846311114b25d6ef"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Problem Solving Scripts/medicine_box.py":[575,1635526561684.9348,"b5f6e30c28618f021157c082b1baecdc24838de8dfe66f3639d89ee0d6f911f8"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Problem Solving Scripts/price_quantity_calc.py":[456,1635526561685.0286,"f8c776042ab42ea748353c37a601a0066235ea2848409b29443c6a12beb7a246"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Problem Solving Scripts/q-min_jumps_array.py":[1010,1635526561685.1265,"58aeb1001c907b268c1787395624027d362b14d49b922d46ccc5736059480b9d"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Self_Destructor.py":[1086,1635526561616.2402,"a0339fa07497bab52ebd548975c0b2def3c178af4c1bc17c7a758ba60e661f16"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Simple_API_study.py":[1444,1635526561616.3772,"6906007b8706643db039a323760c2bec9e3a3781d3be06727bf870ffef3cce39"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/password_generator.py":[653,1635526561617.0168,"5f0cea80c3e440641862cc7abc0d6a5f3a271294d58fb5f0f193e050c1d340ac"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/phone_number_details.py":[989,1635526561617.152,"d1db412e4ec04eb1a0d06f1d15b2c5fa434936f4899842a1dd18dbc237e404e4"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/stock_data_driven_web_app.py":[1348,1635526561617.298,"0c1e36ff3b9d4b6e1b9f74c45fd7eb5111f64801ca933f9d24cbff6074087e1e"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/website_link_extractor.py":[592,1635526561617.431,"df7301e400281837d6dd6907059153a38ac7acb48223691b2737b1136bb62fc6"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/String Based Scripts/basic_input.py":[721,1635526561685.489,"632d0c871fc57eaf0ab227029d42fc42e35b01bd632d2ead9753b0ac33b710b4"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/String Based Scripts/clipboard_time_defs.py":[1020,1635526561685.5952,"8f89f3e74e28a49be4a779201f053e29c236af234cabe937129af70f53d73c73"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/String Based Scripts/downloadsOrganizer.py":[2084,1635526561685.7002,"9d31cde9b196eeffaf0f4e571937064c68c7425b989971ad8a077fb51de1653d"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/String Based Scripts/hide_jpg_message.py":[2022,1635526561686.3872,"269ed46bd88867897f32272ab398f4b2a0b1b453449420e1c68c704279c85221"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/String Based Scripts/reverse_string.py":[83,1635526561686.4727,"bf5f91359365ed349164a5e052229874ce221c32f67bf1790f19c2b21218cf54"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/1-day_Band_Name_generator/1-day_Band_Name_generator.py":[836,1637161371243,"b575b79694af8ef0a398628851ba9e77eaa184e096ac95ebb95dc71e644ab737"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/3-day_interactive-story/3-day_interactive-story.py":[3145,1637161366264,"6e29e3ae9dff47781f4390ee31fb7156c4bebffd9164f93e0860eb2bc109b650"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/2-day_tip-calculator/2-day_tip-calculator.py":[801,1637161368842,"58c16c0c48961e4e93f842d9e3ccef22695987da2945373070fb7d779ac306dc"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/4-day_rock-paper-scissors/4-day_rock-paper-scissors.py":[1518,1637200556515.7844,"36a8c04a260bfc899ec0978afb609f921765e1a894299a8d614c2fbfd81b25e1"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/5-day_password-generator/5-day_password-generator.py":[2879,1637161332410,"bdd93665469cd518a1aea890bcd3b3cb94023494ab1a2399b4ff1facef121101"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/6-day_reeborgs_world/solution.py":[567,1636985827310.6995,"12701ca7039d0881f91ee31f3b34289aea97df34d8618ff7a7409535bb57cbb9"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/1-day-PRE.py":[686,1636046112314,"7b3fab2c241ca466d31f8406040eb645574e6db636e61d1ac77c3f81e6472914"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/2-day-PRE.py":[413,1636046112406,"f26a965c13231befed1b986071b347760b30e3933bede4a3d6a89bb69e4a0730"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/2-day-PRE2.py":[431,1636046112447,"b887d10c13b253fa1ba666acf318860c2afa966953ec3a6280f62971baa31b2f"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/3-day-PRE-leap-year.py":[649,1636046112495,"aeda6c9303dbcbb875b85c481680c90b3f617f9e7fb9e0f06c6638c93c12d3cc"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/3-day-PRE-love-calc.py":[1109,1636046112526,"fc563554f51ce55ed146c2c55531c30a680ea270971eccbbfe92c0d452e11abd"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/3-day-PRE.py":[274,1636046112546,"e258d9b8f84ce1f019eb0f36f0197efc1df91477638c88387b1d68e6943b54a4"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/4-day-PRE-random-name-list.py":[317,1636062254998.2683,"96f8a3f92131097888fddb9b42f3f5f0f3c7578cc0eb9b272ee89023ca2c886c"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/4-day-PRE-random-name-list_alternate.py":[320,1636062639683.2292,"b0697ab81046a7123e4df4668b5104963c98456122061198e6834e191ffe8135"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/4-day-PRE-treasure-map.py":[679,1636067241890.1348,"1941a4c620bf9ca6fb97453faabe3159da6eba8b76584cb7b70d02037661438e"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/5-day-PRE-FizzBuzz.py":[270,1636135182907.1013,"1deb7e3fb82279dfece501134061465f3c9f86b18019ad93e748bef5f55f6553"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/5-day-PRE-average-size.py":[682,1636123784193.0588,"72cc48af3de7feaffd0792270b4d5f5a5e0738a3c032b5980c75341bcb317a5c"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/5-day-PRE-for-loop-range.py":[918,1636134235948.765,"beb480c07f3a0234f87952f25ac5dfda897f53b3d304b16b10b7721286cbd3f0"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/100 Days of Code/_preparations/5-day-PRE-highest-score.py":[579,1636124588901.4617,"8b157652d83723c2d1bbd94cba7fc8abb41cc209695bb59499569cc671146315"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/Image-Optimizer/image-optimizer.py":[2515,1635526561617.7336,"605d621e297da883de2889c5af1be0019c660878e82e31e2f4a84685c7f691db"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Conversion Scripts/PNG-and-JPG-to-WebP/png_jpg_to_webp.py":[1391,1635526561656.7527,"c70a13feab613196038d84f7f3d99f7fe9b33db20b7bd9a29b86561a09230a75"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Problem Solving Scripts/movie-food-decider/movie-food.py":[981,1635874875871.399,"d1db225ad861422b0714e0bdd4a68901291c539c6253718bf9f410875d02fdf8"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Encryptor/decryptor.py":[1718,1635526561615.4387,"7eb873bae63d01df353263ec91b97ff83b657ca432d3062ecb7f916cbec4562a"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Encryptor/encryptor.py":[3555,1635526561615.6057,"e5e600df1a815c5cf13fbcb97a00776485a27759164de8f266cd26642c8da0fd"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Encryptor/main.py":[59,1635526561615.7434,"ed88308372e367ec5605d9dc5b5373573c817c4ef8966c516474e16549548515"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Obfuscation Study/obfuscator_test copy.py":[416,1635526561615.9634,"ea58700142b70b22115f8459697b68a485cff1e9c2c3849e6614169540eb19b2"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/Obfuscation Study/obfuscator_test.py":[416,1635526561616.0999,"ea58700142b70b22115f8459697b68a485cff1e9c2c3849e6614169540eb19b2"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/fast-api-study/fast_api_study.py":[7986,1635526561616.875,"df8fd58e657b885d3a4657af1fa17761688aa4bd47dc24fe327bcbe44c3f2eab"],"/Users/dreamdevourer/Documents/Source Codes/Personal/Python Study/Python-Fundamentals-Study/Advanced Application/json-reader/json-reader.py":[677,1635732094500.9146,"45cec0f24d2eee1d83bef0648545942b79fa9a000e8162ab503cd3dfa9700225"]} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.DS_Store 2 | /Bin 3 | /build 4 | /dist 5 | Bin/ 6 | *.DS_Store 7 | .AppleDouble 8 | .LSOverride 9 | 10 | # Files that might appear in the root of a volume 11 | .DocumentRevisions-V100 12 | .fseventsd 13 | .Spotlight-V100 14 | .TemporaryItems 15 | .Trashes 16 | .VolumeIcon.icns 17 | .com.apple.timemachine.donotpresent 18 | 19 | # Directories potentially created on remote AFP share 20 | .AppleDB 21 | .AppleDesktop 22 | Network Trash Folder 23 | Temporary Items 24 | .apdisk 25 | 26 | 27 | # Windows thumbnail cache files 28 | Thumbs.db 29 | Thumbs.db:encryptable 30 | ehthumbs.db 31 | ehthumbs_vista.db 32 | 33 | # Dump file 34 | *.stackdump 35 | 36 | # Folder config file 37 | [Dd]esktop.ini 38 | 39 | # Recycle Bin used on file shares 40 | $RECYCLE.BIN/ 41 | 42 | # Windows Installer files 43 | *.cab 44 | *.msi 45 | *.msix 46 | *.msm 47 | *.msp 48 | 49 | # Windows shortcuts 50 | *.lnk 51 | 52 | *~ 53 | 54 | # temporary files which can be created if a process still has a handle open of a deleted file 55 | .fuse_hidden* 56 | 57 | # KDE directory preferences 58 | .directory 59 | 60 | # Linux trash folder which might appear on any partition or disk 61 | .Trash-* 62 | 63 | # .nfs files are created when an open file is removed but is still being accessed 64 | .nfs* -------------------------------------------------------------------------------- /100 Days of Code/1-day_Band_Name_generator/1-day_Band_Name_generator.py: -------------------------------------------------------------------------------- 1 | # Objective: Generate a band name from city and pet name. 2 | 3 | import random 4 | # 1. Create a greeting for your program. 5 | print( 6 | "Hello, welcome to Band Name Generator" 7 | ) 8 | # 2. Ask the user for the city that they grew up in. 9 | cityInfo = input("What is the city you grew up?\n") 10 | print("Awesome! \n") 11 | # 3. Ask the user for the name of a pet. 12 | petInfo = input("Type a pet name:\n") 13 | petMSGs = {"msg1": "Great name!", "msg2": "Amazing!", 14 | "msg3": "Interesting name.", "msg4": "Wow, that's great!"} 15 | print(f"{random.choice(list(petMSGs.values()))}\n") 16 | megaFusion = cityInfo+" "+petInfo 17 | # 4. Combine the name of their city and pet and show them their band name. 18 | print(f"Your band name could be: {megaFusion}") 19 | 20 | # 5. Make sure the input cursor shows on a new line, see the example at: 21 | # https://band-name-generator-end.appbrewery.repl.run/ 22 | -------------------------------------------------------------------------------- /100 Days of Code/2-day_tip-calculator/2-day_tip-calculator.py: -------------------------------------------------------------------------------- 1 | # If the bill was $150.00, split between 5 people, with 12% tip. 2 | 3 | # Each person should pay (150.00 / 5) * 1.12 = 33.6 4 | # Format the result to 2 decimal places = 33.60 5 | 6 | # Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪 7 | 8 | # Write your code below this line 👇 9 | print("Welcome to the tip calculator.") 10 | 11 | billTotal = float(input("What's the bill total? $")) 12 | tipPercentage = int( 13 | input("Whats is the percentage tip? (0, 10, 12 or 15) ")) / 100 14 | peopleQnty = int(input("How many people to split the bill? ")) 15 | 16 | totalTip = billTotal * tipPercentage 17 | 18 | if tipPercentage > 0: 19 | mathSolverSum = billTotal + totalTip 20 | mathSolver = mathSolverSum / peopleQnty 21 | else: 22 | mathSolver = billTotal / peopleQnty 23 | 24 | print(f"Each person should pay: ${round(mathSolver, 2)}") 25 | -------------------------------------------------------------------------------- /100 Days of Code/3-day_interactive-story/3-day_interactive-story.py: -------------------------------------------------------------------------------- 1 | print(''' 2 | ******************************************************************************* 3 | . . ' . 4 | ' . . ' . + 5 | ` ' . ' 6 | . ,'`. . 7 | . .." _.-;' `. . 8 | _.-"`.##%"_.--" ,' `. "#" ___,,od000 9 | ,'"-_ _.-.--"\ ,' `-_ '%#%',,/////00000HH 10 | ,' |_.' )`/- __..--""`-_`-._ J L/////00000HHHHM 11 | . + ,' _.-" / / _-"" `-._`-_/___\///0000HHHHMMM 12 | .'_.-"" ' :_/_.-' _,`-/__V__\0000HHHHHMMMM 13 | . _-"" . ' _,////\ | /000HHHHHMMMMM 14 | _-" . ' + . . ,//////0\ | /00HHHHHHHMMMMM 15 | ` ,//////000\|/00HHHHHHHMMMMMM 16 | . ' . ' . . ' ,//////00000|00HHHHHHHHMMMMMM 17 | . . . ' ,//////000000|00HHHHHHHMMMMMMM 18 | . ' . . ,///////000000|0HHHHHHHHMMMMMMM 19 | ' ' . ' ///////000000000HHHHHHHHMMMMMMM 20 | + . . ' . ,///////000000000HHHHHHHMMMMMMMM 21 | ' . ' . ///////000000000HHHHHHHHMMMMMMMM 22 | ' . ' ///////000000000HHHHHHHHMMMMMMMM 23 | . ' ,///////000000000HHHHHHHHMMMMMMMM 24 | + . ' . . ////////000000000HHHHHHHHMMMMMMhs 25 | ******************************************************************************* 26 | ''') 27 | print("Welcome to Titan Station.") 28 | print("Your mission is to find the Marker, a black monolith.") 29 | 30 | #Write your code below this line 👇 31 | 32 | def startChoice(): 33 | choice1 = input('You are orbiting the station, everything seems calm, what do you want to do? Type "dock" to dock your ship into the docking bay or "watch" \n').lower() 34 | 35 | if choice1 == "dock": 36 | choice2 = input('You\'ve docked your ship. Everything is quiet and dark. Type "gov sector" to go to the government sector for looking to the marker or type "explore" to explore the nearby corridors. \n').lower() 37 | if choice2 == "gov sector": 38 | choice3 = input("You reached the government sector bulk door. An Earthgov soldier asks for the password? (you have a note about the marker, probably the password can be 'Tiedemann', 'Marshal Law', 'Isaac Clark') \n").lower() 39 | if choice3 == "Tiedemann": 40 | print("The soldiers disappear and an horde of necromorphs catches you. Game Over.") 41 | elif choice3 == "Marshal Law": 42 | print("You entered the Earthgov sector and now you have access to the black marker! You Win!") 43 | elif choice3 == "Isaac Clark": 44 | print("The soldier calls for reinforcements and then shoot you. Game Over.") 45 | else: 46 | print("You chose a door that doesn't exist. Game Over.") 47 | else: 48 | print("You get attacked by a hidden necromorph in the dark. Game Over.") 49 | else: 50 | print("You have been hit by an asteroid, your ship exploded. Game Over.") 51 | 52 | startChoice() 53 | -------------------------------------------------------------------------------- /100 Days of Code/4-day_rock-paper-scissors/4-day_rock-paper-scissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | import sys 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 | visualSet = {"Rock": rock, "Paper": paper, "Scissors": scissors} 33 | aiChoice = random.choice(list(visualSet.values())) 34 | 35 | print("Welcome to the game.\n0 - Rock\n1 - Paper\n2 - Scissors") 36 | userSet = input("Type a number: \n") 37 | 38 | if userSet == "0": 39 | selectedHuman = visualSet["Rock"] 40 | print(f"HUMAN:\n{selectedHuman}") 41 | print(f"AI:\n{aiChoice}") 42 | if aiChoice == paper: 43 | print("AI wins") 44 | elif aiChoice == rock: 45 | print("Tie") 46 | elif aiChoice == scissors: 47 | print("Human wins") 48 | 49 | elif userSet == "1": 50 | selectedHuman = visualSet["Paper"] 51 | print(f"HUMAN:\n{selectedHuman}") 52 | print(f"AI:\n{aiChoice}") 53 | if aiChoice == paper: 54 | print("Tie") 55 | elif aiChoice == rock: 56 | print("Human wins") 57 | elif aiChoice == scissors: 58 | print("AI wins") 59 | 60 | elif userSet == "2": 61 | selectedHuman = visualSet["Scissors"] 62 | print(f"HUMAN:\n{selectedHuman}") 63 | print(f"AI:\n{aiChoice}") 64 | if aiChoice == paper: 65 | print("Human wins") 66 | elif aiChoice == rock: 67 | print("AI wins") 68 | elif aiChoice == scissors: 69 | print("Tie") 70 | 71 | else: 72 | print("Invalid input") 73 | sys.exit(-1) 74 | -------------------------------------------------------------------------------- /100 Days of Code/5-day_password-generator/5-day_password-generator.py: -------------------------------------------------------------------------------- 1 | #Password Generator Project 2 | import random 3 | import secrets 4 | import os 5 | import sys 6 | 7 | 8 | # Character Lists 9 | 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'] 10 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 11 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 12 | 13 | print("Welcome to the PyMasterPassword Generator!") 14 | nr_letters= int(input("How many letters would you like in your password?\n")) 15 | nr_symbols = int(input(f"How many symbols would you like?\n")) 16 | nr_numbers = int(input(f"How many numbers would you like?\n")) 17 | nr_randomOrder = input("Would you like your password to be in random order? (y/n)\n").lower() 18 | 19 | #Easy Level - Order not randomized: 20 | #e.g. 4 letter, 2 symbol, 2 number = JduE&!91 21 | 22 | def easyMode(): 23 | def generateLetters(): 24 | global letter 25 | letter = "" 26 | for lettersNum in range(nr_letters): 27 | letter += secrets.choice(letters) 28 | generateSymbols() 29 | 30 | 31 | def generateSymbols(): 32 | global genSymbols 33 | genSymbols = "" 34 | for symbolNum in range(nr_symbols): 35 | genSymbols += secrets.choice(symbols) 36 | generateNumbers() 37 | 38 | def generateNumbers(): 39 | global genNumbers 40 | genNumbers = "" 41 | for numNum in range(nr_numbers): 42 | genNumbers += secrets.choice(numbers) 43 | resultPassword() 44 | 45 | def resultPassword(): 46 | print(f"Your password is: {letter}{genSymbols}{genNumbers}") 47 | # copy password to clipboard 48 | copyPass = letter+genSymbols+genNumbers 49 | os.system(f"echo {copyPass} | pbcopy") 50 | 51 | generateLetters() 52 | 53 | 54 | 55 | #Hard Level - Order of characters randomised: 56 | #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P 57 | 58 | passwdList = [] 59 | 60 | 61 | def hardMode(): 62 | 63 | global passwdList 64 | 65 | def generateLettersH(): 66 | global passwdList 67 | for lettersNum in range(nr_letters): 68 | passwdList += random.choice(letters) 69 | generateSymbolsH() 70 | 71 | def generateSymbolsH(): 72 | global passwdList 73 | for symbolNum in range(nr_symbols): 74 | passwdList += random.choice(symbols) 75 | generateNumbersH() 76 | 77 | def generateNumbersH(): 78 | global passwdList 79 | for numNum in range(nr_numbers): 80 | passwdList += random.choice(numbers) 81 | resultPasswordH() 82 | 83 | def resultPasswordH(): 84 | global passwdList 85 | random.shuffle(passwdList) 86 | randomReadable = "" 87 | for eachChar in passwdList: 88 | randomReadable += eachChar 89 | 90 | print(f"Your random password is: {randomReadable}") 91 | # copy randomReadable to clipboard 92 | os.system(f"echo {randomReadable} | pbcopy") 93 | 94 | generateLettersH() 95 | 96 | if nr_randomOrder == "y": 97 | hardMode() 98 | else: 99 | easyMode() 100 | -------------------------------------------------------------------------------- /100 Days of Code/6-day_reeborgs_world/solution.py: -------------------------------------------------------------------------------- 1 | # Please refer to the json file or this link for understanding the main problem and cross compare with this solution. 2 | 3 | def moveUp(): 4 | turn_left() 5 | 6 | 7 | def moveDown(): 8 | turn_left() 9 | turn_left() 10 | 11 | 12 | def moveRight(): 13 | turn_left() 14 | turn_left() 15 | turn_left() 16 | 17 | 18 | if at_goal() != True: 19 | while front_is_clear(): 20 | move() 21 | 22 | turn_left() 23 | 24 | while at_goal() != True: 25 | # Basic conditions 26 | if right_is_clear(): 27 | moveRight() 28 | move() 29 | elif front_is_clear(): 30 | move() 31 | else: 32 | turn_left() 33 | -------------------------------------------------------------------------------- /100 Days of Code/7-day_hangman/__pycache__/arts.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/100 Days of Code/7-day_hangman/__pycache__/arts.cpython-39.pyc -------------------------------------------------------------------------------- /100 Days of Code/7-day_hangman/arts.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 | -------------------------------------------------------------------------------- /100 Days of Code/7-day_hangman/dictionary.json: -------------------------------------------------------------------------------- 1 | { 2 | "word_list": [ 3 | "abruptly", 4 | "absurd", 5 | "abyss", 6 | "affix", 7 | "askew", 8 | "avenue", 9 | "awkward", 10 | "axiom", 11 | "azure", 12 | "bagpipes", 13 | "bandwagon", 14 | "banjo", 15 | "bayou", 16 | "beekeeper", 17 | "bikini", 18 | "blitz", 19 | "blizzard", 20 | "boggle", 21 | "bookworm", 22 | "boxcar", 23 | "boxful", 24 | "buckaroo", 25 | "buffalo", 26 | "buffoon", 27 | "buxom", 28 | "buzzard", 29 | "buzzing", 30 | "buzzwords", 31 | "caliph", 32 | "cobweb", 33 | "cockiness", 34 | "croquet", 35 | "crypt", 36 | "curacao", 37 | "cycle", 38 | "daiquiri", 39 | "dirndl", 40 | "disavow", 41 | "dizzying", 42 | "duplex", 43 | "dwarves", 44 | "embezzle", 45 | "equip", 46 | "espionage", 47 | "euouae", 48 | "exodus", 49 | "faking", 50 | "fishhook", 51 | "fixable", 52 | "fjord", 53 | "flapjack", 54 | "flopping", 55 | "fluffiness", 56 | "flyby", 57 | "foxglove", 58 | "frazzled", 59 | "frizzled", 60 | "fuchsia", 61 | "funny", 62 | "gabby", 63 | "galaxy", 64 | "galvanize", 65 | "gazebo", 66 | "giaour", 67 | "gizmo", 68 | "glowworm", 69 | "glyph", 70 | "gnarly", 71 | "gnostic", 72 | "gossip", 73 | "grogginess", 74 | "haiku", 75 | "haphazard", 76 | "hyphen", 77 | "iatrogenic", 78 | "icebox", 79 | "injury", 80 | "ivory", 81 | "ivy", 82 | "jackpot", 83 | "jaundice", 84 | "jawbreaker", 85 | "jaywalk", 86 | "jazziest", 87 | "jazzy", 88 | "jelly", 89 | "jigsaw", 90 | "jinx", 91 | "jiujitsu", 92 | "jockey", 93 | "jogging", 94 | "joking", 95 | "jovial", 96 | "joyful", 97 | "juicy", 98 | "jukebox", 99 | "jumbo", 100 | "kayak", 101 | "kazoo", 102 | "keyhole", 103 | "khaki", 104 | "kilobyte", 105 | "kiosk", 106 | "kitsch", 107 | "kiwifruit", 108 | "klutz", 109 | "knapsack", 110 | "larynx", 111 | "lengths", 112 | "lucky", 113 | "luxury", 114 | "lymph", 115 | "marquis", 116 | "matrix", 117 | "megahertz", 118 | "microwave", 119 | "mnemonic", 120 | "mystify", 121 | "naphtha", 122 | "nightclub", 123 | "nowadays", 124 | "numbskull", 125 | "nymph", 126 | "onyx", 127 | "ovary", 128 | "oxidize", 129 | "oxygen", 130 | "pajama", 131 | "peekaboo", 132 | "phlegm", 133 | "pixel", 134 | "pizazz", 135 | "pneumonia", 136 | "polka", 137 | "pshaw", 138 | "psyche", 139 | "puppy", 140 | "puzzling", 141 | "quartz", 142 | "queue", 143 | "quips", 144 | "quixotic", 145 | "quiz", 146 | "quizzes", 147 | "quorum", 148 | "razzmatazz", 149 | "rhubarb", 150 | "rhythm", 151 | "rickshaw", 152 | "schnapps", 153 | "scratch", 154 | "shiv", 155 | "snazzy", 156 | "sphinx", 157 | "spritz", 158 | "squawk", 159 | "staff", 160 | "strength", 161 | "strengths", 162 | "stretch", 163 | "stronghold", 164 | "stymied", 165 | "subway", 166 | "swivel", 167 | "syndrome", 168 | "thriftless", 169 | "thumbscrew", 170 | "topaz", 171 | "transcript", 172 | "transgress", 173 | "transplant", 174 | "triphthong", 175 | "twelfth", 176 | "twelfths", 177 | "unknown", 178 | "unworthy", 179 | "unzip", 180 | "uptown", 181 | "vaporize", 182 | "vixen", 183 | "vodka", 184 | "voodoo", 185 | "vortex", 186 | "voyeurism", 187 | "walkway", 188 | "waltz", 189 | "wave", 190 | "wavy", 191 | "waxy", 192 | "wellspring", 193 | "wheezy", 194 | "whiskey", 195 | "whizzing", 196 | "whomever", 197 | "wimpy", 198 | "witchcraft", 199 | "wizard", 200 | "woozy", 201 | "wristwatch", 202 | "wyvern", 203 | "xylophone", 204 | "yachtsman", 205 | "yippee", 206 | "yoked", 207 | "youthful", 208 | "yummy", 209 | "zephyr", 210 | "zigzag", 211 | "zigzagging", 212 | "zilch", 213 | "zipper", 214 | "zodiac", 215 | "zombie" 216 | ] 217 | } 218 | -------------------------------------------------------------------------------- /100 Days of Code/7-day_hangman/main.py: -------------------------------------------------------------------------------- 1 | # Step 5 2 | 3 | import random 4 | import json 5 | from arts import stages, logo 6 | import pathlib 7 | import os 8 | from pathlib import * 9 | 10 | currentPath = pathlib.Path(__file__).parent.absolute() 11 | jsonDictionary = open(f"{currentPath}/dictionary.json", "r") 12 | pyList = jsonDictionary.read() 13 | print(f"RESULT IS: {pyList}") 14 | # word_list = json.loads(jsonDictionary) 15 | word_list = ["null"] 16 | 17 | # TODO-1: - Update the word list to use the 'word_list' from hangman_words.py 18 | # Delete this line: word_list = ["ardvark", "baboon", "camel"] 19 | chosen_word = random.choice(word_list) 20 | word_length = len(chosen_word) 21 | 22 | end_of_game = False 23 | lives = 6 24 | 25 | # TODO-3: - Import the logo from hangman_art.py and print it at the start of the game. 26 | 27 | # Testing code 28 | print(f'Pssst, the solution is {chosen_word}.') 29 | 30 | # Create blanks 31 | display = [] 32 | for _ in range(word_length): 33 | display += "_" 34 | 35 | while not end_of_game: 36 | guess = input("Guess a letter: ").lower() 37 | 38 | # TODO-4: - If the user has entered a letter they've already guessed, print the letter and let them know. 39 | 40 | # Check guessed letter 41 | for position in range(word_length): 42 | letter = chosen_word[position] 43 | print( 44 | f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}") 45 | if letter == guess: 46 | display[position] = letter 47 | 48 | # Check if user is wrong. 49 | if guess not in chosen_word: 50 | # 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. 51 | lives -= 1 52 | if lives == 0: 53 | end_of_game = True 54 | print("You lose.") 55 | 56 | # Join all the elements in the list and turn it into a String. 57 | print(f"{' '.join(display)}") 58 | 59 | # Check if user has got all letters. 60 | if "_" not in display: 61 | end_of_game = True 62 | print("You win.") 63 | 64 | # TODO-2: - Import the stages from hangman_art.py and make this error go away. 65 | print(stages[lives]) 66 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/1-day-PRE.py: -------------------------------------------------------------------------------- 1 | # https://replit.com/@appbrewery/day-1-1-exercise 2 | # Literally print it: 3 | print("Day 1 - Python Print Function", 4 | "\nThe function is declared like this:", 5 | "\nprint('what to print')") 6 | 7 | wordCharCount = input("Write a word here to count:\n") 8 | print(f"This is how many character this word have: {len(wordCharCount)}") 9 | 10 | # 🚨 Don't change the code below 👇 11 | a = input("a: ") 12 | b = input("b: ") 13 | # 🚨 Don't change the code above 👆 14 | 15 | #################################### 16 | # Write your code below this line 👇 17 | 18 | c = a 19 | a = b 20 | b = c 21 | 22 | 23 | # Write your code above this line 👆 24 | #################################### 25 | 26 | # 🚨 Don't change the code below 👇 27 | print("a: " + a) 28 | print("b: " + b) 29 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/2-day-PRE.py: -------------------------------------------------------------------------------- 1 | # BMI Calculator 2 | # https://replit.com/@appbrewery/day-2-2-exercise 3 | # https://en.wikipedia.org/wiki/Body_mass_index 4 | # 🚨 Don't change the code below 👇 5 | height = input("enter your height in m: ") 6 | weight = input("enter your weight in kg: ") 7 | # 🚨 Don't change the code above 👆 8 | 9 | # Write your code below this line 👇 10 | 11 | BMI_formula = float(weight) / float(height) ** 2 12 | 13 | print(f"Your BMI is: {BMI_formula} m2") 14 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/2-day-PRE2.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | age = input("What is your current age? ") 3 | # 🚨 Don't change the code above 👆 4 | 5 | ageLimit = 100 - int(age) 6 | 7 | days = 365 8 | weeks = 52 9 | months = 12 10 | 11 | daysUntilLimit = round(days * ageLimit) 12 | weeksUntilLimit = round(weeks * ageLimit) 13 | monthsUntilLimit = round(months * ageLimit) 14 | 15 | print(f"You have {daysUntilLimit} days, {weeksUntilLimit} weeks, and {monthsUntilLimit} months left until 100 years.") 16 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/3-day-PRE-leap-year.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 | # Can the input be divided by 4? 8 | # If no, then it's not leap, if yes then: 9 | # Can the input be divided by 100? 10 | # if no then it's a leap year, if yes then: 11 | # Can the input be divided by 400? 12 | # if no then it's not a leap year, if yes then it's a leap year. 13 | 14 | def CheckLeap(year): 15 | if((year % 400 == 0) or 16 | (year % 100 != 0) and 17 | (year % 4 == 0)): 18 | print("Given Year is a leap Year"); 19 | else: 20 | print ("Given Year is not a leap Year") 21 | 22 | CheckLeap(year) 23 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/3-day-PRE-love-calc.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | print("Welcome to the Love Calculator!") 3 | name1 = input("What is your name? \n") 4 | name2 = input("What is their name? \n") 5 | # 🚨 Don't change the code above 👆 6 | 7 | # Based on this method: https://www.buzzfeed.com/ariannarebolini/what-are-the-chances-your-crush-is-actually-your-true-love 8 | 9 | # Write your code below this line 👇 10 | 11 | coupleName = name1 + name2 12 | formattedNames = coupleName.lower() 13 | tr00 = formattedNames.count("t") 14 | tr01 = formattedNames.count("r") 15 | tr02 = formattedNames.count("u") 16 | tr03 = formattedNames.count("e") 17 | trueComponent = tr00 + tr01 + tr02 + tr03 18 | 19 | lv00 = formattedNames.count("l") 20 | lv01 = formattedNames.count("o") 21 | lv02 = formattedNames.count("v") 22 | lv03 = formattedNames.count("e") 23 | loveComponent = lv00 + lv01 + lv02 + lv03 24 | 25 | loveCalc = int(str(trueComponent) + str(loveComponent)) 26 | 27 | if (loveCalc < 10) or (loveCalc > 90): 28 | print(f"Your score is {loveCalc}, you go together like coke and mentos.") 29 | elif (loveCalc >= 40) and (loveCalc <= 50): 30 | print(f"Your score is {loveCalc}, you are alright together.") 31 | else: 32 | print(f"Your score is {loveCalc}.") 33 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/3-day-PRE.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | number = int(input("Which number do you want to check? ")) 3 | # 🚨 Don't change the code above 👆 4 | 5 | #Write your code below this line 👇 6 | 7 | if number % 2 == 0: 8 | print("This is an even number.") 9 | else: 10 | print("This is an odd number.") 11 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/4-day-PRE-random-name-list.py: -------------------------------------------------------------------------------- 1 | # Split string method 2 | import random 3 | names_string = input("Give me everybody's names, separated by a comma: ") 4 | names = names_string.split(", ") 5 | # 🚨 Don't change the code above 👆 6 | 7 | # Write your code below this line 👇 8 | 9 | randomName = random.choice(names) 10 | print(f"The chosen one to pay the bill is: {randomName}.") 11 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/4-day-PRE-random-name-list_alternate.py: -------------------------------------------------------------------------------- 1 | # Split string method 2 | import random 3 | names_string = input("Give me everybody's names, separated by a comma: ") 4 | names = names_string.split(", ") 5 | # 🚨 Don't change the code above 👆 6 | 7 | # Write your code below this line 👇 8 | 9 | randomLen = len(names) 10 | randomIndex = random.randint(0, randomLen - 1) 11 | print(names[randomIndex]) 12 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/4-day-PRE-treasure-map.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | row1 = ["⬜️", "⬜️", "⬜️"] 3 | row2 = ["⬜️", "⬜️", "⬜️"] 4 | row3 = ["⬜️", "⬜️", "⬜️"] 5 | map = [row1, row2, row3] 6 | print(f"{row1}\n{row2}\n{row3}") 7 | position = input("Where do you want to put the treasure? ") 8 | # 🚨 Don't change the code above 👆 9 | 10 | # Write your code below this row 👇 11 | 12 | # Picking the user input. 13 | horPos = int(position[0]) 14 | verPos = int(position[1]) 15 | 16 | # Printing selected coordinate 17 | selectedRow = map[verPos - 1] 18 | selectedRow[horPos - 1] = "X" 19 | 20 | print(f"You've selected: {selectedRow}\n") 21 | 22 | # Write your code above this row 👆 23 | 24 | # 🚨 Don't change the code below 👇 25 | print(f"{row1}\n{row2}\n{row3}") 26 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/5-day-PRE-FizzBuzz.py: -------------------------------------------------------------------------------- 1 | #Write your code below this row 👇 2 | 3 | fizzMsg = "FIZZ" 4 | buzzMSG = "BUZZ" 5 | fizzBuzzMSG = "FIZZBUZZ" 6 | 7 | for fB in range(1, 101): 8 | 9 | if fB % 3 == 0 and fB % 5 == 0: 10 | print(fizzBuzzMSG) 11 | elif fB % 5 == 0: 12 | print(buzzMSG) 13 | elif fB % 3 == 0: 14 | print(fizzMsg) 15 | else: 16 | print(fB) 17 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/5-day-PRE-average-size.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | student_heights = input("Input a list of student heights ").split() 3 | for n in range(0, len(student_heights)): 4 | student_heights[n] = int(student_heights[n]) 5 | # 🚨 Don't change the code above 👆 6 | 7 | # Important You should not use the sum() or len() functions in your answer. You should try to replicate their functionality using what you have learnt about for loops. 8 | 9 | 10 | #Write your code below this row 👇 11 | masterSum = 0 12 | for sum in student_heights: 13 | masterSum += sum 14 | # print(masterSum) 15 | 16 | totalItems = 0 17 | for totalNum in student_heights: 18 | totalItems += 1 19 | # print(totalItems) 20 | 21 | calcFinal = masterSum/totalItems 22 | print(f"Average size: {calcFinal}cm") 23 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/5-day-PRE-for-loop-range.py: -------------------------------------------------------------------------------- 1 | # 001 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 2 | 3 | # 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 4 | 5 | # 0 + 1 = 1 6 | # 1 + 2 = 3 7 | # 3 + 3 = 6 8 | # 6 + 4 = 10 9 | # 10 + 5 = 15 10 | 11 | sumTotal = 0 12 | normalVl = [] 13 | 14 | for normalCount in range(1, 101): 15 | normalVl.append(normalCount) 16 | 17 | for number in range(1, len(normalVl)+1): 18 | sumTotal += number 19 | # Print just the final result of sumTotal. 20 | print(f"Carl Gauss method result: {sumTotal}") 21 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/5-day-PRE-highest-score.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | student_scores = input("Input a list of student scores ").split() 3 | for n in range(0, len(student_scores)): 4 | student_scores[n] = int(student_scores[n]) 5 | # print(student_scores) 6 | # 🚨 Don't change the code above 👆 7 | 8 | # Important you are not allowed to use the max() or min() functions. The output words must match the example. 9 | 10 | # Write your code below this row 👇 11 | highestNum = student_scores[0] 12 | for score in student_scores: 13 | if score > highestNum: 14 | highestNum = score 15 | print(f"The highest score in the class is: {highestNum}") 16 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/7-Day_Hangman-Step 2.py: -------------------------------------------------------------------------------- 1 | # Step 2 2 | 3 | import random 4 | word_list = ["aardvark", "baboon", "camel"] 5 | chosen_word = random.choice(word_list) 6 | debugMode = False 7 | displayCount = [] 8 | wordComplete = False 9 | 10 | if debugMode: 11 | # Testing code 12 | print(f'Pssst, the solution is {chosen_word}.') 13 | 14 | for listX in chosen_word: 15 | displayCount += "_" 16 | # TODO-1: - Create an empty List called display. 17 | # For each letter in the chosen_word, add a "_" to 'display'. 18 | # So if the chosen_word was "apple", display should be ["_", "_", "_", "_", "_"] with 5 "_" representing each letter to guess. 19 | print(displayCount) 20 | guess = input("Guess a letter: ").lower() 21 | displayCount = [] 22 | 23 | # TODO-2: - Loop through each position in the chosen_word; 24 | # If the letter at that position matches 'guess' then reveal that letter in the display at that position. 25 | # e.g. If the user guessed "p" and the chosen word was "apple", then display should be ["_", "p", "p", "_", "_"]. 26 | 27 | for letter in chosen_word: 28 | if letter == guess: 29 | if debugMode: 30 | print("Right") 31 | displayCount += letter 32 | else: 33 | if debugMode: 34 | print("Wrong") 35 | displayCount += "_" 36 | 37 | print(displayCount) 38 | 39 | # TODO-3: - Print 'display' and you should see the guessed letter in the correct position and every other letter replace with "_". 40 | # Hint - Don't worry about getting the user to guess the next letter. We'll tackle that in step 3. 41 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/7-Day_Hangman-Step 3.py: -------------------------------------------------------------------------------- 1 | # Step 3 2 | 3 | import random 4 | word_list = ["aardvark", "baboon", "camel"] 5 | chosen_word = random.choice(word_list) 6 | word_length = len(chosen_word) 7 | wordCompleted = False 8 | debugMode = False 9 | 10 | if debugMode: 11 | # Testing code 12 | print(f'Pssst, the solution is {chosen_word}.') 13 | 14 | # Create blanks 15 | display = [] 16 | for _ in range(word_length): 17 | display += "_" 18 | 19 | # TODO-1: - Use a while loop to let the user guess again. The loop should only stop once the user has guessed all the letters in the chosen_word and 'display' has no more blanks ("_"). Then you can tell the user they've won. 20 | 21 | # guess = input("Guess a letter: ").lower() 22 | 23 | # # Check guessed letter 24 | # for position in range(word_length): 25 | # letter = chosen_word[position] 26 | # if debugMode: 27 | # print( 28 | # f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}") 29 | # if letter == guess: 30 | # display[position] = letter 31 | 32 | # print(display) 33 | 34 | while "_" in display: 35 | wordCompleted = False 36 | guess = input("Guess a letter: ").lower() 37 | for position in range(word_length): 38 | letter = chosen_word[position] 39 | if debugMode: 40 | print( 41 | f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}") 42 | if letter == guess: 43 | display[position] = letter 44 | print(display) 45 | 46 | if "_" not in display: 47 | wordCompleted = True 48 | 49 | if wordCompleted == True: 50 | print("You won!") 51 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/7-Day_Hangman-Step 4.py: -------------------------------------------------------------------------------- 1 | # Step 4 2 | 3 | import random 4 | 5 | stages = [''' 6 | +---+ 7 | | | 8 | O | 9 | /|\ | 10 | / \ | 11 | | 12 | ========= 13 | ''', ''' 14 | +---+ 15 | | | 16 | O | 17 | /|\ | 18 | / | 19 | | 20 | ========= 21 | ''', ''' 22 | +---+ 23 | | | 24 | O | 25 | /|\ | 26 | | 27 | | 28 | ========= 29 | ''', ''' 30 | +---+ 31 | | | 32 | O | 33 | /| | 34 | | 35 | | 36 | =========''', ''' 37 | +---+ 38 | | | 39 | O | 40 | | | 41 | | 42 | | 43 | ========= 44 | ''', ''' 45 | +---+ 46 | | | 47 | O | 48 | | 49 | | 50 | | 51 | ========= 52 | ''', ''' 53 | +---+ 54 | | | 55 | | 56 | | 57 | | 58 | | 59 | ========= 60 | '''] 61 | 62 | # All stages 63 | # firstStage = stages[5] 64 | # secondStage = stages[4] 65 | # thirdStage = stages[3] 66 | # fourthStage = stages[2] 67 | # fifthStage = stages[1] 68 | # sixthStage = stages[0] 69 | 70 | # for stage in range(len(stages)): 71 | # print(stages[stage]) 72 | 73 | end_of_game = False 74 | lives = 6 75 | word_list = ["ardvark", "baboon", "camel"] 76 | chosen_word = random.choice(word_list) 77 | word_length = len(chosen_word) 78 | 79 | # TODO-1: - Create a variable called 'lives' to keep track of the number of lives left. 80 | # Set 'lives' to equal 6. 81 | 82 | # Testing code 83 | print(f'Pssst, the solution is {chosen_word}.') 84 | 85 | # Create blanks 86 | display = [] 87 | for _ in range(word_length): 88 | display += "_" 89 | 90 | while not end_of_game: 91 | guess = input("Guess a letter: ").lower() 92 | 93 | # Check guessed letter 94 | for position in range(word_length): 95 | letter = chosen_word[position] 96 | print( 97 | f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}") 98 | if letter == guess: 99 | display[position] = letter 100 | 101 | if guess not in chosen_word: 102 | lives -= 1 103 | # TODO-2: - If guess is not a letter in the chosen_word, 104 | # Then reduce 'lives' by 1. 105 | # If lives goes down to 0 then the game should stop and it should print "You lose." 106 | 107 | # Join all the elements in the list and turn it into a String. 108 | print(stages[lives]) 109 | print(f"{' '.join(display)}") 110 | # Check if user has got all letters. 111 | if "_" not in display: 112 | end_of_game = True 113 | print("You win.") 114 | if lives < 0 or lives == 0: 115 | end_of_game = True 116 | print("You lose.") 117 | # TODO-3: - print the ASCII art from 'stages' that corresponds to the current number of 'lives' the user has remaining. 118 | -------------------------------------------------------------------------------- /100 Days of Code/_preparations/7-day-hangman_progress.py: -------------------------------------------------------------------------------- 1 | import random 2 | # Step 1 3 | 4 | word_list = ["aardvark", "baboon", "camel"] 5 | 6 | # TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word. 7 | 8 | # TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase. 9 | 10 | # TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word. 11 | 12 | randomChoice = random.choice(word_list) 13 | 14 | userGuess = input("Guess a letter: ").lower() 15 | 16 | for hangProg in randomChoice: 17 | if userGuess == hangProg: 18 | print("Correct!") 19 | else: 20 | print("Incorrect!") 21 | -------------------------------------------------------------------------------- /Advanced Application/API-Obfuscator/Data/security/API: -------------------------------------------------------------------------------- 1 | c2FnYXMzNDU0My10cnktcG9wMDk4 -------------------------------------------------------------------------------- /Advanced Application/API-Obfuscator/main.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import pathlib 3 | import os 4 | import re 5 | import string 6 | from pathlib import Path 7 | 8 | 9 | os.system("clear") 10 | 11 | 12 | # Dynamic File Path Solution 13 | API_PATH = pathlib.Path(__file__).parent.absolute() 14 | 15 | 16 | def relative_to_assets(path: str) -> Path: 17 | return API_PATH / Path(path) 18 | 19 | 20 | shiftAlpha = 4 21 | API_CONTENT = None 22 | # 🔐 Security execution READ 23 | 24 | 25 | def API_SEC(): 26 | global API_CONTENT 27 | global shiftAlpha 28 | 29 | # Caesar Cipher 30 | alphaCharset = string.ascii_letters 31 | numCharset = string.digits 32 | charsetMain = alphaCharset + numCharset 33 | 34 | totalNum = 0 35 | for i in range(len(charsetMain)): 36 | totalNum += i 37 | 38 | shiftAlpha %= totalNum 39 | 40 | unshiftAlpha = -shiftAlpha 41 | 42 | alphaUnshifted = None 43 | alphaUnshifted = charsetMain[unshiftAlpha:] + charsetMain[:unshiftAlpha] 44 | tableContentUn = str.maketrans(charsetMain, alphaUnshifted) 45 | 46 | # Security measures 47 | API_CONTENT = open(relative_to_assets("Data/security/API"), "r").read() 48 | API_DECODED = base64.b64decode(API_CONTENT.encode("utf-8")) 49 | 50 | # Regular expression to remove garbage characters, do not remove "-" 51 | API_DECODED_CLEAN = re.sub( 52 | r"[^A-Za-z0-9-]", "", API_DECODED.decode("utf-8")) 53 | 54 | UNLOCKED_CONTENT = str(API_DECODED_CLEAN).translate(tableContentUn) 55 | 56 | return UNLOCKED_CONTENT 57 | 58 | 59 | print("\nAdd your API here.\nNEVER CHANGE THE API KEY DIRECTLY\nFOR SECURITY REASONS!\n") 60 | userChange = input("Enter API key: ").strip() 61 | 62 | # Caesar Cipher 63 | alphaCharset = string.ascii_letters 64 | numCharset = string.digits 65 | # Combine both alphaCharset with numCharset in one variable 66 | charsetMain = alphaCharset + numCharset 67 | 68 | totalNum = 0 69 | for i in range(len(charsetMain)): 70 | totalNum += i 71 | 72 | # print(totalNum) 73 | shiftAlpha = 4 74 | shiftAlpha %= totalNum 75 | 76 | alphaShifted = None 77 | alphaShifted = charsetMain[shiftAlpha:] + charsetMain[:shiftAlpha] 78 | tableContent = str.maketrans(charsetMain, alphaShifted) 79 | 80 | CIPHER_APPLIED = userChange.translate(tableContent) 81 | 82 | # Pick userChange and encode it to base64 83 | userChange = base64.b64encode(CIPHER_APPLIED.encode('utf-8')) 84 | # Save userChange to "API" file 85 | with open(relative_to_assets('Data/security/API'), 'wb') as f: 86 | # Delete everything inside the file. 87 | f.truncate() 88 | f.write(userChange) 89 | 90 | print("DONE! You are ready to use the API!") 91 | 92 | userChoice = input("\nDo you want to check the API? (y/n) ").strip() 93 | 94 | if userChoice == "y": 95 | print(f"Your API decoded is: \n{API_SEC()}\nEncoded is: {API_CONTENT}") 96 | else: 97 | exit() 98 | -------------------------------------------------------------------------------- /Advanced Application/Self_Destructor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import sys 4 | import subprocess 5 | 6 | 7 | current_dir = os.path.dirname(sys.argv[0]) 8 | targetDirectory = "test" 9 | fixDirPath = current_dir.replace(" ", "\\ ").replace("?", "\\?").replace("&", "\\&").replace( 10 | "(", "\\(").replace(")", "\\)").replace("*", "\\*").replace("<", "\\<").replace(">", "\\>") 11 | 12 | dailyTimer = 10 13 | enableCustomHour = True 14 | customHour = "03:00PM" 15 | 16 | userCorrect = None 17 | 18 | print(f"{fixDirPath}/{targetDirectory}") 19 | userPermission = input("What is the password? \n") 20 | 21 | 22 | def deleteFiles(): 23 | if userCorrect == False: 24 | print("Deleting files...") 25 | os.system(f"rm -rf {str(fixDirPath)}/{str(targetDirectory)}") 26 | 27 | # if enableCustomHour: 28 | # if customHour == time.strftime("%I:%M%p"): 29 | # print("Time to delete files!") 30 | # os.system("rm -rf " + str(targetDirectory)) 31 | # else: 32 | # pass 33 | 34 | 35 | if userPermission != "AbC=CdE": 36 | print("Incorrect password... Cleaning process initiated!") 37 | userCorrect = False 38 | deleteFiles() 39 | 40 | elif userPermission == "AbC=CdE": 41 | print("Thank you!") 42 | userCorrect = True 43 | exit() 44 | -------------------------------------------------------------------------------- /Advanced Application/Simple_API_study.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple API study inside Python. 3 | Using Random Fox website to study API. 4 | All HTTP response codes here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status 5 | 6 | Basic sheet: 7 | 8 | - Informational responses (100–199) 9 | - Successful responses (200–299) 10 | - Redirects (300–399) 11 | - Client errors (400–499) 12 | - Server errors (500–599) 13 | """ 14 | 15 | import requests 16 | import json 17 | 18 | # Getting the API url/path 19 | responseAPI = requests.get('https://randomfox.ca/floof') 20 | 21 | # print(responseAPI.status_code) # This will return a simple status code. 22 | # print(responseAPI.text) # This will return a string value with the contents inside the API URL. 23 | # 24 | # Usually this will return a json. 25 | # Output from the responseAPI.text => {"image":"https:\/\/randomfox.ca\/images\/25.jpg","link":"https:\/\/randomfox.ca\/?i=25"} 26 | # Ok that's basicallly a json file, this is a web standard way to use API, so now we need to convert it to a python dictionary with json module. 27 | # 28 | # print(responseAPI.json()) 29 | # 30 | # Awesome, now with the json() function, we have a dictionary. 31 | # Output: {'image': 'https://randomfox.ca/images/13.jpg', 'link': 'https://randomfox.ca/?i=13'} 32 | # Now let's play with variables and the API dictionary. 33 | # 34 | generatedFoxImg = responseAPI.json() 35 | 36 | print("\nHere are all values from the API: \n") 37 | # Let's pick each dictionary element individually and print it. 38 | print(f"Your random fox: {generatedFoxImg['image']} \n") 39 | print(f"Link to that fox: {generatedFoxImg['link']} \n") 40 | -------------------------------------------------------------------------------- /Advanced Application/XOR Cipher/Data/security/.KEY.nclmE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Advanced Application/XOR Cipher/Data/security/.KEY.nclmE -------------------------------------------------------------------------------- /Advanced Application/XOR Cipher/Decryptor.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | import base64 3 | import os 4 | import pathlib 5 | import re 6 | import string 7 | from pathlib import Path 8 | import signal 9 | 10 | # Nick's security protocol 11 | os.system("clear") 12 | 13 | # Dynamic File Path Solution 14 | KEY_PATH = pathlib.Path(__file__).parent.absolute() 15 | 16 | 17 | def relative_to_assets(path: str) -> Path: 18 | return KEY_PATH / Path(path) 19 | 20 | 21 | def signal_handler(sig, frame): 22 | # If the program exits then remove important files. 23 | os.remove(relative_to_assets("Data/security/.tmp/.KEY")) 24 | exit() 25 | 26 | 27 | def decryptSecurity(): 28 | # Use external script to make base64 or https://www.base64encode.org/ 29 | key = "MTMy" # up 255 30 | key = base64.b64decode(key) 31 | cleanKey = re.sub( 32 | r"[^A-Za-z0-9-]", "", key.decode("utf-8")) 33 | finalKey = int(cleanKey) 34 | 35 | loadEnc00 = open(relative_to_assets( 36 | "Data/security/.KEY.nclmE"), "rb").read() 37 | 38 | byteReader = bytearray(loadEnc00) 39 | for index, value in enumerate(byteReader): 40 | byteReader[index] = value ^ finalKey 41 | 42 | decEnc = open(relative_to_assets("Data/security/.tmp/.KEY"), "wb") 43 | decEnc.write(byteReader) 44 | 45 | 46 | try: 47 | # signal handler for "CTRL + C" 48 | signal.signal(signal.SIGINT, signal_handler) 49 | decryptSecurity() 50 | signal.pause() 51 | except: 52 | # Before exit the script will remove decrypted files. 53 | os.remove(relative_to_assets("Data/security/.tmp/.KEY")) 54 | -------------------------------------------------------------------------------- /Advanced Application/XOR Cipher/Encryptor.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | import base64 3 | import os 4 | import pathlib 5 | import re 6 | from pathlib import Path 7 | 8 | # Nick's security protocol 9 | os.system("clear") 10 | 11 | # Dynamic File Path Solution 12 | KEY_PATH = pathlib.Path(__file__).parent.absolute() 13 | 14 | 15 | def relative_to_assets(path: str) -> Path: 16 | return KEY_PATH / Path(path) 17 | 18 | 19 | def encryptSecurity(): 20 | # Use external script to make base64 or https://www.base64encode.org/ 21 | key = "MTMy" # up 255 22 | key = base64.b64decode(key) 23 | cleanKey = re.sub( 24 | r"[^A-Za-z0-9-]", "", key.decode("utf-8")) 25 | finalKey = int(cleanKey) 26 | 27 | loadEnc00 = open(relative_to_assets("Data/security/.KEY"), "rb") 28 | byteReaderData = loadEnc00.read() 29 | loadEnc00.close() 30 | 31 | byteReaderData = bytearray(byteReaderData) 32 | for index, value in enumerate(byteReaderData): 33 | byteReaderData[index] = value ^ finalKey 34 | 35 | Enc = open(relative_to_assets("Data/security/.KEY.nclmE"), "wb") 36 | Enc.write(byteReaderData) 37 | Enc.close() 38 | 39 | # Delete Data/security/KEY 40 | os.remove(relative_to_assets("Data/security/.KEY")) 41 | 42 | 43 | encryptSecurity() 44 | -------------------------------------------------------------------------------- /Advanced Application/fast-api-study/__pycache__/fast_api_study.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Advanced Application/fast-api-study/__pycache__/fast_api_study.cpython-39.pyc -------------------------------------------------------------------------------- /Advanced Application/fast-api-study/fast_api_study.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fast API study inside Python. 3 | All HTTP response codes here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status 4 | To run this script: "uvicorn fast_api_study:appStudy --reload" 5 | Always test things on the docs page: http://127.0.0.1:8000/docs 6 | 7 | Basic response sheet: 8 | 9 | - Informational responses (100–199) 10 | - Successful responses (200–299) 11 | - Redirects (300–399) 12 | - Client errors (400–499) 13 | - Server errors (500–599) 14 | 15 | Requirements: 16 | 17 | - Python 3.5+ (Used for this script: Python 3.9.2) 18 | - fastapi (3.7.4) 19 | - uvicorn (7.1.2) 20 | 21 | Summary: 22 | 23 | - ⚙️ Initial setup of fast API 24 | - 🔖 GET method 25 | - ✍️ POST method 26 | - 🎭 PUT method 27 | """ 28 | 29 | # ============================== ⚙️ Initial setup of fast API ============================== 30 | from fastapi import FastAPI, Path 31 | from fastapi.params import Query 32 | # It's recommended from the FastAPI documentation to import the following when using option parameters: 33 | from typing import Optional 34 | # Importing module for POST requests: 35 | from pydantic import BaseModel 36 | # Importing module for PUT requests: 37 | from fastapi.encoders import jsonable_encoder 38 | 39 | # This function is needed to start the API application. 40 | appStudy = FastAPI() 41 | 42 | 43 | # This class is for the POST request, you can come back here when you reach ✍️ POST method 44 | class Item(BaseModel): 45 | name: str 46 | price: float 47 | # Optional parameter using Optional[] and None. 48 | quantity: Optional[int] = None 49 | 50 | 51 | # This class is for the PUT request, you can come back here when you reach 🎭 PUT method 52 | class updateItem(BaseModel): 53 | name: Optional[str] = None 54 | price: Optional[float] = None 55 | quantity: Optional[int] = None 56 | 57 | # ============================== 🔖 GET method ============================== 58 | # 59 | # Now let's create an endpoint. 60 | # An API endpoint is the point of entry in a communication channel when two systems are interacting. 61 | # It refers to touchpoints of the communication between an API and a server. 62 | # For example: 63 | # /hello 64 | # /hello/world 65 | # These are endpoints from a server or URL. In this case we are using our machine, that means: 66 | # http://localhost:8000/hello 67 | # 68 | # Now we need to create an endpoint method. These are all methods: 69 | # 70 | # GET, used to retrieve data from a server. 71 | # POST, used to send data to a server, change values or create new data. 72 | # PUT, used to update data on a server. 73 | # DELETE, used to delete data on a server. 74 | # PATCH, used to update data on a server without changing all the data. 75 | # OPTIONS, used to retrieve information about the communication options available on a server. 76 | # HEAD, used to retrieve only the headers of a response. 77 | # CONNECT, used to connect to a remote server. 78 | # TRACE, used to retrieve the entire request message as received by the server. 79 | # 80 | # Now we need to create a function that will be called when the endpoint is called. 81 | # And call the method with ".get("PATH_HERE")" for example. 82 | # 83 | 84 | 85 | @appStudy.get("/") 86 | def returnAPIValues(): 87 | # Here we make a python dictionary that can be a json. 88 | # And now we need to open this script with "uvicorn fast_api_study:appStudy --reload" where the script file is located. 89 | # The syntax is simple: "uvicorn SCRIPT_NAME:FastAPI()-FUNCTION_VAR --reload" 90 | return {"DataStudy:": "Hello World!", "TestFieldTwo:": "test"} 91 | 92 | # After running the script with uvicorn, test the documentation here: http://127.0.0.1:8000/docs 93 | 94 | 95 | # Let's make more endpoints to test. 96 | @appStudy.get("/about") 97 | def returnAbout(): 98 | return {"DataStudy:": "About"} 99 | 100 | 101 | # Now let's play with some Inventory Management system, like a store does. 102 | # This is actually the API values 103 | inventoryDict = { 104 | "1": {"name": "Bread", "price": 1.25, "quantity": "10"}, 105 | "2": {"name": "Milk", "price": 2.45, "quantity": "5"}, 106 | "3": {"name": "Eggs", "price": 3.99, "quantity": "20"}, 107 | "4": {"name": "Cheese", "price": 4.99, "quantity": "15"}, 108 | "5": {"name": "Butter", "price": 5.00, "quantity": "5"} 109 | } 110 | 111 | 112 | # Now let's setup an endpoint. In this case, we are going to retrieve information from the inventory based on it's id. 113 | @appStudy.get("/get-item/{individual_item_id}", response_model=updateItem) 114 | # Ok, now we need to make a function with the individual item id with an INT type 115 | # and add Path() parameter to add more details to a path parameter. 116 | def getItem(individual_item_id: int = Path(None, description="The ID of the item you like to view")): 117 | return inventoryDict[str(individual_item_id)] 118 | 119 | 120 | # Now we will need to work with query parameters. 121 | # for example: facebook.com/home?redirect=Test&id=1 122 | # Query parameters are basically syntaxed by "?" and "&" 123 | @appStudy.get("/get-by-item-name") 124 | # Observe that name: str don't have a Path() and it have a None value, which implies that this parameter name is optional. 125 | # It's recommended from the FastAPI documentation to import optional module and use it in optional parameters. 126 | def getItemName(name: Optional[str] = None): 127 | for invID in inventoryDict: 128 | if inventoryDict[invID]["name"] == name: 129 | return inventoryDict[invID] 130 | return inventoryDict["DataErr": "Item not found"] 131 | # Ok let's test it here: http://127.0.0.1:8000/get-by-item-name?name=Bread 132 | # output: {"name":"Bread","price":1.25,"quantity":"10"} 133 | 134 | 135 | # Great, now let's add a required parameter with the optional one and call it. 136 | @appStudy.get("/test-multi-param") 137 | # The idea here is to combine the name string parameter (optional) with a test int parameter. 138 | # With the "*" basically we are saying that there is no limit for parameters in this call function without an order. 139 | def getMultiItem(*, name: Optional[str] = None, test: int): 140 | for invID in inventoryDict: 141 | if inventoryDict[invID]["name"] == name: 142 | return inventoryDict[invID] 143 | return inventoryDict["DataErr": "Item not found"] 144 | # Again, let's test it here: http://127.0.0.1:8000/test-multi-param?test=2&name=Milk 145 | # output: {"name":"Milk","price":2.45,"quantity":"5"} 146 | 147 | 148 | # Let's combine path paramerters with query parameters together. 149 | @appStudy.get("/get-by-item-name/{item_id}") 150 | def getMultiItem(*, name: Optional[str] = None, item_id: int, test: int): 151 | for invID in inventoryDict: 152 | if inventoryDict[invID]["name"] == name: 153 | return inventoryDict[invID] 154 | return inventoryDict["DataErr": "Item not found"] 155 | # Testing it here: http://127.0.0.1:8000/get-by-item-name/1/?test=2&name=Bread 156 | 157 | 158 | # ============================== ✍️ POST method ============================== 159 | # All good! Now let's study how POST method works. 160 | @appStudy.post("/post-item/{item_id}") 161 | def createItem(item_id: int, item: Item): 162 | # Let's create a new item id. 163 | if item_id in inventoryDict: 164 | return {"DataErr": "Item already exists"} 165 | else: 166 | inventoryDict[str(item_id)] = item 167 | return inventoryDict[str(item_id)] 168 | # Testing here http://127.0.0.1:8000/docs#/default/getItem_get_item__individual_item_id__get 169 | # by using the POST to add some eggs and then check if it worked using the check by id GET. 170 | # Remeber that this method will be storing data on the RAM, this is not persistent, when the server reloads it will clear the POST data. 171 | 172 | 173 | # ============================== 🎭 PUT method ============================== 174 | # Time to study the PUT method! 175 | @appStudy.put("/put-item/{item_id}") 176 | def createItem(item_id: int, item: Item): 177 | # Let's create a new item id. 178 | if item_id in inventoryDict: 179 | return {"DataErr": "Item already exists"} 180 | else: 181 | inventoryDict[str(item_id)] = item 182 | return inventoryDict[str(item_id)] 183 | # Testing here http://127.0.0.1:8000/docs#/default/getItem_get_item__individual_item_id__get 184 | 185 | 186 | # ============================== 🎭 DELETE method ============================== 187 | @appStudy.delete("/delete-item/{item_id}") 188 | def createItem(item_id: int = Query(..., description="The ID of the item you like to delete")): 189 | # Let's create a new item id. 190 | if item_id in inventoryDict: 191 | return {"DataErr": "Item already exists"} 192 | else: 193 | del inventoryDict[str(item_id)] 194 | return {"Data DELETED": "Item deleted."} 195 | -------------------------------------------------------------------------------- /Advanced Application/json-reader/json-reader.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | import os 4 | 5 | userContent = {} 6 | current_dir = os.path.dirname(sys.argv[0]) 7 | 8 | with open(f"{current_dir}/sample-json.json", "r") as json_file: 9 | userContent = json.load(json_file) 10 | print(userContent["username"]) 11 | print(userContent["password"]) 12 | 13 | userInp = input("Enter your username: ") 14 | userInp2 = input("Enter your password: ") 15 | userContent["username"] = f"{str(userInp)}" 16 | userContent["password"] = f"{str(userInp2)}" 17 | 18 | 19 | with open(f"{current_dir}/sample-json.json", "w") as json_file: 20 | json.dump(userContent, json_file) 21 | print(f"The new username is: {str(userContent['username'])}") 22 | print(f"The new password is: {str(userContent['password'])}") 23 | -------------------------------------------------------------------------------- /Advanced Application/json-reader/sample-json.json: -------------------------------------------------------------------------------- 1 | { 2 | "username": "testABC", 3 | "password": "testDEF" 4 | } 5 | -------------------------------------------------------------------------------- /Advanced Application/password_generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Variables 4 | lowerCase = "abcdefghijklmnopqrstuvwxyz" 5 | upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 6 | numericApproach = "1234567890" 7 | symbolsCharacters = "[]{}()*&%#@!;:/,_-" 8 | 9 | mergeApproaches = lowerCase + upperCase + numericApproach + symbolsCharacters 10 | 11 | 12 | 13 | # Password generator def 14 | def genPass(): 15 | lengthPasswd = input("What is the password length? ") 16 | passwdFinal = "".join(random.sample(mergeApproaches, int(lengthPasswd))) 17 | print(passwdFinal) 18 | tryOther = input("Try again? (y/n) ") 19 | if tryOther == "y": 20 | print("\n") 21 | genPass() 22 | else: 23 | print("\n") 24 | exit() 25 | 26 | 27 | if __name__ == "__main__": 28 | genPass() 29 | -------------------------------------------------------------------------------- /Advanced Application/phone_number_details.py: -------------------------------------------------------------------------------- 1 | """ 2 | Documentation 3 | https://pypi.org/project/phonenumbers/ 4 | """ 5 | import phonenumbers 6 | from phonenumbers import geocoder, carrier, timezone 7 | 8 | print("Welcome to Phone Number Details.") 9 | print("Sample number: +442083661177") 10 | deviceNumber = input("Enter the phone number: ") 11 | deviceNumber = phonenumbers.parse(str(deviceNumber)) 12 | print(deviceNumber) 13 | 14 | # get timezone from phone number and print it 15 | timezone_result = timezone.time_zones_for_number(deviceNumber) 16 | print("Timezone: ", timezone_result[0]) 17 | 18 | # get carrier from device number and print it 19 | carrier_result = carrier.name_for_number(deviceNumber, None) 20 | print("Carrier: ", carrier_result) 21 | 22 | # get location from device number and print it 23 | location_result = geocoder.description_for_number(deviceNumber, None) 24 | print("Location: ", location_result) 25 | 26 | # validate device number and print it 27 | print("Is valid: ", phonenumbers.is_valid_number(deviceNumber)) 28 | 29 | # check possibility of a number. 30 | print("Possible: ", phonenumbers.is_possible_number(deviceNumber)) 31 | -------------------------------------------------------------------------------- /Advanced Application/stock_data_driven_web_app.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import streamlit as st 3 | import pandas as pd 4 | 5 | st.write( 6 | """ 7 | # Nick Stock Tracker 8 | Here is all targets for the next 6 months. 9 | """ 10 | ) 11 | 12 | # Documentation from https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75 13 | # Define the ticker symbol, get data from it and history. 14 | # How this will show up: 15 | # Open -> High -> Low -> Close -> Volume -> Dividends -> Stock -> Splits 16 | # streamlit run stock_data_driven_web_app.py 17 | 18 | """ 19 | ## HubSpot Global 20 | 21 | ### Market Open/Close 22 | """ 23 | stockCode = 'HUBS' 24 | stockData = yf.Ticker(stockCode) 25 | stockHistory = stockData.history( 26 | period='1d', start='2019-01-01', end='2021-09-01') 27 | 28 | st.line_chart(stockHistory.Close) 29 | """ 30 | ### Market Volume 31 | """ 32 | st.line_chart(stockHistory.Volume) 33 | 34 | 35 | """ 36 | ## Qualcomm Inc. Global 37 | 38 | ### Market Open/Close 39 | """ 40 | stockCode = 'QCOM' 41 | stockData = yf.Ticker(stockCode) 42 | stockHistory = stockData.history( 43 | period='1d', start='2018-01-01', end='2021-09-01') 44 | 45 | st.line_chart(stockHistory.Close) 46 | """ 47 | ### Market Volume 48 | """ 49 | st.line_chart(stockHistory.Volume) 50 | 51 | 52 | """ 53 | ## Electronic Arts Inc. Global 54 | 55 | ### Market Open/Close 56 | """ 57 | stockCode = 'EA' 58 | stockData = yf.Ticker(stockCode) 59 | stockHistory = stockData.history( 60 | period='1d', start='2000-01-01', end='2021-09-01') 61 | 62 | st.line_chart(stockHistory.Close) 63 | """ 64 | ### Market Volume 65 | """ 66 | st.line_chart(stockHistory.Volume) 67 | -------------------------------------------------------------------------------- /Advanced Application/website_link_extractor.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | print("Welcome to Website Link Extractor.") 6 | targetURL = input("Add here the target website to extract links: ") 7 | 8 | requestFromURL = requests.get(targetURL).content 9 | soupModule = BeautifulSoup(requestFromURL, "html.parser") 10 | linksFinder = soupModule.find_all("a") 11 | 12 | for link in linksFinder: 13 | print(link.get("href")) 14 | 15 | saveFile = input( 16 | "Do you want to save this list inside a text file? (y/n) ") 17 | if saveFile == "y": 18 | with open("links.txt", "a") as file: 19 | file.write(link.get("href") + "\n") 20 | else: 21 | pass 22 | -------------------------------------------------------------------------------- /Conversion Scripts/Image-Optimizer/image-optimizer.py: -------------------------------------------------------------------------------- 1 | """ Script made to optimize PNG, JPG, JPEG and SVG from a folder to make it clean and compressed. 2 | This is not just an experimental script, but a need to my daily work as a DevOps. 3 | """ 4 | 5 | import PIL 6 | from PIL import Image 7 | import os 8 | import sys 9 | from pathlib import Path 10 | import pathlib 11 | 12 | OUTPUT_PATH = pathlib.Path(__file__).parent.absolute() 13 | ASSETS_PATH = OUTPUT_PATH / Path("original_images") 14 | 15 | 16 | def relative_to_assets(path: str) -> Path: 17 | return ASSETS_PATH / Path(path) 18 | 19 | 20 | files = os.listdir(ASSETS_PATH) 21 | 22 | print(f"These are all of the files in our current working directory: {files}") 23 | confirmFiles = input("Confirm files? (Y/n) ") 24 | confirmDownRes = input("Do you want to reduce the resolution by 50%? (Y/n) ") 25 | 26 | 27 | if confirmDownRes == "y" or confirmDownRes == "Y" or confirmDownRes == "": 28 | confirmReduction = True 29 | 30 | if confirmFiles == "y" or confirmFiles == "Y" or confirmFiles == "": 31 | for file in files: 32 | if file.endswith(".png") or file.endswith(".jpg") or file.endswith(".jpeg"): 33 | print(f"Optimizing {file}") 34 | imgOptimize = Image.open(relative_to_assets(str(file))) 35 | imgWidth, imgHeight = imgOptimize.size 36 | if confirmReduction == True: 37 | imgOptimize = imgOptimize.resize( 38 | (int(imgWidth / 2), int(imgHeight / 2)), PIL.Image.ANTIALIAS) 39 | 40 | if file.endswith(".png"): 41 | imgOptimize.save(str(relative_to_assets( 42 | str(file))), optimize=True, quality=70) 43 | if file.endswith(".jpg") or file.endswith(".jpeg"): 44 | imgOptimize.save(str(relative_to_assets( 45 | str(file))), optimize=True, quality=80) 46 | else: 47 | if file.endswith(".png"): 48 | imgOptimize.save(str(relative_to_assets( 49 | str(file))), optimize=True, quality=70) 50 | if file.endswith(".jpg") or file.endswith(".jpeg"): 51 | imgOptimize.save(str(relative_to_assets( 52 | str(file))), optimize=True, quality=80) 53 | print(f"{file} optimized!") 54 | else: 55 | print(f"{file} is not a PNG or JPG, skipping") 56 | else: 57 | print("Exiting...") 58 | sys.exit() 59 | 60 | # Testing modules 61 | # imgOptimize = Image.open(files) 62 | # imgHeight, imgWidth = imgOptimize.size 63 | # imgOptimize = imgOptimize.resize((int(imgWidth / 2), int(imgHeight / 2)), PIL.Image.ANTIALIAS) 64 | # imgOptimize.save(ASSETS_PATH / Path("optimized_images/optimized_image.png"), optimize=True, quality=95) 65 | -------------------------------------------------------------------------------- /Conversion Scripts/Image-Optimizer/original_images/sampleOriginal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Conversion Scripts/Image-Optimizer/original_images/sampleOriginal.jpg -------------------------------------------------------------------------------- /Conversion Scripts/Image-Optimizer/sampleOriginal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Conversion Scripts/Image-Optimizer/sampleOriginal.jpg -------------------------------------------------------------------------------- /Conversion Scripts/OrdinalNum2Roman.py: -------------------------------------------------------------------------------- 1 | # Ordinal Numbers to Roman Numbers converter by Nicolas Mendes - September 2021 2 | import sys 3 | 4 | # Mapping all Romman numbers combinations 5 | num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), 6 | (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] 7 | 8 | # Function to convert the numbers to roman values. Based on NullDev algorithm. 9 | 10 | 11 | def num2roman(num): 12 | 13 | roman = '' 14 | 15 | while num > 0: 16 | for i, r in num_map: 17 | while num >= i: 18 | roman += r 19 | num -= i 20 | 21 | return roman 22 | 23 | 24 | # Print roman value. 25 | print(num2roman(int(input("Enter a number: ")))) 26 | # After the input, ask if the user wants to continue, and make the default answer to yes. 27 | while True: 28 | answer = input("Do you want to try again? (Y/n) ") 29 | if answer == 'y' or answer == 'Y' or sys.stdin.isatty(): 30 | num = int(input("Enter a number: ")) 31 | print(num2roman(num)) 32 | elif answer == 'n': 33 | break 34 | else: 35 | print("Invalid input.") 36 | -------------------------------------------------------------------------------- /Conversion Scripts/PNG-and-JPG-to-WebP/original_images/sampleOptimized-converted.jpg.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Conversion Scripts/PNG-and-JPG-to-WebP/original_images/sampleOptimized-converted.jpg.webp -------------------------------------------------------------------------------- /Conversion Scripts/PNG-and-JPG-to-WebP/png_jpg_to_webp.py: -------------------------------------------------------------------------------- 1 | """ Script made to convert PNG or JPG from a folder to WebP format. 2 | This is not just an experimental script, but a need to my daily work as a DevOps. 3 | """ 4 | 5 | from PIL import Image 6 | import os 7 | import sys 8 | from pathlib import Path 9 | import pathlib 10 | 11 | 12 | OUTPUT_PATH = pathlib.Path(__file__).parent.absolute() 13 | ASSETS_PATH = OUTPUT_PATH / Path("original_images") 14 | 15 | def relative_to_assets(path: str) -> Path: 16 | return ASSETS_PATH / Path(path) 17 | 18 | # Testing modules 19 | # loadImg = Image.open(relative_to_assets("image_test.jpg")).convert("RGB") 20 | # loadImg.save(relative_to_assets("image_test.webp"), "WEBP", quality=80) 21 | 22 | 23 | # We list all of the files and folders using os.listdir() 24 | files = os.listdir(ASSETS_PATH) 25 | 26 | print(f"These are all of the files in our current working directory: {files}") 27 | confirmFiles = input("Confirm files? (Y/n) ") 28 | 29 | if confirmFiles == "y" or confirmFiles == "Y" or confirmFiles == "": 30 | for file in files: 31 | if file.endswith(".png") or file.endswith(".jpg") or file.endswith(".jpeg"): 32 | print(f"Converting {file} to WebP") 33 | loadImg = Image.open(relative_to_assets(str(file))) 34 | loadImg.save(str(relative_to_assets(str(file))) + 35 | ".webp", "WEBP", quality=80) 36 | print(f"{file} converted to WebP") 37 | else: 38 | print(f"{file} is not a PNG or JPG, skipping...") 39 | else: 40 | print("Exiting...") 41 | sys.exit() 42 | -------------------------------------------------------------------------------- /Conversion Scripts/PNG-and-JPG-to-WebP/sampleOriginal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Conversion Scripts/PNG-and-JPG-to-WebP/sampleOriginal.jpg -------------------------------------------------------------------------------- /Conversion Scripts/days_hours_minutes_to_seconds.py: -------------------------------------------------------------------------------- 1 | dayQty = input("How many days? ") 2 | hourQty = input("How many hours? ") 3 | minuteQty = input("How many minutes? ") 4 | 5 | print("In " + dayQty + " days, " + hourQty + " hours, and " + minuteQty + " minutes, there are " + 6 | str(int(dayQty) * 86400 + int(hourQty) * 3600 + int(minuteQty) * 60) + " seconds.") 7 | -------------------------------------------------------------------------------- /Conversion Scripts/minutes_to_years.py: -------------------------------------------------------------------------------- 1 | minutes = "24.785089" 2 | print(minutes + " minutes is equal to " + 3 | str(float(minutes)/60/24/365) + " years.") 4 | -------------------------------------------------------------------------------- /Conversion Scripts/seconds_to_days_hours_minutes.py: -------------------------------------------------------------------------------- 1 | secsQty = input("Enter the number of seconds: ") 2 | secsQty = int(secsQty) 3 | 4 | # convert seconds in minutes. 5 | minutes = secsQty // 60 6 | # convert seconds in hours. 7 | hours = minutes // 60 8 | # convert seconds in days. 9 | days = hours // 24 10 | 11 | print(str(secsQty) + " seconds is equal to " + str(minutes) + " minutes, " + 12 | str(hours) + " hours, and " + str(days) + " days.") 13 | -------------------------------------------------------------------------------- /Conversion Scripts/temperature_conversion.py: -------------------------------------------------------------------------------- 1 | print("1. Celsius to Fahrenheit") 2 | print("2. Fahrenheit to Celsius") 3 | whatType = input("What temperature scale do you want to convert from? ") 4 | 5 | if whatType == "1": 6 | celsius = float(input("Enter the temperature in Celsius: ")) 7 | fahrenheit = celsius * 9 / 5 + 32 8 | print("The temperature in Fahrenheit is", fahrenheit) 9 | elif whatType == "2": 10 | fahrenheit = float(input("Enter the temperature in Fahrenheit: ")) 11 | celsius = (fahrenheit - 32) * 5 / 9 12 | print("The temperature in Celsius is", celsius) 13 | else: 14 | print("Invalid input") 15 | print("Please try again") 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Math Scripts/math-circle_area.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interesting resources: 3 | https://docs.python.org/3/library/functions.html#built-in-functions 4 | https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex 5 | https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals 6 | https://docs.python.org/3/tutorial/introduction.html#numbers 7 | https://docs.python.org/3/tutorial/modules.html#modules 8 | """ 9 | 10 | circleRay = float(input("Enter the circle's radius in square meters: ")) 11 | # Calculate the circle's area in square meters 12 | circleArea = circleRay ** 2 * 3.14159 13 | # Print the circle's area in square meters 14 | print("The circle's area is {:.2f} m2.".format(circleArea)) 15 | -------------------------------------------------------------------------------- /Math Scripts/math-fibonacci.py: -------------------------------------------------------------------------------- 1 | """ 2 | In Mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation: 3 | Fn = Fn-1 + Fn-2 4 | Sample with Seed: 5 | F0 = 0 and F1 = 1 6 | Sequence sample: 7 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377... 8 | """ 9 | 10 | fibonacciSequence = [0, 1] 11 | 12 | 13 | def startUsrInput(): 14 | print("Welcome to the Fibonacci Sequence Calc.") 15 | fibUsrGift = input("Type a number for the Fibonacci sequence: ") 16 | fibUsrGift = int(fibUsrGift) 17 | print(fibonacciFunction(fibUsrGift)) 18 | 19 | 20 | def fibonacciFunction(n): 21 | if n <= 1: 22 | print("Not valid.") 23 | elif n <= len(fibonacciSequence): 24 | return fibonacciSequence[n-1] 25 | else: 26 | fibCalc = fibonacciFunction(n-1) + fibonacciFunction(n-2) 27 | fibonacciSequence.append(fibCalc) 28 | return fibCalc 29 | 30 | 31 | if __name__ == "__main__": 32 | startUsrInput() -------------------------------------------------------------------------------- /Math Scripts/math-rectangle_area_equation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interesting resources: 3 | https://docs.python.org/3/library/functions.html#built-in-functions 4 | https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex 5 | https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals 6 | https://docs.python.org/3/tutorial/introduction.html#numbers 7 | https://docs.python.org/3/tutorial/modules.html#modules 8 | """ 9 | 10 | 11 | def welcome(): 12 | print("Welcome! Let's calculate the rectagle.") 13 | units = input( 14 | "Please enter the units to use (square meters or centimeters): ") 15 | 16 | if units == "square meters": 17 | width = float( 18 | input("Please enter the width of the rectangle in meters: ")) 19 | height = float( 20 | input("Please enter the height of the rectangle in meters: ")) 21 | print("The area of the rectangle is: ", 22 | width * height, "square meters") 23 | startAgain() 24 | elif units == "centimeters": 25 | width = float( 26 | input("Please enter the width of the rectangle in centimeters: ")) 27 | height = float( 28 | input("Please enter the height of the rectangle in centimeters: ")) 29 | print("The area of the rectangle is: ", width * height, "centimeters") 30 | startAgain() 31 | else: 32 | print("Please enter a valid input.") 33 | 34 | 35 | def startAgain(): 36 | retryCalc = input("Would you like to calculate another rectangle? (y/n): ") 37 | if retryCalc == "y": 38 | welcome() 39 | elif retryCalc == "n": 40 | print("Thank you for using this program.") 41 | else: 42 | print("Please enter a valid input.") 43 | 44 | 45 | if __name__ == "__main__": 46 | welcome() 47 | -------------------------------------------------------------------------------- /Math Scripts/math-trapeze_area.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interesting resources: 3 | https://docs.python.org/3/library/functions.html#built-in-functions 4 | https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex 5 | https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals 6 | https://docs.python.org/3/tutorial/introduction.html#numbers 7 | https://docs.python.org/3/tutorial/modules.html#modules 8 | """ 9 | 10 | trapezeShortWidth = input( 11 | "Enter the width of the short side of the trapezoid: ") 12 | trapezeShortWidth = float(trapezeShortWidth) 13 | trapezeLongWidth = input("Enter the width of the long side of the trapezoid: ") 14 | trapezeLongWidth = float(trapezeLongWidth) 15 | trapezeheight = input("Enter the height of the trapezoid: ") 16 | trapezeheight = float(trapezeheight) 17 | 18 | trapezeArea = ((trapezeShortWidth + trapezeLongWidth) / 2) * trapezeheight 19 | print("The area of the trapezoid is: " + str(trapezeArea) + " m2") 20 | -------------------------------------------------------------------------------- /OLD-REPO.md: -------------------------------------------------------------------------------- 1 |

About the Old Repository

2 | 3 |

Almost all files available in this repository are actually from another private repository that I've made a couple years ago, but for security reasons some files have not been ported to this public repository, and that also explains why there is just a couple commits compared to the old repository (that actually have 175 commits).

4 | -------------------------------------------------------------------------------- /Problem Solving Scripts/CNPJ_Checker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ Nicolas Mendes - Jan 18 2022 4 | 5 | Based on https://programandoautomacao.blogspot.com/2020/10/python-uma-funcao-pythonica-para_15.html 6 | 7 | Algorithm for validating CNPJ 8 | For the CNPJ validation, the weights applied to its digits range from 2 to 11. For the CNPJ, the weights range from 2 to 9 and then we reset the weights (again at 2). And, just like for the CNPJ, the weights are applied from right to left. 9 | 10 | SAMPLE CNPJ: 46.798.277/0001-02 11 | """ 12 | 13 | import re 14 | import sys 15 | 16 | # WARNING: Disable in production! 17 | debugMode = False 18 | 19 | 20 | def logThis(message: str): 21 | """ 22 | This function is used to log messages if debug is enabled. 23 | """ 24 | if debugMode: 25 | print(f"{message}") 26 | 27 | 28 | def receitaFirstLast(): 29 | """ 30 | This function returns the sequence to discover the first of last two digits. 31 | """ 32 | return 543298765432 33 | 34 | 35 | def receitaSecondLast(): 36 | """ 37 | This function returns the sequence to discover the second of last two digits. 38 | """ 39 | return 6543298765432 40 | 41 | 42 | class CNPJ_Validator_N: 43 | """ 44 | This class is used to validate CNPJ numbers. 45 | """ 46 | 47 | def __init__(self, userCNPJ: str): 48 | """ 49 | This function is used to initialize the class. 50 | """ 51 | self.validateCNPJ(userCNPJ) 52 | 53 | validCNPJ = None 54 | partiallyValidation = None 55 | 56 | @staticmethod 57 | # Validates a CNPJ number with the easy way. 58 | def validateCNPJ(userCNPJ: str): 59 | """ 60 | This function is used to validate and clean the CNPJ number. 61 | """ 62 | # regular expression to remove any non-numeric characters, spaces, dots or dashes. 63 | userCNPJ = re.sub("[^0-9]", "", userCNPJ) 64 | logThis(userCNPJ) 65 | 66 | # Check length of CNPJ 67 | if len(userCNPJ) != 14: 68 | validCNPJ = False 69 | logThis("CNPJ is NOT valid.") 70 | return validCNPJ 71 | else: 72 | 73 | # Separate all numbers from userCNPJ into a list. 74 | userCNPJList = list(userCNPJ) 75 | # Sum every integer of the userCNPJList 76 | sumOfDigits = sum(int(i) for i in userCNPJList) 77 | sumOfDigits = str(sumOfDigits) 78 | 79 | # Get first 12 digits from userCNPJ 80 | firstTwelveDigits = userCNPJList[0:12] 81 | 82 | # Let's find the first last digit with this operation. 83 | # Multiply the last 12 numbers with "543298765432". 84 | 85 | # First digit from last section 86 | sumMaster = 0 87 | firstSequenceObj = str(receitaFirstLast()) 88 | firstSequence = [] 89 | firstSequence[:] = firstSequenceObj 90 | 91 | for cnpjNum, eachNum in zip(firstTwelveDigits, firstSequence): 92 | # logThis(f"{cnpjNum} * {eachNum}") 93 | sumMaster += int(cnpjNum) * int(eachNum) 94 | 95 | restSum = sumMaster % 11 96 | logThis(restSum) 97 | 98 | if restSum < 2: 99 | restSum = 0 100 | else: 101 | restSum = 11 - restSum 102 | 103 | # Now let's find the second last digit with this operation. 104 | # Multiply the last 13 numbers with "6543298765432". 105 | 106 | mergePartRes = str(userCNPJ[:12]) + str(restSum) 107 | mergeResList = [] 108 | mergeResList[:] = mergePartRes 109 | 110 | secondSequenceObj = str(receitaSecondLast()) 111 | secondSequence = [] 112 | secondSequence[:] = secondSequenceObj 113 | 114 | sumMasterBeta = 0 115 | for cnpjNum, eachNum in zip(mergeResList, secondSequence): 116 | # logThis(f"{cnpjNum} * {eachNum}") 117 | sumMasterBeta += int(cnpjNum) * int(eachNum) 118 | restSumBeta = sumMasterBeta % 11 119 | 120 | if restSumBeta < 2: 121 | restSumBeta = 0 122 | else: 123 | restSumBeta = 11 - restSumBeta 124 | 125 | mergePartRes = None 126 | mergePartRes = str(userCNPJ[:12]) + str(restSum) + str(restSumBeta) 127 | logThis(f"Merged result: {mergePartRes}") 128 | 129 | if mergePartRes == userCNPJ: 130 | logThis("CNPJ is valid.") 131 | validCNPJ = True 132 | return validCNPJ 133 | else: 134 | logThis("CNPJ is NOT valid.") 135 | validCNPJ = False 136 | return validCNPJ 137 | 138 | 139 | if __name__ == "__main__": 140 | """ 141 | This function is used to run the program. 142 | """ 143 | if debugMode: 144 | sampleCNPJ = "46.798.277/0001-02" 145 | CNPJ_Validator_N.validateCNPJ(sampleCNPJ) 146 | -------------------------------------------------------------------------------- /Problem Solving Scripts/CPF_Checker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ Nicolas Mendes - Jan 18 2022 4 | 5 | Based on https://www.alura.com.br/conteudo/python-validacao-dados#:~:text=Criando%20um%20novo%20Python%20file,contr%C3%A1rio%20o%20retorno%20ser%C3%A1%20False%20 6 | 7 | Algorithm for validating CPF 8 | The CPF calculation is based on the final 2 digits. 9 | To validate, take the first 9 digits of the CPF, generate the 2 digits and save in a new CPF. 10 | Compare if the CPF sent is the same as the CPF generated. 11 | If true, the CPF is valid, otherwise invalid. 12 | 13 | * Get first digit: 14 | --- Multiply the first 9 digits of the CPF by a count regress starting from 10 and ending at 2. 15 | --- Add all the multiplication values from step 1 16 | --- Get the remainder of the division between the sum and 11 from step 2 17 | --- Subtract the result from step 3 by 11 18 | --- If the result of step 4 is greater than nine, the digit is zero, otherwise the digit is the value from step 4 19 | 20 | * Get second digit: 21 | --- Multiply the first 9 digits of the CPF, PLUS THE FIRST DIGIT, previously obtained by a countdown starting from 11 and ending in 2 22 | --- Same logic as step 2 from the first digit onwards. 23 | 24 | SAMPLE CPF: 113.314.390-35 25 | 26 | TO GET FIRST DIGIT FORM LAST SECTION: 27 | 28 | 1*10 = 10 29 | 1*9 = 9 30 | 3*8 = 24 31 | 3*7 = 21 32 | 1*6 = 6 33 | 4*5 = 20 34 | 3*4 = 12 35 | 9*3 = 27 36 | 0*2 = 0 37 | 38 | TOTAL: 10 + 9 + 24 + 21 + 6 + 20 + 12 + 27 + 0 + 0 = 129 39 | GET THE REST FROM RESULT => 11 - (129 % 11) = 3 40 | 41 | IF RESULT > 9, DIGIT IS 0, ELSE DIGIT IS RESULT. 42 | 43 | TO GET SECOND DIGIT FORM LAST SECTION: 44 | 45 | 1*11 = 11 46 | 1*10 = 10 47 | 3*9 = 27 48 | 3*8 = 21 49 | 1*7 = 7 50 | 4*6 = 18 51 | 3*5 = 15 52 | 9*4 = 36 53 | 0*3 = 0 54 | 3*2 = 6 55 | 56 | TOTAL: 11 + 10 + 27 + 21 + 7 + 18 + 15 + 36 + 0 + 6 = 151 57 | GET THE REST FROM RESULT => 151%11 = 5 58 | 59 | BONUS: 60 | 61 | If the sum pair of all 11 digits are the same, the CPF is invalid. 62 | 63 | EXAMPLE: 64 | DIGITS SUM: 1 + 1 + 3 + 3 + 1 + 4 + 3 + 9 + 0 + 3 + 5 = 33 => Is valid. 65 | 66 | """ 67 | 68 | import re 69 | 70 | # WARNING: Disable in production! 71 | debugMode = False 72 | 73 | 74 | def logThis(message): 75 | """ 76 | This function is used to log messages if debug is enabled. 77 | """ 78 | if debugMode: 79 | print(message) 80 | 81 | 82 | class CPF_Validator_N: 83 | """ 84 | This class is used to validate CPF numbers. 85 | """ 86 | 87 | def __init__(self, cpf: str): 88 | """ 89 | This function is used to initialize the class. 90 | """ 91 | self.validateCPF(cpf) 92 | 93 | validCPF = None 94 | partiallyValidation = False 95 | 96 | @staticmethod 97 | # Validates a CPF number with the easy way. 98 | def validateCPF(userCPF: str): 99 | """ 100 | This function is used to validate and clean the CPF number. 101 | """ 102 | 103 | global partiallyValidation 104 | 105 | # regular expression to remove any non-numeric characters, spaces, dots or dashes. 106 | userCPF = re.sub("[^0-9]", "", userCPF) 107 | logThis(userCPF) 108 | 109 | # Check length of CPF 110 | if len(userCPF) != 11: 111 | validCPF = False 112 | logThis("CPF is NOT valid.") 113 | return False 114 | else: 115 | 116 | # Separate all numbers from userCPF into a list. 117 | userCPFList = list(userCPF) 118 | # Sum every integer of the userCPFList 119 | sumOfDigits = sum(int(i) for i in userCPFList) 120 | sumOfDigits = str(sumOfDigits) 121 | 122 | # Get first nine digits from userCPF 123 | firstNineDigits = userCPFList[0:9] 124 | 125 | # First digit from last section 126 | sumMaster = 0 127 | for key, multiply in enumerate(range(len(firstNineDigits) + 1, 1, -1)): 128 | # logThis(f"{userCPFList[key]} * {multiply}") 129 | sumMaster += int(userCPFList[key]) * multiply 130 | # logThis(sumMaster) 131 | restSum = 11 - (sumMaster % 11) 132 | 133 | # Second Last Digit 134 | sumMasterSec = 0 135 | for key, multiply in enumerate(range(len(firstNineDigits) + 2, 1, -1)): 136 | sumMasterSec += int(userCPFList[key]) * multiply 137 | restSumSec = 11 - (sumMasterSec % 11) 138 | 139 | if restSum > 9 or restSumSec > 9: 140 | restSum = 0 141 | restSumSec = 0 142 | 143 | mergeRes = str(userCPF[:9]) + str(restSum) + str(restSumSec) 144 | logThis(f"Merged result: {mergeRes}") 145 | 146 | if mergeRes == userCPF and sumOfDigits[0] == sumOfDigits[1]: 147 | return True 148 | else: 149 | logThis(f"CPF is NOT valid.") 150 | return False 151 | 152 | 153 | if __name__ == "__main__" and debugMode == True: 154 | """ 155 | This function is used to run the program. 156 | """ 157 | if debugMode: 158 | sampleCPF = "113.314.390-35" 159 | CPF_Validator_N.validateCPF(sampleCPF) 160 | -------------------------------------------------------------------------------- /Problem Solving Scripts/CPF_Generator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ Nicolas Mendes - Jan 26 2022 4 | 5 | Based on https://www.alura.com.br/conteudo/python-validacao-dados#:~:text=Criando%20um%20novo%20Python%20file,contr%C3%A1rio%20o%20retorno%20ser%C3%A1%20False%20, https://gist.github.com/lucascnr/24c70409908a31ad253f97f9dd4c6b7c 6 | 7 | The CPF calculation is based on the final 2 digits. 8 | To validate, take the first 9 digits of the CPF, generate the 2 digits and save in a new CPF. 9 | Compare if the CPF sent is the same as the CPF generated. 10 | If true, the CPF is valid, otherwise invalid. 11 | 12 | SAMPLE CPF: 113.314.390-35 13 | """ 14 | 15 | import random 16 | from CPF_Checker import CPF_Validator_N as isThisValid 17 | 18 | # WARNING: Disable in production! 19 | debugMode = False 20 | 21 | 22 | def logThis(message): 23 | """ 24 | This function is used to log messages if debug is enabled. 25 | """ 26 | if debugMode: 27 | print(message) 28 | 29 | 30 | class CPF_GEN: 31 | """ 32 | This class is used to generate CPF numbers. 33 | """ 34 | 35 | logThis("Generating CPF...") 36 | 37 | def __init__(self): 38 | """ 39 | This function is used to initialize the class. 40 | """ 41 | self.checkCPF() 42 | 43 | @staticmethod 44 | def generateCPF(): 45 | """ 46 | This function is used to generate the CPF. 47 | """ 48 | 49 | nineDigits = None 50 | while True: 51 | nineDigits = [random.randint(0, 9) for i in range(9)] 52 | if nineDigits != nineDigits[::-1]: 53 | break 54 | 55 | for i in range(9, 11): 56 | value = sum((nineDigits[num] * ((i + 1) - num) for num in range(0, i))) 57 | digit = ((value * 10) % 11) % 10 58 | nineDigits.append(digit) 59 | 60 | # Start with random sequence between 0 and 9 61 | result = "".join(map(str, nineDigits)) 62 | logThis(f"Generated CPF: {result}") 63 | formatGenCPF = f"{result[0:3]}.{result[3:6]}.{result[6:9]}-{result[9:11]}" 64 | return formatGenCPF 65 | 66 | def checkCPF(): 67 | 68 | while ( 69 | isThisValid.validateCPF(CPF_GEN.generateCPF()) != True 70 | and isThisValid.validateCPF(CPF_GEN.generateCPF()) is not None 71 | ): 72 | CPF_GEN.checkCPF() 73 | logThis( 74 | f"CPF is invalid, generating another one..." 75 | ) 76 | else: 77 | logThis(f"CPF is valid! {CPF_GEN.generateCPF()}") 78 | return CPF_GEN.generateCPF() 79 | 80 | 81 | if __name__ == "__main__": 82 | """ 83 | This function is used to run the program. 84 | """ 85 | # CPF_GEN.checkCPF() 86 | print(CPF_GEN.checkCPF()) 87 | -------------------------------------------------------------------------------- /Problem Solving Scripts/__pycache__/CPF_Checker.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/Problem Solving Scripts/__pycache__/CPF_Checker.cpython-39.pyc -------------------------------------------------------------------------------- /Problem Solving Scripts/basic_investment_calc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interesting resources: 3 | https://docs.python.org/3/library/functions.html#built-in-functions 4 | https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex 5 | https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals 6 | https://docs.python.org/3/tutorial/introduction.html#numbers 7 | https://docs.python.org/3/tutorial/modules.html#modules 8 | """ 9 | 10 | whatCurrency = input("What currency are you using? (USD/BRL) ") 11 | incomePercentage = input("What is the income percentage per year? ") 12 | investUntil = input("See the projection until: (ex: 5) ") 13 | howMuch = input("How much do you want to invest? ") 14 | print(" ") 15 | 16 | 17 | # Calculate the income 18 | FinalIncome = float(howMuch) * (float(incomePercentage) / 100) 19 | totalIncome = float(FinalIncome) + float(howMuch) 20 | print("Your final income in " + str(investUntil) + 21 | " years is " + str(totalIncome * int(investUntil)) + " " + whatCurrency) 22 | print(" ") 23 | 24 | # Print the income each year in investUntil 25 | for eachYearIncome in range(1, int(investUntil) + 1): 26 | print("In " + str(eachYearIncome) + " year(s) you will have " + 27 | str(totalIncome * eachYearIncome) + " " + whatCurrency) 28 | -------------------------------------------------------------------------------- /Problem Solving Scripts/bonus_and_salary.py: -------------------------------------------------------------------------------- 1 | """ 2 | The employees of a company will receive a 5% salary increase and a bonus at the end of the year equivalent to 20% of the new salary. 3 | """ 4 | 5 | bonusQuantity = 5 6 | endOfYearPercentage = 20 7 | 8 | employeeSalary = float(input("Enter the employee's salary: ")) 9 | # Calculate the percentage employeeSalary with bonusQuantity 10 | bonus = employeeSalary * bonusQuantity / 100 11 | # Calculate the percentage employeeSalary with endOfYearPercentage 12 | endOfYear = employeeSalary * endOfYearPercentage / 100 13 | # Calculate the new salary 14 | newSalary = employeeSalary + bonus + endOfYear 15 | print("With the bonus it will be: ", bonus + employeeSalary) 16 | print("With the end of year it will be: ", endOfYear + employeeSalary) 17 | print("Final salary is: ", newSalary) 18 | -------------------------------------------------------------------------------- /Problem Solving Scripts/medicine_box.py: -------------------------------------------------------------------------------- 1 | """ 2 | I need to take 1.6ml of a medicine every day. A box of this medicine comes with a bottle of 20ml. 3 | """ 4 | quantityTaken = 1.6 5 | boxBottleQuantity = 20 6 | 7 | monthsToTake = input("How many months do you need to take this medicine? ") 8 | monthsToTake = int(monthsToTake) 9 | 10 | print("Ok, you will take:", quantityTaken * 30, " ml each month.") 11 | print("So... You will have to take: ", (quantityTaken * 30) 12 | * monthsToTake, " ml of medicine in total.") 13 | print("That means you will need to buy: ", 14 | int(((quantityTaken * 30) * monthsToTake) / boxBottleQuantity), " boxes of medicine.") 15 | -------------------------------------------------------------------------------- /Problem Solving Scripts/movie-food-decider/food.json: -------------------------------------------------------------------------------- 1 | { 2 | "foods": [ 3 | "Apple", 4 | "Banana", 5 | "Orange" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Problem Solving Scripts/movie-food-decider/movie-food.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import json 4 | import sys 5 | import os 6 | import random 7 | 8 | foodDict = {} 9 | movieDict = {} 10 | 11 | currentDir = os.path.dirname(sys.argv[0]) 12 | 13 | 14 | def randomFood(): 15 | with open(f"{currentDir}/food.json", "r") as json_food: 16 | foodStored = json.load(json_food) 17 | foodDict = foodStored 18 | foodList = foodDict["foods"] 19 | randomFood = random.choice(foodList) 20 | return randomFood 21 | 22 | 23 | def randomMovie(): 24 | with open(f"{currentDir}/movies.json", "r") as json_movies: 25 | moviesStored = json.load(json_movies) 26 | movieDict = moviesStored 27 | movieList = movieDict["movies"] 28 | randomMovie = random.choice(movieList) 29 | return randomMovie 30 | 31 | 32 | class main(): 33 | userChoice = input("Would you like to eat or watch a movie? ") 34 | 35 | if userChoice == "eat" or userChoice == "food": 36 | print(randomFood()) 37 | elif userChoice == "watch" or userChoice == "movie": 38 | print(randomMovie()) 39 | else: 40 | print("Please enter eat or watch") 41 | -------------------------------------------------------------------------------- /Problem Solving Scripts/movie-food-decider/movies.json: -------------------------------------------------------------------------------- 1 | { 2 | "movies": [ 3 | "Dune", 4 | "Star Trek", 5 | "Star Wars" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Problem Solving Scripts/price_quantity_calc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Idea: 3 | A fair sells hot dog and refrigerant. 4 | Each hot dog is sold by 8 USD. 5 | Each refrigerant is sold by 5 USD. 6 | """ 7 | 8 | howManyHD = input("How many hot dogs do you want to buy? ") 9 | howManyRef = input("How many refrigerants do you want to buy? ") 10 | 11 | #Values in USD 12 | hotDogPrice = 8.0 13 | refPrice = 5.0 14 | 15 | finalHDInt = int(howManyHD) 16 | finalRefInt = int(howManyRef) 17 | 18 | print("You have to pay: $", (finalHDInt * hotDogPrice) + (finalRefInt * refPrice)) 19 | print("Thank you.") 20 | -------------------------------------------------------------------------------- /Problem Solving Scripts/q-min_jumps_array.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | we have an array {1,4,3,7,1,2,6,7,6,10} we need to reach at the end of the array 4 | and we have to do this using minimum number of jumps. 5 | 6 | So let each element in the array represent the number of steps we can move forward. 7 | So 1 means one step forward, 4 means 4 steps forward. 8 | Now starting at 1 we reach 4. So that is one jump. Now we are at 4 so we will 9 | move 4 steps forward, as we are moving 4 steps forward we compare each element with 4. 10 | Since 3<4 we will ignore it. Now 7>4, so we will store it as we will use this later. 11 | Now from 4 we hv reached 2. So that is 2 jumps. 12 | 13 | Now since 4 steps are over, we will use the 7 that we had stored and move 7- 3 14 | (the position of 7 in the array) steps. So we will reach the end of the array in 15 | total 3 jumps. 16 | """ 17 | 18 | 19 | def jumps(self): 20 | jumps = [0] * len(self.arr) 21 | jumps[0] = 1 22 | for i in range(1, len(self.arr)): 23 | for j in range(i): 24 | if self.arr[j] + j >= i: 25 | jumps[i] = max(jumps[i], jumps[j] + 1) 26 | return jumps[-1] 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Python Fundamentals Study 📚

2 | 3 |

This repository is dedicated for my fundamental knowledge related to Python 3 and newer. I intend to work on this repository weekly.

4 | 5 |

6 | License 7 |

8 | 9 | Sample password generator script study. 10 | 11 |

In this repository I study the practical application of:

12 |
    13 |
  • Python built-in functions
  • 14 |
  • Types of numeric data (such as int and float)
  • 15 |
  • Strings Formatting
  • 16 |
  • Variables
  • 17 |
  • Mathematical operations with Python
  • 18 |
  • Libraries
  • 19 |
  • Decision making (if, elif, else)
  • 20 |
  • Repetitions (while, for)
  • 21 |
  • User-defined functions (def())
  • 22 |
  • My knowledge of English and general Python use.
  • 23 |
  • Advanced use cases
  • 24 |
25 | 26 | ## 🗺 Directory Map 27 | 28 |
    29 |
  1. Advanced Applications
  2. 30 |
  3. Conversion Scripts
  4. 31 |
  5. Math Scripts
  6. 32 |
  7. Problem Solving Scripts
  8. 33 |
  9. String Based Scripts
  10. 34 |
  11. 100 Days Coding Challenge
  12. 35 |
36 | 37 |

1. Advanced Applications

38 |

Advanced scripts related to daily and possible market problems solving, high use of all practical applications on each script.

39 | 40 |

2. Conversion Scripts

41 |

Scripts with focus on conversion operations, using part of practical application topics

42 | 43 |

3. Math Scripts

44 |

Mathematical operations scripts to calculate and/or give mathematical results.

45 | 46 |

4. Problem Solving Scripts

47 |

These scripts are daily general problem solving scripts, like an investment calculator, a salary bonus calculation, price per quantity, etc.

48 | 49 |

5. String Based Scripts

50 |

Simple and direct strings scripts with minimal interaction with the user.

51 | 52 |

6. 100 Days Coding Challenge

53 |

An initiative by Dr. Angela Yu to learn Python by building 100 projects in 100 days. Learning to build websites, games, apps, plus scraping and data science.

54 | 55 | ## 🦾 100 Days Coding Challenge Pieces 56 | 57 | #### **Day 1** - Band Name Generator 58 | #### **Day 2** - Tip Calculator 59 | #### **Day 3** - Interactive Story 60 | #### **Day 4** - Rock, Paper, Scissors game 61 | #### **Day 5** - Password Generator 62 | #### **Day 6** - Reeborg Maze Solution 63 | #### **Day 7** - Hangman Game 64 | #### **Day 8** - Caesar Cipher 65 | #### **Day 9** - Silent/Secret Auction 66 | #### **Day 10** - Calculator App 67 | #### **Day 11** - Blackjack Capstone Project 68 | #### **Day 12** - Guessing Game 69 | #### **Day 13** - Debugger 70 | #### **Day 14** - Higher or Lower game 71 | #### **Day 15** - Coffee machine project 72 | #### **Day 16** - Object Oriented Programming with Coffee Machine 73 | #### **Day 17** - Object Oriented Programming with Quiz App 74 | #### **Day 18** - Turtle and GUI 75 | #### **Day 19** - Etch a Sketch with Turtle GUI 76 | #### **Day 20** - Snake Game 77 | #### **Day 21** - Advanced Snake Game 78 | #### **Day 22** - Pong Game 79 | #### **Day 23** - Turtle crossing road Game 80 | #### **Day 24** - Improved Snake Game 81 | #### **Day 25** - Work with CSV files with Pandas 82 | #### **Day 26** - List and Dictionary comprehensions with NATO phonetic alphabet 83 | #### **Day 27** - Tkinter GUI 84 | #### **Day 28** - Advanced Tkinter GUI - Pomodoro App 85 | #### **Day 29** - Tkinter GUI Password Manager 86 | #### **Day 30** - Password Manager JSON implementation 87 | #### **Day 31** - Flash card program - Frequency language dictionary 88 | #### **Day 32** - Send Emails and date/time management 89 | #### **Day 33** - API endpoints - ISS tracker 90 | #### **Day 34** - Trivia API to work with Quiz app 91 | #### **Day 35** - Authentication, SMS sender 92 | #### **Day 36** - Stock Trading News 93 | #### **Day 37** - Habit tracking app 94 | #### **Day 38** - Exercise tracking app 95 | #### **Day 39** - Cheap flight finder 96 | #### **Day 40** - Flight Club app 97 | #### **Day 41** - Basic Web Development with Python 98 | #### **Day 42** - Intermediate Web Development with Python 99 | #### **Day 43** & **Day 44** - Website Development 100 | #### **Day 45** - Web scraping with BeautifulSoup 101 | #### **Day 46** - Musical Time Machine 102 | #### **Day 47** - Automated Amazon price tracker 103 | #### **Day 48** - Game Playing Bot 104 | #### **Day 49** - LinkedIn Job Application Automation 105 | #### **Day 50** - Auto Tinder Swiping Bot 106 | #### **Day 51** - Twitter compliant bot 107 | #### **Day 52** - Instagram follower bot 108 | #### **Day 53** - Web scraping - Data entry job automation 109 | #### **Day 54** - Web Development with Flask 110 | #### **Day 55** - Parsing web elements with Flask 111 | #### **Day 56** - Website Templates 112 | #### **Day 57** - Jinja with Flask 113 | #### **Day 58** - Bootstrap 114 | #### **Day 59** - Blog Capstone 115 | #### **Day 60** - Web forms and POST with Flask 116 | #### **Day 61** - Advanced forms with Flask WT-Forms 117 | #### **Day 62** - Wifi Project 118 | #### **Day 63** - Database with SQLite 119 | #### **Day 64** - Top 10 Movies 120 | #### **Day 65** - Web Design and Development project study 121 | #### **Day 66** - RESTful API 122 | #### **Day 67** - Advanced RESTful API 123 | #### **Day 68** - Authentication with Flask 124 | #### **Day 69** - Adding users in a database 125 | #### **Day 70** - Deploy web app with Heroku 126 | #### **Day 71** - Data exploration with Pandas 127 | #### **Day 72** - Data visualization with Matplotlib 128 | #### **Day 73** - Analysis of LEGO database 129 | #### **Day 74** - Google Trends Data 130 | #### **Day 75** - Plotly Charts 131 | #### **Day 76** - Computation with NumPy 132 | #### **Day 77** - Linear Regression 133 | #### **Day 78** - Nobel Prize Analysis 134 | #### **Day 79** - Handwashing 135 | #### **Day 80** - Predict Houses Prices 136 | #### **Day 81** - Convert Strings into Morse Code 137 | #### **Day 82** - Portfolio Project Development 138 | #### **Day 83** - Professional Portfolio Project 139 | #### **Day 84** - Watermark adder (GUI) 140 | #### **Day 85** - Typing speed tester (GUI) 141 | #### **Day 86** - Game development with Godot 142 | #### **Day 87** - Cafe and Wifi Website 143 | #### **Day 88** - Web Todo List 144 | #### **Day 89** - Text Writing App 145 | #### **Day 90** - PDF to Audiobook Converter 146 | #### **Day 91** - Image Colour Palette Generator 147 | #### **Day 92** - Custom Web Scraper 148 | #### **Day 93** - Google Dinosaur Game bot 149 | #### **Day 94** - Space Invaders with Godot 150 | #### **Day 95** - Landing Page 151 | #### **Day 96** - Ecommerce website page 152 | #### **Day 97** - Custom Automation 153 | #### **Day 98** - Generate random profile pictures 154 | #### **Day 99** - Youtube channel tracker 155 | #### **Day 100** - Predict Earnings using Multivariable Regressio 156 | 157 | 158 | 159 | ## 💡 Useful Snippets and study pieces 160 | 161 |

Here are some useful snippets to use daily for boosting code efficiency. Every single snippet is coming from a study script that I made from this repository.

162 | 163 |

Dynamic File Path

164 |

Useful for loading external assets in specific directories and subdirectories, this snippet will work on every major OS like Windows, MacOS, Linux and BSD.

165 | 166 | ```python 167 | import pathlib 168 | from pathlib import Path 169 | 170 | # Dynamic File Path Solution 171 | OUTPUT_PATH = pathlib.Path(__file__).parent.absolute() 172 | ASSETS_PATH = OUTPUT_PATH / Path("./assets") 173 | 174 | 175 | def relative_to_assets(path: str) -> Path: 176 | return ASSETS_PATH / Path(path) 177 | ``` 178 | 179 | OR 180 | 181 | ```python 182 | import pathlib 183 | import shutil 184 | from pathlib import Path 185 | 186 | # Dynamic File Path Solution 187 | THIS_PATH = pathlib.Path(__file__).parent.absolute() 188 | ASSETS_PATH = THIS_PATH / Path("aarch64") 189 | 190 | 191 | def relative_to_assets(path: str) -> Path: 192 | return ASSETS_PATH / Path(path) 193 | 194 | 195 | def relative_to_target(path: str) -> Path: 196 | return THIS_PATH / Path(path) 197 | 198 | 199 | def copy_and_overwrite(from_path, to_path): 200 | if os.path.exists(to_path): 201 | shutil.rmtree(to_path) 202 | shutil.copytree(from_path, to_path) 203 | ``` 204 | 205 |

While

206 |

While can be used to start a script on the core part of it or to use as a logic operator.

207 | 208 | ```python 209 | while True: 210 | answer = input("Do you want to try again? (Y/n) ") 211 | if answer == 'y' or answer == 'Y' or sys.stdin.isatty(): 212 | num = int(input("Enter a number: ")) 213 | print(num2roman(num)) 214 | elif answer == 'n': 215 | break 216 | else: 217 | print("Invalid input.") 218 | ``` 219 | 220 |

For loops

221 |

For loops are essential these days, there is no doubt about that. It's possible to make a huge range of logical solutions with lists, arrays and other variables.

222 | 223 | ```python 224 | for link in linksFinder: 225 | print(link.get("href")) 226 | 227 | saveFile = input( 228 | "Do you want to save this list inside a text file? (y/n) ") 229 | if saveFile == "y": 230 | with open("links.txt", "a") as file: 231 | file.write(link.get("href") + "\n") 232 | else: 233 | pass 234 | ``` 235 | 236 | 237 |

Random List

238 |

Randomization is a must need thing in our code, so this is a quick snippet to random lists.

239 | 240 | ```python 241 | import random 242 | 243 | sample = ['a', 'b', 'c', 'd', 'e'] 244 | print(random.choice(sample)) 245 | 246 | # For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice(): 247 | 248 | import secrets 249 | 250 | sample = ['battery', 'correct', 'horse', 'staple'] 251 | print(secrets.choice(sample)) 252 | 253 | ``` 254 | 255 |

Random Dictionary

256 |

Randomization is a must need thing in our code, so this is a quick snippet to randomize dictionaries.

257 | 258 | ```python 259 | import random 260 | 261 | visualSet = {"Rock": rock, "Paper": paper, "Scissors": scissors} 262 | aiChoice = random.choice(list(visualSet.values())) 263 | 264 | """All possible ways to randomize: 265 | 266 | 'd' is the dictionary variable. 267 | 268 | A random key: 269 | random.choice(list(d.keys())) 270 | 271 | A random value: 272 | random.choice(list(d.values())) 273 | 274 | A random key and value: 275 | random.choice(list(d.items())) 276 | """ 277 | 278 | ``` 279 |

Unix Administrative Request

280 |

If the script needs root user privileges then we need to use this snippet to call sudo.

281 | 282 | ```python 283 | import subprocess 284 | 285 | rootNeeded = subprocess.call(["/usr/bin/sudo", "/usr/bin/id"]) 286 | ``` 287 | 288 |

Bytes Encode and Decode

289 |

Bytes converts an object to an immutable byte-represented object of given size and data, which is useful for writing or reading HEX values inside a file.

290 | 291 | ```python 292 | # Bytes Encode and Decode Study 293 | 294 | def writeString(): 295 | # Write a string at the end of a JPG file. 296 | with open(relative_to_assets('photo.jpg'), 'ab') as f: # ab append bytes mode 297 | f.write(b' Hidden message: test :)') # b is for bytes 298 | 299 | def readString(): 300 | # Read HEX of the JPG file. 301 | with open(relative_to_assets('photo.jpg'), 'rb') as f: # Read bytes mode 302 | jpgContent = f.read() 303 | # when FF D9 occurs. 304 | offset = jpgContent.index(bytes.fromhex('FFD9')) 305 | f.seek(offset + 2) 306 | print(f.read()) 307 | 308 | def deleteString(): 309 | # delete everything after the last FF D9 from a JPG file 310 | with open(relative_to_assets('photo.jpg'), 'r+') as f: # Read bytes mode 311 | jpgContent = f.read() 312 | offset = jpgContent.index(bytes.fromhex('FFD9')) 313 | f.seek(offset + 2) 314 | f.truncate() 315 | ``` 316 | 317 |

Endswith

318 |

This function returns True if a string ends with the specified suffix (case-sensitive), otherwise returns False. A tuple of string elements can also be passed to check for multiple options. For startswith we have a similar approach.

319 | 320 | ```python 321 | from pathlib import Path 322 | import pathlib 323 | files = os.listdir(ASSETS_PATH) 324 | 325 | # Interesting solution to pick specific files inside a list. 326 | for file in files: 327 | if file.endswith(".png") or file.endswith(".jpg") or file.endswith(".jpeg"): 328 | print(f"Optimizing {file}") 329 | imgOptimize = Image.open(relative_to_assets(str(file))) 330 | imgWidth, imgHeight = imgOptimize.size 331 | else: 332 | print(f"{file} is not a PNG or JPG, skipping") 333 | ``` 334 | 335 |

Regular Expression

336 |

Regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.

337 | 338 | ```python 339 | import re 340 | 341 | # Regular Expression from module re; 342 | # https://docs.python.org/3/library/re.html 343 | # validate def will make sure that the remTwo var can have a "." as float 344 | 345 | 346 | def validate(string): 347 | result = re.match(r"(\+|\-)?\d+(\.\d+)?$", string) 348 | return result is not None 349 | ``` 350 | 351 |

Using Shell Paths

352 |

Usually when we need to call a shell script within a python script, paths tends to break and not be cross compatible between python and shell lines. So this snippet helps to solve that.

353 | 354 | ```python 355 | import os 356 | import sys 357 | 358 | # Python path. This will pick the current directory where the script is located. 359 | current_dir = os.path.dirname(sys.argv[0]) 360 | # OR 361 | current_shell_dir = os.path.dirname(os.path.abspath(__file__)) 362 | 363 | # Shell path. This will pick "current_dir" and replace any possible empty spaces with "\" and other fixes to be compatible with any unix-like Shell. 364 | 365 | fixDirPath = current_dir.replace(" ", "\\ ").replace("?", "\\?").replace("&", "\\&").replace( 366 | "(", "\\(").replace(")", "\\)").replace("*", "\\*").replace("<", "\\<").replace(">", "\\>") 367 | 368 | 369 | targetDirectory = "Sample" 370 | 371 | # Sample script usage to delete a directory using shell commands 372 | os.system(f"rm -rf {str(fixDirPath)}/{str(targetDirectory)}") 373 | ``` 374 | 375 |

Input

376 |

Input is a built-in function in Python, allows coders to receive information through the keyboard, which they can process in a Python program. This is basic and essential.

377 | 378 | ```python 379 | # Simple like that :) 380 | userString = input("Enter a text: ") 381 | print(userString[::-1]) # Reverse the string 382 | ``` 383 | 384 |

Time Conversion

385 |

Making mathematical operations inside python are easy things to do, you basically need to know the formula and the logic to implement conversion and precision operations.

386 | 387 | ```python 388 | minutes = "24.785089" 389 | print(minutes + " minutes is equal to " + 390 | str(float(minutes)/60/24/365) + " years.") 391 | ``` 392 | 393 |

Ordinal Numbers to Roman Numbers

394 |

With a simple array, it's possible to compare ordinal numbers with strings that represents roman numbers.

395 | 396 | ```python 397 | num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), 398 | (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] 399 | 400 | # Function to convert the numbers to roman values. Based on NullDev algorithm. 401 | 402 | 403 | def num2roman(num): 404 | 405 | roman = '' 406 | 407 | while num > 0: 408 | for i, r in num_map: 409 | while num >= i: 410 | roman += r 411 | num -= i 412 | 413 | return roman 414 | ``` 415 | 416 |

Temperature Conversion

417 |

Converting temperature units is a simple task, all that is needed is the formula of each unit.

418 | 419 | ```python 420 | # Simple formulas to convert temperature from Celsius to Fahrenheit and vice versa. 421 | fahrenheit = celsius * 9 / 5 + 32 422 | celsius = (fahrenheit - 32) * 5 / 9 423 | ``` 424 | 425 |

Copy to Clipboard

426 |

When copying content to the user's clipboard, it's needed to import the OS module to use features like that.

427 | 428 | ```python 429 | import os 430 | nameGen = "Hello there :)" 431 | # Copy to the variable "nameGen" to the clipboard 432 | os.system(f"echo {nameGen} | pbcopy") 433 | ``` 434 | 435 |

Open Website or Application

436 |

Opening external websites or applications also requires the OS module to be imported, this snippet allows the script to open almost every type of file, like Shell scripts, default applications and websites.

437 | 438 | ```python 439 | import os 440 | targetSite = "https://google.com/" 441 | os.system(f"open {targetSite}") 442 | ``` 443 | 444 | 445 |

Watchdog Usage

446 |

Watchdog is used to monitor events on the OS, that means that it's possible to monitor files and folders. To be more specific: Python API library and shell utilities to monitor file system events.

447 | 448 | ```python 449 | from watchdog.observers import Observer 450 | from watchdog.events import FileSystemEventHandler 451 | 452 | currentUser = "default" 453 | mainDirectory = f"/Users/{currentUser}/Downloads" 454 | jobDestinationPath = f"/Users/{currentUser}/Documents/Remotish" 455 | 456 | class MyHandler(FileSystemEventHandler): # We need to create a class with the FileSystemEventHandler 457 | 458 | # After that we need to make a function with self and event. So when anything happens to the folder it will execute the function. 459 | def on_modified(self, event): 460 | for individualFile in os.listdir(mainDirectory): 461 | os.rename(f"{mainDirectory}/{individualFile}", f"{jobDestinationPath}/{individualFile}") 462 | 463 | # Needed to monitor Watchdog 464 | eventHandler = MyHandler() 465 | observer = Observer() 466 | observer.schedule(eventHandler, mainDirectory, recursive=True) 467 | observer.start() 468 | 469 | # Needed to monitor Watchdog 470 | try: 471 | while True: 472 | time.sleep(10) 473 | except KeyboardInterrupt: 474 | observer.stop() 475 | observer.join() 476 | ``` 477 | 478 | 479 |

Simple JSON read method

480 |

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. These days, JSON is mandatory. This little snippet can read a json file and output its content.

481 | 482 | ```json 483 | { 484 | "_comment": "SAMPLE JSON FILE", 485 | "username": "testABC", 486 | "password": "testDEF" 487 | } 488 | ``` 489 | 490 | ```python 491 | import json 492 | import sys 493 | import os 494 | 495 | userContent = {} 496 | current_dir = os.path.dirname(sys.argv[0]) 497 | 498 | with open(f"{current_dir}/sample-json.json", "r") as json_file: 499 | userContent = json.load(json_file) 500 | print(userContent["username"]) 501 | print(userContent["password"]) 502 | ``` 503 | 504 |

Simple JSON write method

505 |

This little snippet can write a json file and output its content.

506 | 507 | ```json 508 | { 509 | "_comment": "SAMPLE JSON FILE", 510 | "username": "testABC", 511 | "password": "testDEF" 512 | } 513 | ``` 514 | 515 | ```python 516 | import json 517 | import sys 518 | import os 519 | 520 | userContent = {} 521 | current_dir = os.path.dirname(sys.argv[0]) 522 | 523 | userInp = input("Enter your username: ") 524 | userInp2 = input("Enter your password: ") 525 | 526 | userContent["username"] = f"{str(userInp)}" 527 | userContent["password"] = f"{str(userInp2)}" 528 | 529 | 530 | with open(f"{current_dir}/sample-json.json", "w") as json_file: 531 | json.dump(userContent, json_file) 532 | print(f"The new username is: {str(userContent['username'])}") 533 | print(f"The new password is: {str(userContent['password'])}") 534 | ``` 535 | 536 | 537 |

Simple API Read Methods

538 |

Here are some ways to read the API path content with a simple GET method and some extra calls.

539 | 540 | ```python 541 | import requests 542 | import json 543 | 544 | responseAPI = requests.get('https://randomfox.ca/floof') 545 | 546 | # This will return a simple status code. 547 | print(responseAPI.status_code) 548 | # This will return a string value with the contents inside the API URL. 549 | print(responseAPI.text) 550 | # Now printing json format and using as a dictionary. 551 | print(responseAPI.json()) 552 | ``` 553 | 554 | 555 |

Simple API GET Method

556 |

Reading values from an API can be done very easily by using the requests module and also to converting the API values into Python dictionaries using json module and function.

557 | 558 | ```python 559 | import requests 560 | import json 561 | 562 | # Getting the API url/path 563 | responseAPI = requests.get('https://randomfox.ca/floof') 564 | # Output from GET: {'image': 'https://randomfox.ca/images/13.jpg', 'link': 'https://randomfox.ca/?i=13'} 565 | generatedFoxImg = responseAPI.json() 566 | 567 | print(f"Your random fox: {generatedFoxImg['image']} \n") 568 | ``` 569 | 570 | 571 |

FastAPI GET Method

572 |

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. Making GET requests are easy thing to do, just need to import the module and associate the function to a variable and start coding paths and parameters with the FastAPI Functions.

573 | 574 | ```python 575 | from fastapi import FastAPI 576 | 577 | appStudy = FastAPI() 578 | 579 | 580 | @appStudy.get("/") 581 | async def root(): 582 | return {"messageField": "Message content here."} 583 | ``` 584 | 585 |

FastAPI POST Method

586 |

The POST method is used to request that the origin server accept the entity attached in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

587 | 588 | ```python 589 | from fastapi import FastAPI, Path 590 | from pydantic import BaseModel 591 | 592 | appStudy = FastAPI() 593 | 594 | class Item(BaseModel): 595 | name: str 596 | price: float 597 | quantity: Optional[int] = None 598 | 599 | # This is actually the API values 600 | inventoryDict = { 601 | "1": {"name": "Bread", "price": 1.25, "quantity": "10"}, 602 | "2": {"name": "Milk", "price": 2.45, "quantity": "5"}, 603 | "3": {"name": "Eggs", "price": 3.99, "quantity": "20"}, 604 | "4": {"name": "Cheese", "price": 4.99, "quantity": "15"}, 605 | "5": {"name": "Butter", "price": 5.00, "quantity": "5"} 606 | } 607 | 608 | # Using POST method 609 | @appStudy.post("/post-item/{item_id}") 610 | def createItem(item_id: int, item: Item): 611 | # Let's create a new item id. 612 | if item_id in inventoryDict: 613 | return {"DataErr": "Item already exists"} 614 | else: 615 | inventoryDict[str(item_id)] = item 616 | return inventoryDict[str(item_id)] 617 | ``` 618 | 619 | 620 |

FastAPI PUT Method

621 |

PUT method requests for the attached entity (in the request body) to be stored into the server which hosts the supplied Request-URI. If the Request-URI refers to an already existing resource – an update operation will happen

622 | 623 | ```python 624 | from fastapi import FastAPI, Path 625 | from pydantic import BaseModel 626 | from fastapi.encoders import jsonable_encoder 627 | from typing import Optional 628 | 629 | appStudy = FastAPI() 630 | 631 | # This class is for the PUT request 632 | class updateItem(BaseModel): 633 | name: Optional[str] = None 634 | price: Optional[float] = None 635 | quantity: Optional[int] = None 636 | 637 | # This is actually the API values 638 | inventoryDict = { 639 | "1": {"name": "Bread", "price": 1.25, "quantity": "10"}, 640 | "2": {"name": "Milk", "price": 2.45, "quantity": "5"}, 641 | "3": {"name": "Eggs", "price": 3.99, "quantity": "20"}, 642 | "4": {"name": "Cheese", "price": 4.99, "quantity": "15"}, 643 | "5": {"name": "Butter", "price": 5.00, "quantity": "5"} 644 | } 645 | 646 | # PUT method 647 | @appStudy.put("/put-item/{item_id}") 648 | def createItem(item_id: int, item: Item): 649 | # Let's create a new item id. 650 | if item_id in inventoryDict: 651 | return {"DataErr": "Item already exists"} 652 | else: 653 | inventoryDict[str(item_id)] = item 654 | return inventoryDict[str(item_id)] 655 | ``` 656 | 657 | 658 |

Key Obfuscation

659 |

Obfuscation is the deliberate act of creating source or machine code that is difficult for humans to understand, this helps to improve security - it is far from being the ultimate security solution but is a thing to use in a non-production environment.

660 | 661 | For creating a file with the key and obfuscating it: 662 | 663 | ```python 664 | import base64 665 | import pathlib 666 | import os 667 | import re 668 | from pathlib import Path 669 | 670 | # Dynamic File Path Solution 671 | API_PATH = pathlib.Path(__file__).parent.absolute() 672 | 673 | 674 | def relative_to_assets(path: str) -> Path: 675 | return API_PATH / Path(path) 676 | 677 | userChange = input("Enter key: ").strip() 678 | 679 | # Pick userChange and encode it to base64 680 | userChange = base64.b64encode(userChange.encode('utf-8')) 681 | # Save userChange to "API" file 682 | with open(relative_to_assets('Data/security/API'), 'wb') as f: 683 | # Delete everything inside the file. 684 | f.truncate() 685 | f.write(userChange) 686 | 687 | print("DONE! You are ready to use the API!") 688 | 689 | ``` 690 | 691 |

XOR Cipher

692 |

XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method, i.e generating random encryption keys to match with the correct one.

693 | 694 | Encrypting: 695 | 696 | ```python 697 | #! /usr/bin/env python3 698 | import base64 699 | import os 700 | import pathlib 701 | import re 702 | from pathlib import Path 703 | 704 | # Dynamic File Path Solution 705 | KEY_PATH = pathlib.Path(__file__).parent.absolute() 706 | 707 | 708 | def relative_to_assets(path: str) -> Path: 709 | return KEY_PATH / Path(path) 710 | 711 | 712 | def encryptSecurity(): 713 | # Use external script to make base64 or https://www.base64encode.org/ 714 | key = "MTMy" # up 255 715 | key = base64.b64decode(key) 716 | cleanKey = re.sub( 717 | r"[^A-Za-z0-9-]", "", key.decode("utf-8")) 718 | finalKey = int(cleanKey) 719 | 720 | loadEnc00 = open(relative_to_assets("Data/security/.KEY"), "rb") 721 | byteReaderData = loadEnc00.read() 722 | loadEnc00.close() 723 | 724 | byteReaderData = bytearray(byteReaderData) 725 | for index, value in enumerate(byteReaderData): 726 | byteReaderData[index] = value ^ finalKey 727 | 728 | Enc = open(relative_to_assets("Data/security/.KEY.nclmE"), "wb") 729 | Enc.write(byteReaderData) 730 | Enc.close() 731 | 732 | # Delete Data/security/KEY 733 | os.remove(relative_to_assets("Data/security/.KEY")) 734 | 735 | 736 | encryptSecurity() 737 | 738 | ``` 739 | 740 | Decrypting: 741 | 742 | ```python 743 | #! /usr/bin/env python3 744 | import base64 745 | import os 746 | import pathlib 747 | import re 748 | import string 749 | from pathlib import Path 750 | import signal 751 | 752 | # Dynamic File Path Solution 753 | KEY_PATH = pathlib.Path(__file__).parent.absolute() 754 | 755 | 756 | def relative_to_assets(path: str) -> Path: 757 | return KEY_PATH / Path(path) 758 | 759 | 760 | def signal_handler(sig, frame): 761 | # If the program exits then remove important files. 762 | os.remove(relative_to_assets("Data/security/.tmp/.KEY")) 763 | exit() 764 | 765 | 766 | def decryptSecurity(): 767 | # Use external script to make base64 or https://www.base64encode.org/ 768 | key = "MTMy" # up 255 769 | key = base64.b64decode(key) 770 | cleanKey = re.sub( 771 | r"[^A-Za-z0-9-]", "", key.decode("utf-8")) 772 | finalKey = int(cleanKey) 773 | 774 | loadEnc00 = open(relative_to_assets( 775 | "Data/security/.KEY.nclmE"), "rb").read() 776 | 777 | byteReader = bytearray(loadEnc00) 778 | for index, value in enumerate(byteReader): 779 | byteReader[index] = value ^ finalKey 780 | 781 | decEnc = open(relative_to_assets("Data/security/.tmp/.KEY"), "wb") 782 | decEnc.write(byteReader) 783 | 784 | 785 | try: 786 | # signal handler for "CTRL + C" 787 | signal.signal(signal.SIGINT, signal_handler) 788 | decryptSecurity() 789 | signal.pause() 790 | except: 791 | # In exeption remove important files. 792 | os.remove(relative_to_assets("Data/security/.tmp/.KEY")) 793 | 794 | ``` 795 | 796 |

Quick logger

797 |

Logs provide developers with an extra set of eyes that are constantly looking at the flow that an application is going through.

798 | 799 | ```python 800 | 801 | import os 802 | import time 803 | import subprocess 804 | import pathlib 805 | from pathlib import Path 806 | 807 | currentVersion = "v1.0.5 - Release" 808 | pid = os.getpid() 809 | 810 | OUTPUT_PATH = pathlib.Path(__file__).parent.absolute() 811 | LOGS_PATH = OUTPUT_PATH / Path("./logs") 812 | 813 | def relative_to_logs(path: str) -> Path: 814 | """Return a path relative to the logs folder.""" 815 | return LOGS_PATH / Path(path) 816 | 817 | def get_timestamp(): 818 | """Return a unix timestamp.""" 819 | return time.time() 820 | 821 | def logRoutine(log: str, timeNeeded: bool = True): 822 | """Write strings to the log file and if debug is enabled, print it to console.""" 823 | 824 | if timeNeeded is None: 825 | timeNeeded = True 826 | 827 | debugMode = False 828 | currentTime = time.strftime("%m-%d-%Y -> %H:%M:%S") 829 | logHeader = f"""{currentVersion} 830 | =================================================== 831 | LOG FILE MADE FOR DEBUG PURPOSES 832 | made by Nicolas Mendes - September 2021 833 | ===================================================\n 834 | """ 835 | 836 | # Check if "ioc.log" exists, if not create this file. 837 | if not os.path.exists(relative_to_logs("ioc.log")): 838 | open(f"{relative_to_logs('ioc.log')}", "w+") 839 | # append logHeader to the file. 840 | with open(f"{relative_to_logs('ioc.log')}", "a") as logFile: 841 | logFile.write(logHeader) 842 | 843 | # if the first line of ioc.log is different from currentVersion 844 | with open(f"{relative_to_logs('ioc.log')}") as checkVer: 845 | firstlineVer = checkVer.readline().rstrip() 846 | if firstlineVer != currentVersion: 847 | # Delete everything inside the file and append logHeader. 848 | with open(f"{relative_to_logs('ioc.log')}", "w+") as logFile: 849 | logFile.write(logHeader) 850 | 851 | # if the file exceeds 1000 lines, delete everything and append logHeader to the file. 852 | with open(f"{relative_to_logs('ioc.log')}", "r") as logFile: 853 | if len(logFile.readlines()) > 1000: 854 | with open(f"{relative_to_logs('ioc.log')}", "w") as logFile: 855 | logFile.write(logHeader) 856 | 857 | # Append the log to the file. 858 | 859 | if timeNeeded == True: 860 | with open(f"{relative_to_logs('ioc.log')}", "a") as logFile: 861 | logFile.write(f"{currentTime} - {log}\n") 862 | else: 863 | with open(f"{relative_to_logs('ioc.log')}", "a") as logFile: 864 | logFile.write(f"{log}\n") 865 | 866 | if debugMode == True: 867 | return print(f"DEBUG LOG: {log}") 868 | 869 | logRoutine( 870 | f"\n\n[OK] ===> Python loaded. Starting new instance at PID: {pid} | UTS: {get_timestamp()}\n", 871 | False, 872 | ) 873 | 874 | ``` 875 | 876 | 877 | ## 📄 License 878 | 879 | Permissions of this strong copyleft license are conditioned on making available complete source code of licensed works and modifications, which include larger works using a licensed work, under the same license. Copyright and license notices must be preserved. Contributors provide an express grant of patent rights. 880 | 881 | | Permissions | Restrictions | Conditions 882 | | --- | --- | --- 883 | ✓ Commercial Use | × Liability | 🛈 License and Copyright Notice 884 | ✓ Modification | × Warranty | 🛈 State changes 885 | ✓ Distribution | | 🛈 Disclose source 886 | ✓ Patent Use | | 🛈 Same license 887 | ✓ Private Use 888 | -------------------------------------------------------------------------------- /String Based Scripts/basic_input.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interesting resources: 3 | https://docs.python.org/3/library/functions.html#built-in-functions 4 | https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex 5 | https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals 6 | https://docs.python.org/3/tutorial/introduction.html#numbers 7 | https://docs.python.org/3/tutorial/modules.html#modules 8 | """ 9 | username = input("What is your name? ") 10 | print("Hello, " + username + "!") 11 | print("Tell me, how old are you?") 12 | age = input() 13 | print("You are " + age + " years old.") 14 | print("Awesome, now let me know what is your favorite number!") 15 | number = input() 16 | print("Cool, so your favorite number is " + number + ".") 17 | print("That's all, thank you.") 18 | quit() 19 | -------------------------------------------------------------------------------- /String Based Scripts/clipboard_time_defs.py: -------------------------------------------------------------------------------- 1 | """ Made by Nicolas Mendes - Sept 24 2021 2 | Script to study how to use time and clipboard. 3 | """ 4 | from datetime import date, timedelta 5 | import os 6 | 7 | namePrint = "Name Last Name" 8 | # Pick current month 9 | currentMonth = date.today().month 10 | # Pick current day 11 | currentDay = date.today().day 12 | # Randomly change between 1 and 9 mins. 13 | randomMins = int(os.urandom(1).hex(), 16) % 9 + 1 14 | hourGen = f"14:0{str(randomMins)}" 15 | targetSite = "https://discord.com/channels/XXXXX/XXXXX" 16 | print(f"The random time is: {hourGen}") 17 | 18 | 19 | def allFriday(year): 20 | d = date(year, 1, 1) # Jan 1 21 | d += timedelta(days=4 - d.weekday()) # First Friday 22 | while d.year == year: 23 | yield d 24 | d += timedelta(days=7) 25 | 26 | 27 | for dia in allFriday(2021): 28 | if dia.day == currentDay and dia.month == currentMonth: 29 | nameGen = f"{currentDay}/{currentMonth} - {namePrint}" 30 | print(nameGen) 31 | # Copy to the variable "nameGen" to the clipboard 32 | os.system(f"echo {nameGen} | pbcopy") 33 | os.system(f"open {targetSite}") 34 | -------------------------------------------------------------------------------- /String Based Scripts/downloadsOrganizer.py: -------------------------------------------------------------------------------- 1 | from watchdog.observers import Observer 2 | from watchdog.events import FileSystemEventHandler 3 | import os 4 | import time 5 | 6 | currentUser = "dreamdevourer" 7 | mainDirectory = f"/Users/{currentUser}/Downloads" 8 | 9 | jobDestinationPath = f"/Users/{currentUser}/Documents/Remotish" 10 | personalDestinationPath = f"/Users/{currentUser}/Documents/Personal" 11 | tmpPath = f"/Users/{currentUser}/Downloads/tmp" 12 | 13 | 14 | class MyHandler(FileSystemEventHandler): 15 | print("DEBUG: You are inside the MyHandler.") 16 | 17 | def on_modified(self, event): 18 | print("DEBUG: You are inside on_modified function.") 19 | for fileName in os.listdir(mainDirectory): 20 | # if the filename starts with "job_" then move it to jobDestinationPath 21 | if fileName.startswith("job_") or fileName.startswith("rem_"): 22 | print(f"{fileName} is work asset!") 23 | # move files from mainDirectory to jobDestinationPath 24 | os.rename(f"{mainDirectory}/{fileName}", 25 | f"{jobDestinationPath}/{fileName}") 26 | print(f"{fileName} moved to {jobDestinationPath}") 27 | 28 | elif fileName.startswith("per_"): 29 | print(f"{fileName} is a personal file!") 30 | # move files from mainDirectory to personalDestinationPath 31 | os.rename(f"{mainDirectory}/{fileName}", 32 | f"{personalDestinationPath}/{fileName}") 33 | print(f"{fileName} moved to {personalDestinationPath}") 34 | 35 | elif fileName.startswith("_") or fileName.startswith("tmp_") or fileName.startswith("temp_"): 36 | print(f"{fileName} is a temporary file!") 37 | # move files from mainDirectory to tmpPath 38 | os.rename(f"{mainDirectory}/{fileName}", 39 | f"{tmpPath}/{fileName}") 40 | print(f"{fileName} moved to {tmpPath}") 41 | 42 | 43 | eventHandler = MyHandler() 44 | observer = Observer() 45 | observer.schedule(eventHandler, mainDirectory, recursive=True) 46 | observer.start() 47 | 48 | try: 49 | while True: 50 | time.sleep(10) 51 | except KeyboardInterrupt: 52 | observer.stop() 53 | observer.join() 54 | -------------------------------------------------------------------------------- /String Based Scripts/hideJPG/photo copy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/String Based Scripts/hideJPG/photo copy.jpg -------------------------------------------------------------------------------- /String Based Scripts/hideJPG/photo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DreamDevourer/Python-Fundamentals-Study/28784bd8b8c9b92e631a3b1d4173d489ed71ec3d/String Based Scripts/hideJPG/photo.jpg -------------------------------------------------------------------------------- /String Based Scripts/hide_jpg_message.py: -------------------------------------------------------------------------------- 1 | """ Made by Nicolas Mendes September 26 2021 2 | Study to understand how JPG/JPEG files work in HEX form and how to hide a string in a JPG file. 3 | Basically JPG images ALWAYS start with "FF D8 FF" and ends with "FF D9". That means we can append a string 4 | on the end of this sequence "FF D9". 5 | """ 6 | import pathlib 7 | from pathlib import Path 8 | import string 9 | 10 | 11 | """ 12 | 0xffd8: "Start of Image", 13 | 0xffe0: "Application Default Header", 14 | 0xffdb: "Quantization Table", 15 | 0xffc0: "Start of Frame", 16 | 0xffc4: "Define Huffman Table", 17 | 0xffda: "Start of Scan", 18 | 0xffd9: "End of Image" 19 | """ 20 | 21 | # Initial Setup to load assets 22 | OUTPUT_PATH = pathlib.Path(__file__).parent.absolute() 23 | ASSETS_PATH = OUTPUT_PATH / Path("./hideJPG") 24 | 25 | 26 | def relative_to_assets(path: str) -> Path: 27 | return ASSETS_PATH / Path(path) 28 | 29 | 30 | while True: 31 | 32 | def writeString(): 33 | with open(relative_to_assets('photo.jpg'), 'ab') as f: # ab append bytes mode 34 | f.write(b' Hidden message: test :)') 35 | 36 | def readString(): 37 | with open(relative_to_assets('photo.jpg'), 'rb') as f: # Read bytes mode 38 | jpgContent = f.read() 39 | # when FF D9 occurs. 40 | offset = jpgContent.index(bytes.fromhex('FFD9')) 41 | f.seek(offset + 2) 42 | print(f.read()) 43 | 44 | def deleteString(): 45 | # delete everything after the last FF D9 46 | with open(relative_to_assets('photo.jpg'), 'r+') as f: # Read bytes mode 47 | jpgContent = f.read() 48 | offset = jpgContent.index(bytes.fromhex('FFD9')) 49 | f.seek(offset + 2) 50 | f.truncate() 51 | 52 | # Check if photo.jpg exists and print it. 53 | if relative_to_assets("photo.jpg").exists(): 54 | print("Found photo.jpg") 55 | readMessage = input( 56 | "Do you want to read, write or delete a message? (r/w/d) ") 57 | if readMessage == "r": 58 | readString() 59 | if readMessage == "w": 60 | writeString() 61 | if readMessage == "d": 62 | deleteString() 63 | 64 | else: 65 | print("Could not find photo.jpg") 66 | -------------------------------------------------------------------------------- /String Based Scripts/reverse_string.py: -------------------------------------------------------------------------------- 1 | # Simple like that :) 2 | userString = input("Enter a text: ") 3 | print(userString[::-1]) 4 | --------------------------------------------------------------------------------