├── .DS_Store ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── custom.md ├── .replit ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── Turtleprojects ├── Indianflag.py ├── chessboard.py ├── clock.py ├── colorfilledshapes │ ├── circle.py │ ├── hexagon.py │ ├── square.py │ ├── star.py │ └── triangle.py ├── flippingtile.py ├── olympicsymbol.py ├── polygon.py ├── rainbow.py └── yfractaltree.py ├── begineerprojects ├── ASCII_VALUE.py ├── BMI_Calculator.py ├── Simple stopwatch ├── automatescreenshot.py ├── bandnamegenerator.py ├── binarysearch.py ├── calculator.py ├── fidgedspinner.py ├── flamesgame.py ├── guessthenumber.py ├── language_detector.ipynb ├── madlibs.py ├── minesweeper.py ├── passwordgenerator.py ├── percentilecalculator.py ├── rockpaperscissor.py ├── sudoku.py ├── textbasedgame.py ├── tictactoe.py ├── tipcalculator.py ├── treasureisland.py └── wordguessinggame.py ├── guiprojects ├── agecalculator.py ├── calculator.py ├── calender.py ├── colorgame.py ├── guiform.py ├── interestcalculator.py ├── loancalculator.py ├── notepad.py ├── spellcorrector.py ├── switchpages.py ├── textdetection.py ├── weightconversion.py └── youtubedownloader.py ├── intermediateprojects ├── bubblesortvisualizer.py ├── rotatescreen.py ├── weatherreport.py └── websiteblocker.py ├── python └── pythongame1.py └── pythongames ├── 2048game.py └── 21numbergame.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sumukhmg/pythonprojects/5a5e373333854f3c682f155d2f10e4a310bc552e/.DS_Store -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.replit: -------------------------------------------------------------------------------- 1 | language = "bash" 2 | run = "" -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | 20ise0038@vvce.ac.in. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 sumukhmg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pythonprojects 2 | 3 | [![forthebadge](https://forthebadge.com/images/badges/built-by-developers.svg)](https://forthebadge.com) 4 | [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) 5 | [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](https://forthebadge.com) 6 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 7 | 8 | # PythonProjects 9 | 10 | [![All Contributors](https://img.shields.io/github/contributors/sumukhmg/pythonprojects)](#contributors-) 11 | ![Issues](https://img.shields.io/github/issues/sumukhmg/pythonprojects) 12 | ![Pull Requests](https://img.shields.io/github/issues-pr/sumukhmg/pythonprojects?) 13 | ![Forks](https://img.shields.io/github/forks/sumukhmg/pythonprojects) 14 | ![Stars](https://img.shields.io/github/stars/sumukhmg/pythonprojects) 15 | ![License](https://img.shields.io/github/license/sumukhmg/pythonprojects) 16 | 17 |

note: The code belong to the respective owners...this Repo contains collection of all those projects

18 | A collection of simple python projects from beginner to Advanced level to enhance your Python skills. 19 | 20 | ## Steps To Follow 21 | 22 | - Select an issue and ask to be _assigned_ to it. 23 | - Check existing scripts in the Repo 24 | - **Star** this repository. 25 | - On the [pythonprojects](https://github.com/sumukhmg/pythonprojects) repo page, click the **Fork** button. 26 |
27 | - **Clone** your forked repository to your local machine. This button will show you the URL to run. 28 |
29 | 30 | For example, run this command inside your terminal: 31 | 32 | ```bash 33 | git clone https://github.com//pythonprojects.git 34 | ``` 35 | 36 | **Replace \!** 37 | 38 | Learn more about 39 | [forking](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) and 40 | [cloning a repo](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository). 41 | 42 | - If you run into a **merge conflict**, you have to resolve the conflict. There are a lot of guides online, or you can try this one by [opensource.com](https://opensource.com/article/20/4/git-merge-conflict). 43 | 44 | - Checkout to development branch (*name your branch according to the issue name*). 45 | 46 | ```bash 47 | git checkout -b 48 | ``` 49 | Write your code and add to the respective folder in the projects directory, locally. 50 | 51 | Add the changes with `git add`, `git commit` ([write a good commit message](https://chris.beams.io/posts/git-commit/), if possible): 52 | 53 | ```bash 54 | git add -A 55 | git commit -m "" 56 | ``` 57 | 58 | - Push the code _to your repository_. 59 | 60 | ```bash 61 | git push origin 62 | ``` 63 | 64 | Go to the GitHub page of _your fork_, and 65 | **make a pull request**: 66 | 67 | ![pull request image](https://help.github.com/assets/images/help/pull_requests/choose-base-and-compare-branches.png) 68 | 69 | Read more about pull requests on the [GitHub help pages](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request). 70 | - Now wait, until one of us *reviews your Pull Request*! If there are any conflicts, you will get a notification. 71 | 72 | - ## Connect On Social media 73 | 74 | [Twitter](https://www.twitter.com/sumukhmg) 75 | [Linkedin](https://www.linkedin.com/in/sumukh-mg/) 76 | 77 | 78 | -------------------------------------------------------------------------------- /Turtleprojects/Indianflag.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | from turtle import* 3 | 4 | #screen for output 5 | screen = turtle.Screen() 6 | 7 | # Defining a turtle Instance 8 | t = turtle.Turtle() 9 | speed(0) 10 | 11 | # initially penup() 12 | t.penup() 13 | t.goto(-400, 250) 14 | t.pendown() 15 | 16 | # Orange Rectangle 17 | #white rectangle 18 | t.color("orange") 19 | t.begin_fill() 20 | t.forward(800) 21 | t.right(90) 22 | t.forward(167) 23 | t.right(90) 24 | t.forward(800) 25 | t.end_fill() 26 | t.left(90) 27 | t.forward(167) 28 | 29 | # Green Rectangle 30 | t.color("green") 31 | t.begin_fill() 32 | t.forward(167) 33 | t.left(90) 34 | t.forward(800) 35 | t.left(90) 36 | t.forward(167) 37 | t.end_fill() 38 | 39 | # Big Blue Circle 40 | t.penup() 41 | t.goto(70, 0) 42 | t.pendown() 43 | t.color("navy") 44 | t.begin_fill() 45 | t.circle(70) 46 | t.end_fill() 47 | 48 | # Big White Circle 49 | t.penup() 50 | t.goto(60, 0) 51 | t.pendown() 52 | t.color("white") 53 | t.begin_fill() 54 | t.circle(60) 55 | t.end_fill() 56 | 57 | # Mini Blue Circles 58 | t.penup() 59 | t.goto(-57, -8) 60 | t.pendown() 61 | t.color("navy") 62 | for i in range(24): 63 | t.begin_fill() 64 | t.circle(3) 65 | t.end_fill() 66 | t.penup() 67 | t.forward(15) 68 | t.right(15) 69 | t.pendown() 70 | 71 | # Small Blue Circle 72 | t.penup() 73 | t.goto(20, 0) 74 | t.pendown() 75 | t.begin_fill() 76 | t.circle(20) 77 | t.end_fill() 78 | # Spokes 79 | t.penup() 80 | t.goto(0, 0) 81 | t.pendown() 82 | t.pensize(2) 83 | for i in range(24): 84 | t.forward(60) 85 | t.backward(60) 86 | t.left(15) 87 | 88 | #to hold the 89 | #output window 90 | turtle.done() -------------------------------------------------------------------------------- /Turtleprojects/chessboard.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | sc = turtle.Screen() 3 | pen = turtle.Turtle() 4 | def draw(): 5 | for i in range(4): 6 | pen.forward(30) 7 | pen.left(90) 8 | pen.forward(30) 9 | 10 | 11 | if __name__ == "__main__" : 12 | 13 | sc.setup(600, 600) 14 | pen.speed(100) 15 | 16 | for i in range(8): 17 | pen.up() 18 | pen.setpos(0, 30 * i) 19 | pen.down() 20 | 21 | for j in range(8): 22 | 23 | if (i + j)% 2 == 0: 24 | col ='black' 25 | 26 | else: 27 | col ='white' 28 | 29 | pen.fillcolor(col) 30 | pen.begin_fill() 31 | 32 | draw() 33 | pen.end_fill() 34 | 35 | pen.hideturtle() -------------------------------------------------------------------------------- /Turtleprojects/clock.py: -------------------------------------------------------------------------------- 1 | import time 2 | import datetime as dt 3 | import turtle 4 | 5 | 6 | # create a turtle to display time 7 | t = turtle.Turtle() 8 | 9 | # create a turtle to create rectangle box 10 | t1 = turtle.Turtle() 11 | 12 | # create screen 13 | s = turtle.Screen() 14 | 15 | # set background color of the screen 16 | s.bgcolor("green") 17 | 18 | # obtain current hour, minute and second 19 | # from the system 20 | sec = dt.datetime.now().second 21 | min = dt.datetime.now().minute 22 | hr = dt.datetime.now().hour 23 | t1.pensize(3) 24 | t1.color('black') 25 | t1.penup() 26 | 27 | # set the position of turtle 28 | t1.goto(-20, 0) 29 | t1.pendown() 30 | 31 | # create rectangular box 32 | for i in range(2): 33 | t1.forward(200) 34 | t1.left(90) 35 | t1.forward(70) 36 | t1.left(90) 37 | 38 | # hide the turtle 39 | t1.hideturtle() 40 | 41 | while True: 42 | t.hideturtle() 43 | t.clear() 44 | # display the time 45 | t.write(str(hr).zfill(2) 46 | +":"+str(min).zfill(2)+":" 47 | +str(sec).zfill(2), 48 | font =("Arial Narrow", 35, "bold")) 49 | time.sleep(1) 50 | sec+= 1 51 | 52 | if sec == 60: 53 | sec = 0 54 | min+= 1 55 | 56 | if min == 60: 57 | min = 0 58 | hr+= 1 59 | 60 | if hr == 13: 61 | hr = 1 -------------------------------------------------------------------------------- /Turtleprojects/colorfilledshapes/circle.py: -------------------------------------------------------------------------------- 1 | # draw color filled star in turtle 2 | 3 | import turtle 4 | 5 | # creating turtle pen 6 | t = turtle.Turtle() 7 | 8 | # taking input for the side of the star 9 | s = int(input("Enter the length of the side of the star: ")) 10 | 11 | # taking the input for the color 12 | col = input("Enter the color name or hex value of color(# RRGGBB): ") 13 | 14 | # set the fillcolor 15 | t.fillcolor(col) 16 | 17 | # start the filling color 18 | t.begin_fill() 19 | 20 | # drawing the star of side s 21 | for _ in range(5): 22 | t.forward(s) 23 | t.right(144) 24 | 25 | # ending the filling of color 26 | t.end_fill() -------------------------------------------------------------------------------- /Turtleprojects/colorfilledshapes/hexagon.py: -------------------------------------------------------------------------------- 1 | # draw color-filled hexagon in turtle 2 | 3 | import turtle 4 | 5 | # creating turtle pen 6 | t = turtle.Turtle() 7 | 8 | # taking input for the side of the hexagon 9 | s = int(input("Enter the length of the side of the hexagon: ")) 10 | 11 | # taking the input for the color 12 | col = input("Enter the color name or hex value of color(# RRGGBB): ") 13 | 14 | # set the fillcolor 15 | t.fillcolor(col) 16 | 17 | # start the filling color 18 | t.begin_fill() 19 | 20 | # drawing the hexagon of side s 21 | for _ in range(6): 22 | t.forward(s) 23 | t.right(-60) 24 | 25 | # ending the filling of the color 26 | t.end_fill() -------------------------------------------------------------------------------- /Turtleprojects/colorfilledshapes/square.py: -------------------------------------------------------------------------------- 1 | # draw color-filled square in turtle 2 | 3 | import turtle 4 | 5 | # creating turtle pen 6 | t = turtle.Turtle() 7 | 8 | # taking input for the side of the square 9 | s = int(input("Enter the length of the side of the square: ")) 10 | 11 | # taking the input for the color 12 | col = input("Enter the color name or hex value of color(# RRGGBB): ") 13 | 14 | # set the fillcolor 15 | t.fillcolor(col) 16 | 17 | # start the filling color 18 | t.begin_fill() 19 | 20 | # drawing the square of side s 21 | for _ in range(4): 22 | t.forward(s) 23 | t.right(90) 24 | 25 | # ending the filling of the color 26 | t.end_fill() -------------------------------------------------------------------------------- /Turtleprojects/colorfilledshapes/star.py: -------------------------------------------------------------------------------- 1 | # draw color filled star in turtle 2 | 3 | import turtle 4 | 5 | # creating turtle pen 6 | t = turtle.Turtle() 7 | 8 | # taking input for the side of the star 9 | s = int(input("Enter the length of the side of the star: ")) 10 | 11 | # taking the input for the color 12 | col = input("Enter the color name or hex value of color(# RRGGBB): ") 13 | 14 | # set the fillcolor 15 | t.fillcolor(col) 16 | 17 | # start the filling color 18 | t.begin_fill() 19 | 20 | # drawing the star of side s 21 | for _ in range(5): 22 | t.forward(s) 23 | t.right(144) 24 | 25 | # ending the filling of color 26 | t.end_fill() -------------------------------------------------------------------------------- /Turtleprojects/colorfilledshapes/triangle.py: -------------------------------------------------------------------------------- 1 | # draw color filled triangle in turtle 2 | 3 | import turtle 4 | 5 | # creating turtle pen 6 | t = turtle.Turtle() 7 | 8 | # taking input for the side of the triangle 9 | s = int(input("Enter the length of the side of the triangle: ")) 10 | 11 | # taking the input for the color 12 | col = input("Enter the color name or hex value of color(# RRGGBB): ") 13 | 14 | # set the fillcolor 15 | t.fillcolor(col) 16 | 17 | # start the filling color 18 | t.begin_fill() 19 | 20 | # drawing the triangle of side s 21 | for _ in range(3): 22 | t.forward(s) 23 | t.right(-120) 24 | 25 | # ending the filling of the color 26 | t.end_fill() -------------------------------------------------------------------------------- /Turtleprojects/flippingtile.py: -------------------------------------------------------------------------------- 1 | # import modules 2 | from random import * 3 | from turtle import * 4 | 5 | # set the screen 6 | screen = Screen() 7 | 8 | #choose background color 9 | screen.bgcolor("yellow") 10 | 11 | # define the function 12 | # for creating a square section 13 | # for the game 14 | def Square(x, y): 15 | up() 16 | goto(x, y) 17 | down() 18 | color('white', 'green') 19 | begin_fill() 20 | for count in range(4): 21 | forward(50) 22 | left(90) 23 | end_fill() 24 | 25 | # define function to 26 | # keep a check of index number 27 | def Numbering(x, y): 28 | return int((x + 200) // 50 + ((y + 200) // 50) * 8) 29 | 30 | # define function 31 | def Coordinates(count): 32 | return (count % 8) * 50 - 200, (count // 8) * 50 - 200 33 | 34 | # define function 35 | # to make it interactive 36 | # user click 37 | def click(x, y): 38 | spot = Numbering(x, y) 39 | mark = state['mark'] 40 | 41 | if mark is None or mark == spot or tiles[mark] != tiles[spot]: 42 | state['mark'] = spot 43 | else: 44 | hide[spot] = False 45 | hide[mark] = False 46 | state['mark'] = None 47 | 48 | def draw(): 49 | clear() 50 | goto(0, 0) 51 | stamp() 52 | 53 | for count in range(64): 54 | if hide[count]: 55 | x, y = Coordinates(count) 56 | Square(x, y) 57 | 58 | mark = state['mark'] 59 | 60 | if mark is not None and hide[mark]: 61 | x, y = Coordinates(mark) 62 | up() 63 | goto(x + 2, y) 64 | color('black') 65 | write(tiles[mark], font=('Arial', 30, 'normal')) 66 | 67 | update() 68 | ontimer(draw, 10) 69 | 70 | tiles = list(range(32)) * 2 71 | state = {'mark': None} 72 | hide = [True] * 64 73 | 74 | # for shuffling the 75 | # numbers placed inside 76 | # the square tiles 77 | shuffle(tiles) 78 | tracer(False) 79 | onscreenclick(click) 80 | draw() 81 | done() -------------------------------------------------------------------------------- /Turtleprojects/olympicsymbol.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | # object tr for turtle 4 | tr = turtle.Turtle() 5 | 6 | # set thikness for each ring 7 | tr.pensize(5) 8 | 9 | tr.color("blue") 10 | tr.penup() 11 | tr.goto(-110, -25) 12 | tr.pendown() 13 | tr.circle(45) 14 | 15 | tr.color("black") 16 | tr.penup() 17 | tr.goto(0, -25) 18 | tr.pendown() 19 | tr.circle(45) 20 | 21 | tr.color("red") 22 | tr.penup() 23 | tr.goto(110, -25) 24 | tr.pendown() 25 | tr.circle(45) 26 | 27 | tr.color("yellow") 28 | tr.penup() 29 | tr.goto(-55, -75) 30 | tr.pendown() 31 | tr.circle(45) 32 | 33 | tr.color("green") 34 | tr.penup() 35 | tr.goto(55, -75) 36 | tr.pendown() 37 | tr.circle(45) 38 | -------------------------------------------------------------------------------- /Turtleprojects/polygon.py: -------------------------------------------------------------------------------- 1 | # draw any polygon in turtle 2 | 3 | import turtle 4 | 5 | # creating turtle pen 6 | t = turtle.Turtle() 7 | 8 | # taking input for the no of the sides of the polygon 9 | n = int(input("Enter the no of the sides of the polygon : ")) 10 | 11 | # taking input for the length of the sides of the polygon 12 | l = int(input("Enter the length of the sides of the polygon : ")) 13 | 14 | 15 | for _ in range(n): 16 | turtle.forward(l) 17 | turtle.right(360 / n) -------------------------------------------------------------------------------- /Turtleprojects/rainbow.py: -------------------------------------------------------------------------------- 1 | # Import turtle package 2 | import turtle 3 | 4 | # Creating a turtle screen object 5 | sc = turtle.Screen() 6 | 7 | # Creating a turtle object(pen) 8 | pen = turtle.Turtle() 9 | 10 | # Defining a method to form a semicircle 11 | # with a dynamic radius and color 12 | def semi_circle(col, rad, val): 13 | 14 | # Set the fill color of the semicircle 15 | pen.color(col) 16 | 17 | # Draw a circle 18 | pen.circle(rad, -180) 19 | 20 | # Move the turtle to air 21 | pen.up() 22 | 23 | # Move the turtle to a given position 24 | pen.setpos(val, 0) 25 | 26 | # Move the turtle to the ground 27 | pen.down() 28 | 29 | pen.right(180) 30 | 31 | 32 | # Set the colors for drawing 33 | col = ['violet', 'indigo', 'blue', 34 | 'green', 'yellow', 'orange', 'red'] 35 | 36 | # Setup the screen features 37 | sc.setup(600, 600) 38 | 39 | # Set the screen color to black 40 | sc.bgcolor('black') 41 | 42 | # Setup the turtle features 43 | pen.right(90) 44 | pen.width(10) 45 | pen.speed(7) 46 | 47 | # Loop to draw 7 semicircles 48 | for i in range(7): 49 | semi_circle(col[i], 10*( 50 | i + 8), -10*(i + 1)) 51 | 52 | # Hide the turtle 53 | pen.hideturtle() -------------------------------------------------------------------------------- /Turtleprojects/yfractaltree.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | 3 | 4 | speed('fastest') 5 | 6 | # turning the turtle to face upwards 7 | rt(-90) 8 | 9 | # the acute angle between 10 | # the base and branch of the Y 11 | angle = 30 12 | 13 | # function to plot a Y 14 | def y(sz, level): 15 | 16 | if level > 0: 17 | colormode(255) 18 | 19 | # splitting the rgb range for green 20 | # into equal intervals for each level 21 | # setting the colour according 22 | # to the current level 23 | pencolor(0, 255//level, 0) 24 | 25 | # drawing the base 26 | fd(sz) 27 | 28 | rt(angle) 29 | 30 | # recursive call for 31 | # the right subtree 32 | y(0.8 * sz, level-1) 33 | 34 | pencolor(0, 255//level, 0) 35 | 36 | lt( 2 * angle ) 37 | 38 | # recursive call for 39 | # the left subtree 40 | y(0.8 * sz, level-1) 41 | 42 | pencolor(0, 255//level, 0) 43 | 44 | rt(angle) 45 | fd(-sz) 46 | 47 | 48 | # tree of size 80 and level 7 49 | y(80, 7) 50 | -------------------------------------------------------------------------------- /begineerprojects/ASCII_VALUE.py: -------------------------------------------------------------------------------- 1 | # Program to find the ASCII value of the given character 2 | 3 | c = 'p' 4 | print("The ASCII value of '" + c + "' is", ord(c)) 5 | 6 | -------------------------------------------------------------------------------- /begineerprojects/BMI_Calculator.py: -------------------------------------------------------------------------------- 1 | Height=float(input("Enter your height in centimeters: ")) 2 | Weight=float(input("Enter your Weight in Kg: ")) 3 | Height = Height/100 4 | BMI=Weight/(Height*Height) 5 | print("Your Body Mass Index is: ", BMI) 6 | if(BMI>0): 7 | if(BMI<=16): 8 | print("you are severely underweight") 9 | elif(BMI<=18.5): 10 | print("you are underweight") 11 | elif(BMI<=25): 12 | print("you are Healthy") 13 | elif(BMI<=30): 14 | print("you are overweight") 15 | else: print("you are severely overweight") 16 | else:("enter valid details") -------------------------------------------------------------------------------- /begineerprojects/Simple stopwatch: -------------------------------------------------------------------------------- 1 | import time 2 | import sys 3 | 4 | # it will only accept lowercase inputs. 5 | # the steps are: 1 - start stopwatch, 2 - stop stopwatch and 3 - calculate time passed. 6 | 7 | start = input('Start stopwatch? y/n: ') 8 | if start == "y": 9 | startTime = time.time() 10 | else: 11 | print("program closed") 12 | sys.exit() # the sys.exit() when activated will exit and stop the script 13 | 14 | 15 | finish = input("Stop? y/n: ") 16 | if finish == "y": 17 | finishTime = time.time() 18 | else: 19 | print("program closed") 20 | sys.exit() 21 | 22 | 23 | calculate = input("Calculate? y/n: ") 24 | if calculate == "y": 25 | print("Time passed =", (finishTime - startTime), "seconds.") 26 | else: 27 | print("program closed") 28 | sys.exit() 29 | -------------------------------------------------------------------------------- /begineerprojects/automatescreenshot.py: -------------------------------------------------------------------------------- 1 | # Program to take screenshot 2 | 3 | import pyscreenshot 4 | 5 | # To capture the screen 6 | image = pyscreenshot.grab() 7 | 8 | # To display the captured screenshot 9 | image.show() 10 | 11 | # To save the screenshot 12 | image.save("screenshot.png") -------------------------------------------------------------------------------- /begineerprojects/bandnamegenerator.py: -------------------------------------------------------------------------------- 1 | #printing welcome 2 | print("welcome to band name generator") 3 | #taking cityname as input 4 | cityname=input("what is your city name?\n") 5 | #taking favfood as input 6 | favfood=input("what is your favourite food?\n") 7 | #combining cityname and favfood to show the band name 8 | print("The band name is " +cityname + " " + favfood) -------------------------------------------------------------------------------- /begineerprojects/binarysearch.py: -------------------------------------------------------------------------------- 1 | 2 | import random 3 | import time 4 | 5 | # Implementation of binary search algorithm!! 6 | 7 | # We will prove that binary search is faster than naive search! 8 | 9 | 10 | # Essence of binary search: 11 | # If you have a sorted list and you want to search this array for something, 12 | # You could go through each item in the list and ask, is this equal to what we're looking for? 13 | # But we can make this *faster* by leveraging the fact that our array is sorted! 14 | # Binary search ~ O(log(n)), naive search ~ O(n) 15 | 16 | # In these two examples, l is a list in ascending order, and target is something that we're looking for 17 | # Return -1 if not found 18 | 19 | 20 | # naive search: scan entire list and ask if its equal to the target 21 | # if yes, return the index 22 | # if no, then return -1 23 | def naive_search(l, target): 24 | # example l = [1, 3, 10, 12] 25 | for i in range(len(l)): 26 | if l[i] == target: 27 | return i 28 | return -1 29 | 30 | 31 | # binary search uses divide and conquer! 32 | # we will leverage the fact that our list is SORTED 33 | def binary_search(l, target, low=None, high=None): 34 | if low is None: 35 | low = 0 36 | if high is None: 37 | high = len(l) - 1 38 | 39 | if high < low: 40 | return -1 41 | 42 | # example l = [1, 3, 5, 10, 12] # should return 3 43 | midpoint = (low + high) // 2 # 2 44 | 45 | # we'll check if l[midpoint] == target, and if not, we can find out if 46 | # target will be to the left or right of midpoint 47 | # we know everything to the left of midpoint is smaller than the midpoint 48 | # and everything to the right is larger 49 | if l[midpoint] == target: 50 | return midpoint 51 | elif target < l[midpoint]: 52 | return binary_search(l, target, low, midpoint-1) 53 | else: 54 | # target > l[midpoint] 55 | return binary_search(l, target, midpoint+1, high) 56 | 57 | if __name__=='__main__': 58 | # l = [1, 3, 5, 10, 12] 59 | # target = 7 60 | # print(naive_search(l, target)) 61 | # print(binary_search(l, target)) 62 | 63 | length = 10000 64 | # build a sorted list of length 10000 65 | sorted_list = set() 66 | while len(sorted_list) < length: 67 | sorted_list.add(random.randint(-3*length, 3*length)) 68 | sorted_list = sorted(list(sorted_list)) 69 | 70 | start = time.time() 71 | for target in sorted_list: 72 | naive_search(sorted_list, target) 73 | end = time.time() 74 | print("Naive search time: ", (end - start), "seconds") 75 | 76 | start = time.time() 77 | for target in sorted_list: 78 | binary_search(sorted_list, target) 79 | end = time.time() 80 | print("Binary search time: ", (end - start), "seconds") -------------------------------------------------------------------------------- /begineerprojects/calculator.py: -------------------------------------------------------------------------------- 1 | def addition(a,b): 2 | print("Addition of",a ,b,"is",a+b) 3 | 4 | def subtraction(num1,num2): 5 | print("subtraction of ",a ,b,"is",a-b) 6 | 7 | def multiplication(num1,num2): 8 | print("multiplication of",a ,b,"is",a*b) 9 | 10 | def division(num1,num2): 11 | print("division of",a ,b,"is",a/b) 12 | 13 | def remainder(num1,num2): 14 | print("remainder of",a ,b,"is",a%b) 15 | 16 | def quotient(num1,num2): 17 | print("quotient of",a ,b,"is",a//b) 18 | 19 | while True: 20 | print("1. Addition") 21 | print("2. Subtraction") 22 | print("3. Multiplication") 23 | print("4. Division") 24 | print("5. remainder") 25 | print("6. quotient") 26 | print("7. Exit") 27 | choice=int(input("Enter your choice(1-7):")) 28 | 29 | if choice==1: 30 | a=int(input("Enter First Number:")) 31 | b=int(input("Enter Second Number:")) 32 | addition(a,b) 33 | 34 | 35 | elif choice==2: 36 | a=int(input("Enter First Number:")) 37 | b=int(input("Enter Second Number:")) 38 | subtraction(a,b) 39 | 40 | elif choice==3: 41 | a=int(input("Enter First Number:")) 42 | b=int(input("Enter SecondNumber:")) 43 | multiplication(a,b) 44 | 45 | elif choice==4: 46 | a=int(input("Enter First Number:")) 47 | b=int(input("Enter Second Number:")) 48 | if b == 0: 49 | print('Infinity') 50 | else: 51 | division(a,b) 52 | 53 | elif choice==5: 54 | a=int(input("Enter First Number:")) 55 | b=int(input("Enter Second Number:")) 56 | remainder(a,b) 57 | 58 | elif choice==6: 59 | a=int(input("Enter First Number:")) 60 | b=int(input("Enter Second Number:")) 61 | quotient(a,b) 62 | 63 | elif choice==7: 64 | break 65 | 66 | else: 67 | print("Wrong Choice") 68 | 69 | -------------------------------------------------------------------------------- /begineerprojects/fidgedspinner.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | state = {'turn': 0} 3 | def spinner(): 4 | clear() 5 | angle = state['turn']/10 6 | right(angle) 7 | forward(100) 8 | dot(80, 'violet') 9 | back(100) 10 | right(51.42) 11 | forward(100) 12 | dot(80, 'indigo') 13 | back(100) 14 | right(51.42) 15 | forward(100) 16 | dot(80, 'blue') 17 | back(100) 18 | right(51.42) 19 | forward(100) 20 | dot(80, 'green') 21 | back(100) 22 | right(51.42) 23 | forward(100) 24 | dot(80, 'yellow') 25 | back(100) 26 | right(51.42) 27 | forward(100) 28 | dot(80, 'orange') 29 | back(100) 30 | right(51.42) 31 | forward(100) 32 | dot(80, 'red') 33 | back(100) 34 | right(51.42) 35 | update() 36 | def animate(): 37 | if state['turn']>0: 38 | state['turn']-=1 39 | 40 | spinner() 41 | ontimer(animate, 20) 42 | def flick(): 43 | state['turn']+=10 44 | 45 | setup(420, 420, 370, 0) 46 | hideturtle() 47 | tracer(False) 48 | width(20) 49 | onkey(flick, 'space') 50 | listen() 51 | animate() 52 | done() -------------------------------------------------------------------------------- /begineerprojects/flamesgame.py: -------------------------------------------------------------------------------- 1 | # function for removing common characters 2 | # with their respective occurrences 3 | def remove_match_char(list1, list2): 4 | 5 | for i in range(len(list1)) : 6 | for j in range(len(list2)) : 7 | 8 | # if common character is found 9 | # then remove that character 10 | # and return list of concatenated 11 | # list with True Flag 12 | if list1[i] == list2[j] : 13 | c = list1[i] 14 | 15 | # remove character from the list 16 | list1.remove(c) 17 | list2.remove(c) 18 | 19 | # concatenation of two list elements with * 20 | # * is act as border mark here 21 | list3 = list1 + ["*"] + list2 22 | 23 | # return the concatenated list with True flag 24 | return [list3, True] 25 | 26 | # no common characters is found 27 | # return the concatenated list with False flag 28 | list3 = list1 + ["*"] + list2 29 | return [list3, False] 30 | 31 | # Driver code 32 | if __name__ == "__main__" : 33 | 34 | # take first name 35 | p1 = input("Player 1 name : ") 36 | 37 | # converted all letters into lower case 38 | p1 = p1.lower() 39 | 40 | # replace any space with empty string 41 | p1.replace(" ", "") 42 | 43 | # make a list of letters or characters 44 | p1_list = list(p1) 45 | 46 | # take 2nd name 47 | p2 = input("Player 2 name : ") 48 | p2 = p2.lower() 49 | p2.replace(" ", "") 50 | p2_list = list(p2) 51 | 52 | # taking a flag as True initially 53 | proceed = True 54 | 55 | # keep calling remove_match_char function 56 | # until common characters is found or 57 | # keep looping until proceed flag is True 58 | while proceed : 59 | 60 | # function calling and store return value 61 | ret_list = remove_match_char(p1_list, p2_list) 62 | 63 | # take out concatenated list from return list 64 | con_list = ret_list[0] 65 | 66 | # take out flag value from return list 67 | proceed = ret_list[1] 68 | 69 | # find the index of "*" / border mark 70 | star_index = con_list.index("*") 71 | 72 | # list slicing perform 73 | 74 | # all characters before * store in p1_list 75 | p1_list = con_list[ : star_index] 76 | 77 | # all characters after * store in p2_list 78 | p2_list = con_list[star_index + 1 : ] 79 | 80 | 81 | # count total remaining characters 82 | count = len(p1_list) + len(p2_list) 83 | 84 | # list of FLAMES acronym 85 | result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"] 86 | 87 | # keep looping until only one item 88 | # is not remaining in the result list 89 | while len(result) > 1 : 90 | 91 | # store that index value from 92 | # where we have to perform slicing. 93 | split_index = (count % len(result) - 1) 94 | 95 | # this steps is done for performing 96 | # anticlock-wise circular fashion counting. 97 | if split_index >= 0 : 98 | 99 | # list slicing 100 | right = result[split_index + 1 : ] 101 | left = result[ : split_index] 102 | 103 | # list concatenation 104 | result = right + left 105 | 106 | else : 107 | result = result[ : len(result) - 1] 108 | 109 | # print final result 110 | print("Relationship status :", result[0]) 111 | -------------------------------------------------------------------------------- /begineerprojects/guessthenumber.py: -------------------------------------------------------------------------------- 1 | #this is a number guess game. 2 | import random 3 | secretnumber=random.randint(1,50) 4 | 5 | #asking player to guess 6 times. 6 | for guesstaken in range(1,7): 7 | print(" guess number between 1 to 50 :)") 8 | guess = int(input()) 9 | 10 | if guess < secretnumber: 11 | print("your guess is too low. ") 12 | elif guess>secretnumber: 13 | print("your guess is too high") 14 | else: 15 | break 16 | if guess == secretnumber: 17 | print("Good Job! you guessed my number in" + " " + str(guesstaken) +"guesses!") 18 | else: 19 | print("nope. the number i was thinking of was"+" "+ str(secretnumber)) -------------------------------------------------------------------------------- /begineerprojects/language_detector.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from langdetect import detect\n", 10 | "import tkinter as tk" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "def detect_lang():\n", 20 | " window = tk.Tk()\n", 21 | " window.geometry('600x400')\n", 22 | " head = tk.Label(window, text='Language Detector', font=('Arial 15'))\n", 23 | " head.pack(pady=20)\n", 24 | "\n", 25 | " def check_language():\n", 26 | " new_text = text.get()\n", 27 | " lang = detect(str(new_text))\n", 28 | " tk.Label(window, text=lang, font=('Arial 15')).place(x=250, y=200)\n", 29 | "\n", 30 | " text = tk.StringVar()\n", 31 | " tk.Entry(window, textvariable=text).place(\n", 32 | " x=200, y=80, height=30, width=280)\n", 33 | " tk.Button(window, text='Test Language',\n", 34 | " command=check_language).place(x=300, y=150)\n", 35 | " window.mainloop()\n", 36 | "\n", 37 | "\n", 38 | "if __name__ == '__main__':\n", 39 | " detect_lang()" 40 | ] 41 | } 42 | ], 43 | "metadata": { 44 | "kernelspec": { 45 | "display_name": "Python 3.10.7 64-bit", 46 | "language": "python", 47 | "name": "python3" 48 | }, 49 | "language_info": { 50 | "codemirror_mode": { 51 | "name": "ipython", 52 | "version": 3 53 | }, 54 | "file_extension": ".py", 55 | "mimetype": "text/x-python", 56 | "name": "python", 57 | "nbconvert_exporter": "python", 58 | "pygments_lexer": "ipython3", 59 | "version": "3.10.7" 60 | }, 61 | "orig_nbformat": 4, 62 | "vscode": { 63 | "interpreter": { 64 | "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49" 65 | } 66 | } 67 | }, 68 | "nbformat": 4, 69 | "nbformat_minor": 2 70 | } 71 | -------------------------------------------------------------------------------- /begineerprojects/madlibs.py: -------------------------------------------------------------------------------- 1 | #this is only sample of madlib.you can have different statements for it. 2 | adj1=input("enter first adjective:") 3 | adj2=input("enter second adjective") 4 | adj3=input("enter third adjective") 5 | verb1=input("enter first verb") 6 | verb2=input("enter second verb") 7 | noun=input("enter noun") 8 | madlib=f"our school cafteria has really {adj1} food.just thinking about it makes my stomach {verb1}.the spaghetti is {adj2} and tastes like {noun}.one day i swear one of my meatballs started to {verb2}!.the turky tacos are totally {adj3} and look kind of like old {noun}." 9 | print(madlib) -------------------------------------------------------------------------------- /begineerprojects/minesweeper.py: -------------------------------------------------------------------------------- 1 | #code credits: Kylie Ying 2 | import random 3 | import re 4 | 5 | # lets create a board object to represent the minesweeper game 6 | # this is so that we can just say "create a new board object", or 7 | # "dig here", or "render this game for this object" 8 | class Board: 9 | def __init__(self, dim_size, num_bombs): 10 | # let's keep track of these parameters. they'll be helpful later 11 | self.dim_size = dim_size 12 | self.num_bombs = num_bombs 13 | 14 | # let's create the board 15 | # helper function! 16 | self.board = self.make_new_board() # plant the bombs 17 | self.assign_values_to_board() 18 | 19 | # initialize a set to keep track of which locations we've uncovered 20 | # we'll save (row,col) tuples into this set 21 | self.dug = set() # if we dig at 0, 0, then self.dug = {(0,0)} 22 | 23 | def make_new_board(self): 24 | # construct a new board based on the dim size and num bombs 25 | # we should construct the list of lists here (or whatever representation you prefer, 26 | # but since we have a 2-D board, list of lists is most natural) 27 | 28 | # generate a new board 29 | board = [[None for _ in range(self.dim_size)] for _ in range(self.dim_size)] 30 | # this creates an array like this: 31 | # [[None, None, ..., None], 32 | # [None, None, ..., None], 33 | # [... ], 34 | # [None, None, ..., None]] 35 | # we can see how this represents a board! 36 | 37 | # plant the bombs 38 | bombs_planted = 0 39 | while bombs_planted < self.num_bombs: 40 | loc = random.randint(0, self.dim_size**2 - 1) # return a random integer N such that a <= N <= b 41 | row = loc // self.dim_size # we want the number of times dim_size goes into loc to tell us what row to look at 42 | col = loc % self.dim_size # we want the remainder to tell us what index in that row to look at 43 | 44 | if board[row][col] == '*': 45 | # this means we've actually planted a bomb there already so keep going 46 | continue 47 | 48 | board[row][col] = '*' # plant the bomb 49 | bombs_planted += 1 50 | 51 | return board 52 | 53 | def assign_values_to_board(self): 54 | # now that we have the bombs planted, let's assign a number 0-8 for all the empty spaces, which 55 | # represents how many neighboring bombs there are. we can precompute these and it'll save us some 56 | # effort checking what's around the board later on :) 57 | for r in range(self.dim_size): 58 | for c in range(self.dim_size): 59 | if self.board[r][c] == '*': 60 | # if this is already a bomb, we don't want to calculate anything 61 | continue 62 | self.board[r][c] = self.get_num_neighboring_bombs(r, c) 63 | 64 | def get_num_neighboring_bombs(self, row, col): 65 | # let's iterate through each of the neighboring positions and sum number of bombs 66 | # top left: (row-1, col-1) 67 | # top middle: (row-1, col) 68 | # top right: (row-1, col+1) 69 | # left: (row, col-1) 70 | # right: (row, col+1) 71 | # bottom left: (row+1, col-1) 72 | # bottom middle: (row+1, col) 73 | # bottom right: (row+1, col+1) 74 | 75 | # make sure to not go out of bounds! 76 | 77 | num_neighboring_bombs = 0 78 | for r in range(max(0, row-1), min(self.dim_size-1, row+1)+1): 79 | for c in range(max(0, col-1), min(self.dim_size-1, col+1)+1): 80 | if r == row and c == col: 81 | # our original location, don't check 82 | continue 83 | if self.board[r][c] == '*': 84 | num_neighboring_bombs += 1 85 | 86 | return num_neighboring_bombs 87 | 88 | def dig(self, row, col): 89 | # dig at that location! 90 | # return True if successful dig, False if bomb dug 91 | 92 | # a few scenarios: 93 | # hit a bomb -> game over 94 | # dig at location with neighboring bombs -> finish dig 95 | # dig at location with no neighboring bombs -> recursively dig neighbors! 96 | 97 | self.dug.add((row, col)) # keep track that we dug here 98 | 99 | if self.board[row][col] == '*': 100 | return False 101 | elif self.board[row][col] > 0: 102 | return True 103 | 104 | # self.board[row][col] == 0 105 | for r in range(max(0, row-1), min(self.dim_size-1, row+1)+1): 106 | for c in range(max(0, col-1), min(self.dim_size-1, col+1)+1): 107 | if (r, c) in self.dug: 108 | continue # don't dig where you've already dug 109 | self.dig(r, c) 110 | 111 | # if our initial dig didn't hit a bomb, we *shouldn't* hit a bomb here 112 | return True 113 | 114 | def __str__(self): 115 | # this is a magic function where if you call print on this object, 116 | # it'll print out what this function returns! 117 | # return a string that shows the board to the player 118 | 119 | # first let's create a new array that represents what the user would see 120 | visible_board = [[None for _ in range(self.dim_size)] for _ in range(self.dim_size)] 121 | for row in range(self.dim_size): 122 | for col in range(self.dim_size): 123 | if (row,col) in self.dug: 124 | visible_board[row][col] = str(self.board[row][col]) 125 | else: 126 | visible_board[row][col] = ' ' 127 | 128 | # put this together in a string 129 | string_rep = '' 130 | # get max column widths for printing 131 | widths = [] 132 | for idx in range(self.dim_size): 133 | columns = map(lambda x: x[idx], visible_board) 134 | widths.append( 135 | len( 136 | max(columns, key = len) 137 | ) 138 | ) 139 | 140 | # print the csv strings 141 | indices = [i for i in range(self.dim_size)] 142 | indices_row = ' ' 143 | cells = [] 144 | for idx, col in enumerate(indices): 145 | format = '%-' + str(widths[idx]) + "s" 146 | cells.append(format % (col)) 147 | indices_row += ' '.join(cells) 148 | indices_row += ' \n' 149 | 150 | for i in range(len(visible_board)): 151 | row = visible_board[i] 152 | string_rep += f'{i} |' 153 | cells = [] 154 | for idx, col in enumerate(row): 155 | format = '%-' + str(widths[idx]) + "s" 156 | cells.append(format % (col)) 157 | string_rep += ' |'.join(cells) 158 | string_rep += ' |\n' 159 | 160 | str_len = int(len(string_rep) / self.dim_size) 161 | string_rep = indices_row + '-'*str_len + '\n' + string_rep + '-'*str_len 162 | 163 | return string_rep 164 | 165 | # play the game 166 | def play(dim_size=10, num_bombs=10): 167 | # Step 1: create the board and plant the bombs 168 | board = Board(dim_size, num_bombs) 169 | 170 | # Step 2: show the user the board and ask for where they want to dig 171 | # Step 3a: if location is a bomb, show game over message 172 | # Step 3b: if location is not a bomb, dig recursively until each square is at least 173 | # next to a bomb 174 | # Step 4: repeat steps 2 and 3a/b until there are no more places to dig -> VICTORY! 175 | safe = True 176 | 177 | while len(board.dug) < board.dim_size ** 2 - num_bombs: 178 | print(board) 179 | # 0,0 or 0, 0 or 0, 0 180 | user_input = re.split(',(\\s)*', input("Where would you like to dig? Input as row,col: ")) # '0, 3' 181 | row, col = int(user_input[0]), int(user_input[-1]) 182 | if row < 0 or row >= board.dim_size or col < 0 or col >= dim_size: 183 | print("Invalid location. Try again.") 184 | continue 185 | 186 | # if it's valid, we dig 187 | safe = board.dig(row, col) 188 | if not safe: 189 | # dug a bomb ahhhhhhh 190 | break # (game over rip) 191 | 192 | # 2 ways to end loop, lets check which one 193 | if safe: 194 | print("CONGRATULATIONS!!!! YOU ARE VICTORIOUS!") 195 | else: 196 | print("SORRY GAME OVER :(") 197 | # let's reveal the whole board! 198 | board.dug = [(r,c) for r in range(board.dim_size) for c in range(board.dim_size)] 199 | print(board) 200 | 201 | if __name__ == '__main__': # good practice :) 202 | play() 203 | -------------------------------------------------------------------------------- /begineerprojects/passwordgenerator.py: -------------------------------------------------------------------------------- 1 | import random 2 | passlen = int(input("enter the length of password")) 3 | s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?" 4 | p = "".join(random.sample(s,passlen )) 5 | print(p) -------------------------------------------------------------------------------- /begineerprojects/percentilecalculator.py: -------------------------------------------------------------------------------- 1 | # import all functions from the tkinter 2 | from tkinter import * 3 | 4 | 5 | # Function to calculate the percentile 6 | def getPercentile() : 7 | 8 | # take a value from the respective entry boxespython 9 | # get method returns current text as string 10 | students= int(total_participantField.get()) 11 | 12 | rank = int(rankField.get()) 13 | 14 | # variable to store the result upto 3 15 | # decimal points 16 | result = round((students - rank) / students * 100,3); 17 | 18 | # insert method inserting the 19 | # value in the text entry box. 20 | percentileField.insert(10, str(result)) 21 | 22 | 23 | # Function for clearing the 24 | # contents of all text entry boxes 25 | def Clear(): 26 | 27 | # deleting the content from the entry box 28 | rankField.delete(0, END) 29 | 30 | total_participantField.delete(0, END) 31 | 32 | percentileField.delete(0, END) 33 | 34 | 35 | # Driver Code 36 | if __name__ == "__main__" : 37 | 38 | # Create a GUI window 39 | gui = Tk() 40 | 41 | # Set the background colour of GUI window 42 | gui.configure(background = "light green") 43 | 44 | # set the name of tkinter GUI window 45 | gui.title("Rank Based- Percentile Calculator") 46 | 47 | # Set the configuration of GUI window 48 | gui.geometry("650x200") 49 | 50 | # Create a Rank: label 51 | rank = Label(gui, text = "Rank", bg = "blue") 52 | 53 | # Create a And: label 54 | andl = Label(gui, text = "And", bg = "blue") 55 | 56 | # Create a Total Participants : label 57 | total_participant = Label(gui, 58 | text = "Total Participants", 59 | bg = "blue") 60 | 61 | # Create a Find Percentile Button and 62 | # attached to getPercentile function 63 | find = Button(gui, text = "Find Percentile", 64 | fg = "Black", bg = "Red", 65 | command = getPercentile) 66 | 67 | # Create a Percentile : label 68 | percentile = Label(gui, text = "Percentile", bg = "blue") 69 | 70 | # Create a Clear Button and attached 71 | # to Clear function 72 | clear = Button(gui, text = "Clear", 73 | fg = "Black", bg = "Red", 74 | command = Clear) 75 | 76 | # grid method is used for placing 77 | # the widgets at respective positions 78 | # in table like structure . 79 | 80 | # padx attributed provide x-axis margin 81 | # from the root window to the widget. 82 | rank.grid(row = 1, column = 1,padx = 10) 83 | 84 | andl.grid(row = 1, column = 4) 85 | 86 | total_participant.grid(row = 1, column = 6, padx = 10) 87 | 88 | # pady attributed provide y-axis 89 | # margin from the widget. 90 | find.grid(row = 3, column = 4,pady = 10) 91 | 92 | percentile.grid(row = 4, column = 3,padx = 10) 93 | 94 | clear.grid(row = 5, column = 4,pady = 10) 95 | 96 | # Create a text entry box for filling or 97 | # typing the information. 98 | rankField = Entry(gui) 99 | 100 | total_participantField = Entry(gui) 101 | 102 | percentileField = Entry(gui) 103 | 104 | # grid method is used for placing 105 | # the widgets at respective positions 106 | # in table like structure . 107 | rankField.grid(row = 1, column = 2) 108 | 109 | total_participantField.grid(row = 1, column = 7) 110 | 111 | percentileField.grid(row = 4, column = 4) 112 | 113 | # Start the GUI 114 | gui.mainloop() 115 | -------------------------------------------------------------------------------- /begineerprojects/rockpaperscissor.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | rock = ''' 4 | _______ 5 | ---' ____) 6 | (_____) 7 | (_____) 8 | (____) 9 | ---.__(___) 10 | ''' 11 | 12 | paper = ''' 13 | _______ 14 | ---' ____)____ 15 | ______) 16 | _______) 17 | _______) 18 | ---.__________) 19 | ''' 20 | 21 | scissors = ''' 22 | _______ 23 | ---' ____)____ 24 | ______) 25 | __________) 26 | (____) 27 | ---.__(___) 28 | ''' 29 | game_images = [rock, paper, scissors] 30 | 31 | user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n")) 32 | if user_choice >= 3 or user_choice < 0: 33 | print("You typed an invalid number, you lose!") 34 | else: 35 | print(game_images[user_choice]) 36 | 37 | computer_choice = random.randint(0, 2) 38 | print("Computer chose:") 39 | print(game_images[computer_choice]) 40 | 41 | 42 | if user_choice == 0 and computer_choice == 2: 43 | print("You win!\n") 44 | elif computer_choice == 0 and user_choice == 2: 45 | print("You lose\n") 46 | elif computer_choice > user_choice: 47 | print("You lose\n") 48 | elif user_choice > computer_choice: 49 | print("You win!\n") 50 | elif computer_choice == user_choice: 51 | print("It's a draw\n") -------------------------------------------------------------------------------- /begineerprojects/sudoku.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #code credits: Kylie ying 4 | 5 | from pprint import pprint 6 | 7 | 8 | def find_next_empty(puzzle): 9 | # finds the next row, col on the puzzle that's not filled yet --> rep with -1 10 | # return row, col tuple (or (None, None) if there is none) 11 | 12 | # keep in mind that we are using 0-8 for our indices 13 | for r in range(9): 14 | for c in range(9): # range(9) is 0, 1, 2, ... 8 15 | if puzzle[r][c] == -1: 16 | return r, c 17 | 18 | return None, None # if no spaces in the puzzle are empty (-1) 19 | 20 | def is_valid(puzzle, guess, row, col): 21 | # figures out whether the guess at the row/col of the puzzle is a valid guess 22 | # returns True or False 23 | 24 | # for a guess to be valid, then we need to follow the sudoku rules 25 | # that number must not be repeated in the row, column, or 3x3 square that it appears in 26 | 27 | # let's start with the row 28 | row_vals = puzzle[row] 29 | if guess in row_vals: 30 | return False # if we've repeated, then our guess is not valid! 31 | 32 | # now the column 33 | # col_vals = [] 34 | # for i in range(9): 35 | # col_vals.append(puzzle[i][col]) 36 | col_vals = [puzzle[i][col] for i in range(9)] 37 | if guess in col_vals: 38 | return False 39 | 40 | # and then the square 41 | row_start = (row // 3) * 3 # 10 // 3 = 3, 5 // 3 = 1, 1 // 3 = 0 42 | col_start = (col // 3) * 3 43 | 44 | for r in range(row_start, row_start + 3): 45 | for c in range(col_start, col_start + 3): 46 | if puzzle[r][c] == guess: 47 | return False 48 | 49 | return True 50 | 51 | def solve_sudoku(puzzle): 52 | # solve sudoku using backtracking! 53 | # our puzzle is a list of lists, where each inner list is a row in our sudoku puzzle 54 | # return whether a solution exists 55 | # mutates puzzle to be the solution (if solution exists) 56 | 57 | # step 1: choose somewhere on the puzzle to make a guess 58 | row, col = find_next_empty(puzzle) 59 | 60 | # step 1.1: if there's nowhere left, then we're done because we only allowed valid inputs 61 | if row is None: # this is true if our find_next_empty function returns None, None 62 | return True 63 | 64 | # step 2: if there is a place to put a number, then make a guess between 1 and 9 65 | for guess in range(1, 10): # range(1, 10) is 1, 2, 3, ... 9 66 | # step 3: check if this is a valid guess 67 | if is_valid(puzzle, guess, row, col): 68 | # step 3.1: if this is a valid guess, then place it at that spot on the puzzle 69 | puzzle[row][col] = guess 70 | # step 4: then we recursively call our solver! 71 | if solve_sudoku(puzzle): 72 | return True 73 | 74 | # step 5: it not valid or if nothing gets returned true, then we need to backtrack and try a new number 75 | puzzle[row][col] = -1 76 | 77 | # step 6: if none of the numbers that we try work, then this puzzle is UNSOLVABLE!! 78 | return False 79 | 80 | if __name__ == '__main__': 81 | example_board = [ 82 | [3, 9, -1, -1, 5, -1, -1, -1, -1], 83 | [-1, -1, -1, 2, -1, -1, -1, -1, 5], 84 | [-1, -1, -1, 7, 1, 9, -1, 8, -1], 85 | 86 | [-1, 5, -1, -1, 6, 8, -1, -1, -1], 87 | [2, -1, 6, -1, -1, 3, -1, -1, -1], 88 | [-1, -1, -1, -1, -1, -1, -1, -1, 4], 89 | 90 | [5, -1, -1, -1, -1, -1, -1, -1, -1], 91 | [6, 7, -1, 1, -1, 5, -1, 4, -1], 92 | [1, -1, 9, -1, -1, -1, 2, -1, -1] 93 | ] 94 | print(solve_sudoku(example_board)) 95 | pprint(example_board) 96 | -------------------------------------------------------------------------------- /begineerprojects/textbasedgame.py: -------------------------------------------------------------------------------- 1 | answer_yes = ["Yes", "Y", "yes", "y"] 2 | answer_no = ["No", "N", "no", "n"] 3 | 4 | print(""" 5 | WELCOME! LET'S START THE ADVENTURE 6 | 7 | You are standing outside of your house and you see a man running towards you and asking for urgent shelter. 8 | 9 | Will you provide shelter to him. (Yes / No) 10 | """) 11 | 12 | ans1 = input(">>") 13 | 14 | if ans1 in answer_yes: 15 | print("\nAfter 2 minutes, the Police came to your house, and ask you that whether the thief is in your house or not. Will you say (Yes / No)\n") 16 | 17 | ans2 = input(">>") 18 | 19 | if ans2 in answer_yes: 20 | print("\nYou are an honest person. He was a thief & You won the Game") 21 | 22 | elif ans2 in answer_no: 23 | print("\nYou helped a thief. Now, go to Jail. GAME OVER") 24 | 25 | else: 26 | print("\nYou typed the wrong input. GOODBYE!") 27 | 28 | elif ans1 in answer_no: 29 | print("\nNow, he is trying to kill you. Will, you knock him down? (Yes / No)\n") 30 | 31 | ans3 = input(">>") 32 | 33 | if ans3 in answer_yes: 34 | print("\nCongrats! He was a thief & You helped the police to catch him with your bravery.") 35 | 36 | elif ans3 in answer_no: 37 | print("\nSorry! You are dead. He was a thief & He killed you. GAME OVER") 38 | 39 | else: 40 | print("\nYou typed the wrong input. GOODBYE!") 41 | 42 | else: 43 | print("\nYou typed the wrong input. GOODBYE!") -------------------------------------------------------------------------------- /begineerprojects/tictactoe.py: -------------------------------------------------------------------------------- 1 | """ Tic Tac Toe 2 | ---------------------------------------- 3 | """ 4 | import random 5 | import sys 6 | board=[i for i in range(0,9)] 7 | player, computer = '','' 8 | #Corners, Center and Others, respectively 9 | moves=((1,7,3,9),(5,),(2,4,6,8)) 10 | # Winner combinations 11 | winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) 12 | # Table 13 | tab=range(1,10) 14 | def print_board(): 15 | x=1 16 | for i in board: 17 | end = ' | ' 18 | if x%3 == 0: 19 | end = ' \n' 20 | if i != 1: end+='---------\n'; 21 | char=' ' 22 | if i in ('X','O'): char=i; 23 | x+=1 24 | print(char,end=end) 25 | def select_char(): 26 | chars=('X','O') 27 | if random.randint(0,1) == 0: 28 | return chars[::-1] 29 | return chars 30 | def can_move(brd, player, move): 31 | if move in tab and brd[move-1] == move-1: 32 | return True 33 | return False 34 | def can_win(brd, player, move): 35 | places=[] 36 | x=0 37 | for i in brd: 38 | if i == player: places.append(x); 39 | x+=1 40 | win=True 41 | for tup in winners: 42 | win=True 43 | for ix in tup: 44 | if brd[ix] != player: 45 | win=False 46 | break 47 | if win == True: 48 | break 49 | return win 50 | def make_move(brd, player, move, undo=False): 51 | if can_move(brd, player, move): 52 | brd[move-1] = player 53 | win=can_win(brd, player, move) 54 | if undo: 55 | brd[move-1] = move-1 56 | return (True, win) 57 | return (False, False) 58 | # AI goes here 59 | def computer_move(): 60 | move=-1 61 | # If I can win, others do not matter. 62 | for i in range(1,10): 63 | if make_move(board, computer, i, True)[1]: 64 | move=i 65 | break 66 | if move == -1: 67 | # If player can win, block him. 68 | for i in range(1,10): 69 | if make_move(board, player, i, True)[1]: 70 | move=i 71 | break 72 | if move == -1: 73 | # Otherwise, try to take one of desired places. 74 | for tup in moves: 75 | for mv in tup: 76 | if move == -1 and can_move(board, computer, mv): 77 | move=mv 78 | break 79 | return make_move(board, computer, move) 80 | def space_exist(): 81 | return board.count('X') + board.count('O') != 9 82 | player, computer = select_char() 83 | print('Player is [%s] and computer is [%s]' % (player, computer)) 84 | result='%%% Deuce ! %%%' 85 | while space_exist(): 86 | print_board() 87 | print('#Make your move ! [1-9] : ', end='') 88 | move = int(input()) 89 | moved, won = make_move(board, player, move) 90 | if not moved: 91 | print(' >> Invalid number ! Try again !') 92 | continue 93 | 94 | if won: 95 | result='*** Congratulations ! You won ! ***' 96 | break 97 | elif computer_move()[1]: 98 | result='=== You lose ! ==' 99 | break; 100 | print_board() 101 | print(result) -------------------------------------------------------------------------------- /begineerprojects/tipcalculator.py: -------------------------------------------------------------------------------- 1 | #Welcome message 2 | print("Welcome to the Tip Calculator.") 3 | #Gather inputs from the user 4 | bill = float(input("What was the total bill? ₹")) 5 | tip_percent = int(input("What percentage tip would you like to give? ")) 6 | people = int(input("How many people to split the bill? ")) 7 | #Calculate payment per person and use "{:.2f}".format() to round at 2 decimal places 8 | payment = "{:.2f}".format((bill * (1 + tip_percent / 100)) / people) 9 | #Print amount to pay per person 10 | print("Each person should pay ₹",payment) -------------------------------------------------------------------------------- /begineerprojects/treasureisland.py: -------------------------------------------------------------------------------- 1 | print(''' 2 | ******************************************************************************* 3 | | | | | 4 | _________|________________.=""_;=.______________|_____________________|_______ 5 | | | ,-"_,="" `"=.| | 6 | |___________________|__"=._o`"-._ `"=.______________|___________________ 7 | | `"=._o`"=._ _`"=._ | 8 | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______ 9 | | | __.--" , ; `"=._o." ,-"""-._ ". | 10 | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________ 11 | | |o`"=._` , "` `; .". , "-._"-._; ; | 12 | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______ 13 | | | |o; `"-.o`"=._`` '` " ,__.--o; | 14 | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________ 15 | ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____ 16 | /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_ 17 | ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____ 18 | /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_ 19 | ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____ 20 | /______/______/______/______/______/______/______/______/______/______/_____ / 21 | ******************************************************************************* 22 | ''') 23 | print("Welcome to Treasure Island.") 24 | print("Your mission is to find the treasure.") 25 | 26 | choice1 = input('You\'re at a cross road. Where do you want to go? Type "left" or "right" \n').lower() 27 | 28 | if choice1 == "left": 29 | choice2 = input('You\'ve come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across. \n').lower() 30 | 31 | if choice2 == "wait": 32 | choice3 = input("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose? \n").lower() 33 | 34 | if choice3 == "red": 35 | print("It's a room full of fire. Game Over.") 36 | elif choice3 == "yellow": 37 | print("You found the treasure! You Win!") 38 | elif choice3 == "blue": 39 | print("You enter a room of beasts. Game Over.") 40 | else: 41 | print("You chose a door that doesn't exist. Game Over.") 42 | else: 43 | print("You get attacked by an angry trout. Game Over.") 44 | else: 45 | print("You fell into a hole. Game Over.") 46 | -------------------------------------------------------------------------------- /begineerprojects/wordguessinggame.py: -------------------------------------------------------------------------------- 1 | import random 2 | # library that we use in order to choose 3 | # on random words from a list of words 4 | 5 | name = input("What is your name? ") 6 | # Here the user is asked to enter the name first 7 | 8 | print("Good Luck ! ", name) 9 | 10 | 11 | words = ['rainbow', 'computer', 'science', 'programming', 12 | 'python', 'mathematics', 'player', 'condition', 13 | 'reverse', 'water', 'board', 'geeks'] 14 | 15 | # Function will choose one random 16 | # word from this list of words 17 | word = random.choice(words) 18 | 19 | 20 | print("Guess the characters") 21 | 22 | guesses = '' 23 | 24 | # any number of turns can be used here 25 | turns = 12 26 | 27 | 28 | while turns > 0: 29 | 30 | # counts the number of times a user fails 31 | failed = 0 32 | 33 | # all characters from the input 34 | # word taking one at a time. 35 | for char in word: 36 | 37 | # comparing that character with 38 | # the character in guesses 39 | if char in guesses: 40 | print(char) 41 | 42 | else: 43 | print("_") 44 | 45 | # for every failure 1 will be 46 | # incremented in failure 47 | failed += 1 48 | 49 | 50 | if failed == 0: 51 | # user will win the game if failure is 0 52 | # and 'You Win' will be given as output 53 | print("You Win") 54 | 55 | # this print the correct word 56 | print("The word is: ", word) 57 | break 58 | 59 | # if user has input the wrong alphabet then 60 | # it will ask user to enter another alphabet 61 | guess = input("guess a character:") 62 | 63 | # every input character will be stored in guesses 64 | guesses += guess 65 | 66 | # check input with the character in word 67 | if guess not in word: 68 | 69 | turns -= 1 70 | 71 | # if the character doesn’t match the word 72 | # then “Wrong” will be given as output 73 | print("Wrong") 74 | 75 | # this will print the number of 76 | # turns left for the user 77 | print("You have", + turns, 'more guesses') 78 | 79 | 80 | if turns == 0: 81 | print("You Loose") 82 | -------------------------------------------------------------------------------- /guiprojects/agecalculator.py: -------------------------------------------------------------------------------- 1 | # import all functions from the tkinter 2 | from tkinter import * 3 | 4 | # import messagebox class from tkinter 5 | from tkinter import messagebox 6 | 7 | # Function for clearing the 8 | # contents of all text entry boxes 9 | def clearAll() : 10 | 11 | # deleting the content from the entry box 12 | dayField.delete(0, END) 13 | monthField.delete(0, END) 14 | yearField.delete(0, END) 15 | givenDayField.delete(0, END) 16 | givenMonthField.delete(0, END) 17 | givenYearField.delete(0, END) 18 | rsltDayField.delete(0, END) 19 | rsltMonthField.delete(0, END) 20 | rsltYearField.delete(0, END) 21 | 22 | # function for checking error 23 | def checkError() : 24 | 25 | # if any of the entry field is empty 26 | # then show an error message and clear 27 | # all the entries 28 | if (dayField.get() == "" or monthField.get() == "" 29 | or yearField.get() == "" or givenDayField.get() == "" 30 | or givenMonthField.get() == "" or givenYearField.get() == "") : 31 | 32 | # show the error message 33 | messagebox.showerror("Input Error") 34 | 35 | # clearAll function calling 36 | clearAll() 37 | 38 | return -1 39 | 40 | # function to calculate Age 41 | def calculateAge() : 42 | 43 | # check for error 44 | value = checkError() 45 | 46 | # if error is occur then return 47 | if value == -1 : 48 | return 49 | 50 | else : 51 | 52 | # take a value from the respective entry boxes 53 | # get method returns current text as string 54 | birth_day = int(dayField.get()) 55 | birth_month = int(monthField.get()) 56 | birth_year = int(yearField.get()) 57 | 58 | given_day = int(givenDayField.get()) 59 | given_month = int(givenMonthField.get()) 60 | given_year = int(givenYearField.get()) 61 | 62 | 63 | # if birth date is greater then given birth_month 64 | # then donot count this month and add 30 to the date so 65 | # as to subtract the date and get the remaining days 66 | month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 67 | 68 | if (birth_day > given_day): 69 | given_month = given_month - 1 70 | given_day = given_day + month[birth_month-1] 71 | 72 | 73 | # if birth month exceeds given month, then 74 | # donot count this year and add 12 to the 75 | # month so that we can subtract and find out 76 | # the difference 77 | if (birth_month > given_month): 78 | given_year = given_year - 1 79 | given_month = given_month + 12 80 | 81 | # calculate day, month, year 82 | calculated_day = given_day - birth_day; 83 | calculated_month = given_month - birth_month; 84 | calculated_year = given_year - birth_year; 85 | 86 | # calculated day, month, year write back 87 | # to the respective entry boxes 88 | 89 | # insert method inserting the 90 | # value in the text entry box. 91 | 92 | rsltDayField.insert(10, str(calculated_day)) 93 | rsltMonthField.insert(10, str(calculated_month)) 94 | rsltYearField.insert(10, str(calculated_year)) 95 | 96 | 97 | # Driver Code 98 | if __name__ == "__main__" : 99 | 100 | # Create a GUI window 101 | gui = Tk() 102 | 103 | # Set the background colour of GUI window 104 | gui.configure(background = "light green") 105 | 106 | # set the name of tkinter GUI window 107 | gui.title("Age Calculator") 108 | 109 | # Set the configuration of GUI window 110 | gui.geometry("525x260") 111 | 112 | # Create a Date Of Birth : label 113 | dob = Label(gui, text = "Date Of Birth", bg = "blue") 114 | 115 | # Create a Given Date : label 116 | givenDate = Label(gui, text = "Given Date", bg = "blue") 117 | 118 | # Create a Day : label 119 | day = Label(gui, text = "Day", bg = "light green") 120 | 121 | # Create a Month : label 122 | month = Label(gui, text = "Month", bg = "light green") 123 | 124 | # Create a Year : label 125 | year = Label(gui, text = "Year", bg = "light green") 126 | 127 | # Create a Given Day : label 128 | givenDay = Label(gui, text = "Given Day", bg = "light green") 129 | 130 | # Create a Given Month : label 131 | givenMonth = Label(gui, text = "Given Month", bg = "light green") 132 | 133 | # Create a Given Year : label 134 | givenYear = Label(gui, text = "Given Year", bg = "light green") 135 | 136 | # Create a Years : label 137 | rsltYear = Label(gui, text = "Years", bg = "light green") 138 | 139 | # Create a Months : label 140 | rsltMonth = Label(gui, text = "Months", bg = "light green") 141 | 142 | # Create a Days : label 143 | rsltDay = Label(gui, text = "Days", bg = "light green") 144 | 145 | # Create a Resultant Age Button and attached to calculateAge function 146 | resultantAge = Button(gui, text = "Resultant Age", fg = "Black", bg = "Red", command = calculateAge) 147 | 148 | # Create a Clear All Button and attached to clearAll function 149 | clearAllEntry = Button(gui, text = "Clear All", fg = "Black", bg = "Red", command = clearAll) 150 | 151 | # Create a text entry box for filling or typing the information. 152 | dayField = Entry(gui) 153 | monthField = Entry(gui) 154 | yearField = Entry(gui) 155 | 156 | givenDayField = Entry(gui) 157 | givenMonthField = Entry(gui) 158 | givenYearField = Entry(gui) 159 | 160 | rsltYearField = Entry(gui) 161 | rsltMonthField = Entry(gui) 162 | rsltDayField = Entry(gui) 163 | 164 | 165 | # grid method is used for placing 166 | # the widgets at respective positions 167 | # in table like structure . 168 | dob.grid(row = 0, column = 1) 169 | 170 | day.grid(row = 1, column = 0) 171 | dayField.grid(row = 1, column = 1) 172 | 173 | month.grid(row = 2, column = 0) 174 | monthField.grid(row = 2, column = 1) 175 | 176 | year.grid(row = 3, column = 0) 177 | yearField.grid(row = 3, column = 1) 178 | 179 | givenDate.grid(row = 0, column = 4) 180 | 181 | givenDay.grid(row = 1, column = 3) 182 | givenDayField.grid(row = 1, column = 4) 183 | 184 | givenMonth.grid(row = 2, column = 3) 185 | givenMonthField.grid(row = 2, column = 4) 186 | 187 | givenYear.grid(row = 3, column = 3) 188 | givenYearField.grid(row = 3, column = 4) 189 | 190 | resultantAge.grid(row = 4, column = 2) 191 | 192 | rsltYear.grid(row = 5, column = 2) 193 | rsltYearField.grid(row = 6, column = 2) 194 | 195 | rsltMonth.grid(row = 7, column = 2) 196 | rsltMonthField.grid(row = 8, column = 2) 197 | 198 | rsltDay.grid(row = 9, column = 2) 199 | rsltDayField.grid(row = 10, column = 2) 200 | 201 | clearAllEntry.grid(row = 12, column = 2) 202 | 203 | # Start the GUI 204 | gui.mainloop() 205 | -------------------------------------------------------------------------------- /guiprojects/calculator.py: -------------------------------------------------------------------------------- 1 | # Python program to create a simple GUI 2 | # calculator using Tkinter 3 | 4 | # import everything from tkinter module 5 | from tkinter import * 6 | 7 | # globally declare the expression variable 8 | expression = "" 9 | 10 | 11 | # Function to update expression 12 | # in the text entry box 13 | def press(num): 14 | # point out the global expression variable 15 | global expression 16 | 17 | # concatenation of string 18 | expression = expression + str(num) 19 | 20 | # update the expression by using set method 21 | equation.set(expression) 22 | 23 | 24 | # Function to evaluate the final expression 25 | def equalpress(): 26 | # Try and except statement is used 27 | # for handling the errors like zero 28 | # division error etc. 29 | 30 | # Put that code inside the try block 31 | # which may generate the error 32 | try: 33 | 34 | global expression 35 | 36 | # eval function evaluate the expression 37 | # and str function convert the result 38 | # into string 39 | total = str(eval(expression)) 40 | 41 | equation.set(total) 42 | 43 | # initialize the expression variable 44 | # by empty string 45 | expression = "" 46 | 47 | # if error is generate then handle 48 | # by the except block 49 | except: 50 | 51 | equation.set(" error ") 52 | expression = "" 53 | 54 | 55 | # Function to clear the contents 56 | # of text entry box 57 | def clear(): 58 | global expression 59 | expression = "" 60 | equation.set("") 61 | 62 | 63 | # Driver code 64 | if __name__ == "__main__": 65 | # create a GUI window 66 | gui = Tk() 67 | 68 | # set the background colour of GUI window 69 | gui.configure(background="light green") 70 | 71 | # set the title of GUI window 72 | gui.title("Simple Calculator") 73 | 74 | # set the configuration of GUI window 75 | gui.geometry("270x150") 76 | 77 | # StringVar() is the variable class 78 | # we create an instance of this class 79 | equation = StringVar() 80 | 81 | # create the text entry box for 82 | # showing the expression . 83 | expression_field = Entry(gui, textvariable=equation) 84 | 85 | # grid method is used for placing 86 | # the widgets at respective positions 87 | # in table like structure . 88 | expression_field.grid(columnspan=4, ipadx=70) 89 | 90 | # create a Buttons and place at a particular 91 | # location inside the root window . 92 | # when user press the button, the command or 93 | # function affiliated to that button is executed . 94 | button1 = Button(gui, text=' 1 ', fg='black', bg='red', 95 | command=lambda: press(1), height=1, width=7) 96 | button1.grid(row=2, column=0) 97 | 98 | button2 = Button(gui, text=' 2 ', fg='black', bg='red', 99 | command=lambda: press(2), height=1, width=7) 100 | button2.grid(row=2, column=1) 101 | 102 | button3 = Button(gui, text=' 3 ', fg='black', bg='red', 103 | command=lambda: press(3), height=1, width=7) 104 | button3.grid(row=2, column=2) 105 | 106 | button4 = Button(gui, text=' 4 ', fg='black', bg='red', 107 | command=lambda: press(4), height=1, width=7) 108 | button4.grid(row=3, column=0) 109 | 110 | button5 = Button(gui, text=' 5 ', fg='black', bg='red', 111 | command=lambda: press(5), height=1, width=7) 112 | button5.grid(row=3, column=1) 113 | 114 | button6 = Button(gui, text=' 6 ', fg='black', bg='red', 115 | command=lambda: press(6), height=1, width=7) 116 | button6.grid(row=3, column=2) 117 | 118 | button7 = Button(gui, text=' 7 ', fg='black', bg='red', 119 | command=lambda: press(7), height=1, width=7) 120 | button7.grid(row=4, column=0) 121 | 122 | button8 = Button(gui, text=' 8 ', fg='black', bg='red', 123 | command=lambda: press(8), height=1, width=7) 124 | button8.grid(row=4, column=1) 125 | 126 | button9 = Button(gui, text=' 9 ', fg='black', bg='red', 127 | command=lambda: press(9), height=1, width=7) 128 | button9.grid(row=4, column=2) 129 | 130 | button0 = Button(gui, text=' 0 ', fg='black', bg='red', 131 | command=lambda: press(0), height=1, width=7) 132 | button0.grid(row=5, column=0) 133 | 134 | plus = Button(gui, text=' + ', fg='black', bg='red', 135 | command=lambda: press("+"), height=1, width=7) 136 | plus.grid(row=2, column=3) 137 | 138 | minus = Button(gui, text=' - ', fg='black', bg='red', 139 | command=lambda: press("-"), height=1, width=7) 140 | minus.grid(row=3, column=3) 141 | 142 | multiply = Button(gui, text=' * ', fg='black', bg='red', 143 | command=lambda: press("*"), height=1, width=7) 144 | multiply.grid(row=4, column=3) 145 | 146 | divide = Button(gui, text=' / ', fg='black', bg='red', 147 | command=lambda: press("/"), height=1, width=7) 148 | divide.grid(row=5, column=3) 149 | 150 | equal = Button(gui, text=' = ', fg='black', bg='red', 151 | command=equalpress, height=1, width=7) 152 | equal.grid(row=5, column=2) 153 | 154 | clear = Button(gui, text='Clear', fg='black', bg='red', 155 | command=clear, height=1, width=7) 156 | clear.grid(row=5, column='1') 157 | 158 | Decimal= Button(gui, text='.', fg='black', bg='red', 159 | command=lambda: press('.'), height=1, width=7) 160 | Decimal.grid(row=6, column=0) 161 | # start the GUI 162 | gui.mainloop() 163 | -------------------------------------------------------------------------------- /guiprojects/calender.py: -------------------------------------------------------------------------------- 1 | # import all methods and classes from the tkinter 2 | from tkinter import * 3 | 4 | # import calendar module 5 | import calendar 6 | 7 | # Function for showing the calendar of the given year 8 | def showCal() : 9 | 10 | # Create a GUI window 11 | new_gui = Tk() 12 | 13 | # Set the background colour of GUI window 14 | new_gui.config(background = "white") 15 | 16 | # set the name of tkinter GUI window 17 | new_gui.title("CALENDAR") 18 | 19 | # Set the configuration of GUI window 20 | new_gui.geometry("550x600") 21 | 22 | # get method returns current text as string 23 | fetch_year = int(year_field.get()) 24 | 25 | # calendar method of calendar module return 26 | # the calendar of the given year . 27 | cal_content = calendar.calendar(fetch_year) 28 | 29 | # Create a label for showing the content of the calendar 30 | cal_year = Label(new_gui, text = cal_content, font = "Consolas 10 bold") 31 | 32 | # grid method is used for placing 33 | # the widgets at respective positions 34 | # in table like structure. 35 | cal_year.grid(row = 5, column = 1, padx = 20) 36 | 37 | # start the GUI 38 | new_gui.mainloop() 39 | 40 | 41 | # Driver Code 42 | if __name__ == "__main__" : 43 | 44 | # Create a GUI window 45 | gui = Tk() 46 | 47 | # Set the background colour of GUI window 48 | gui.config(background = "white") 49 | 50 | # set the name of tkinter GUI window 51 | gui.title("CALENDAR") 52 | 53 | # Set the configuration of GUI window 54 | gui.geometry("250x140") 55 | 56 | # Create a CALENDAR : label with specified font and size 57 | cal = Label(gui, text = "CALENDAR", bg = "dark gray", 58 | font = ("times", 28, 'bold')) 59 | 60 | # Create a Enter Year : label 61 | year = Label(gui, text = "Enter Year", bg = "light green") 62 | 63 | # Create a text entry box for filling or typing the information. 64 | year_field = Entry(gui) 65 | 66 | # Create a Show Calendar Button and attached to showCal function 67 | Show = Button(gui, text = "Show Calendar", fg = "Black", 68 | bg = "Red", command = showCal) 69 | 70 | # Create a Exit Button and attached to exit function 71 | Exit = Button(gui, text = "Exit", fg = "Black", bg = "Red", command = exit) 72 | 73 | # grid method is used for placing 74 | # the widgets at respective positions 75 | # in table like structure. 76 | cal.grid(row = 1, column = 1) 77 | 78 | year.grid(row = 2, column = 1) 79 | 80 | year_field.grid(row = 3, column = 1) 81 | 82 | Show.grid(row = 4, column = 1) 83 | 84 | Exit.grid(row = 6, column = 1) 85 | 86 | # start the GUI 87 | gui.mainloop() 88 | 89 | -------------------------------------------------------------------------------- /guiprojects/colorgame.py: -------------------------------------------------------------------------------- 1 | # import the modules 2 | import tkinter 3 | import random 4 | 5 | # list of possible colour. 6 | colours = ['Red','Blue','Green','Pink','Black', 7 | 'Yellow','Orange','White','Purple','Brown'] 8 | score = 0 9 | 10 | # the game time left, initially 30 seconds. 11 | timeleft = 30 12 | 13 | # function that will start the game. 14 | def startGame(event): 15 | 16 | if timeleft == 30: 17 | 18 | # start the countdown timer. 19 | countdown() 20 | 21 | # run the function to 22 | # choose the next colour. 23 | nextColour() 24 | 25 | # Function to choose and 26 | # display the next colour. 27 | def nextColour(): 28 | 29 | # use the globally declared 'score' 30 | # and 'play' variables above. 31 | global score 32 | global timeleft 33 | 34 | # if a game is currently in play 35 | if timeleft > 0: 36 | 37 | # make the text entry box active. 38 | e.focus_set() 39 | 40 | # if the colour typed is equal 41 | # to the colour of the text 42 | if e.get().lower() == colours[1].lower(): 43 | 44 | score += 1 45 | 46 | # clear the text entry box. 47 | e.delete(0, tkinter.END) 48 | 49 | random.shuffle(colours) 50 | 51 | # change the colour to type, by changing the 52 | # text _and_ the colour to a random colour value 53 | label.config(fg = str(colours[1]), text = str(colours[0])) 54 | 55 | # update the score. 56 | scoreLabel.config(text = "Score: " + str(score)) 57 | 58 | 59 | # Countdown timer function 60 | def countdown(): 61 | 62 | global timeleft 63 | 64 | # if a game is in play 65 | if timeleft > 0: 66 | 67 | # decrement the timer. 68 | timeleft -= 1 69 | 70 | # update the time left label 71 | timeLabel.config(text = "Time left: " 72 | + str(timeleft)) 73 | 74 | # run the function again after 1 second. 75 | timeLabel.after(1000, countdown) 76 | 77 | 78 | # Driver Code 79 | 80 | # create a GUI window 81 | root = tkinter.Tk() 82 | 83 | # set the title 84 | root.title("COLORGAME") 85 | 86 | # set the size 87 | root.geometry("375x200") 88 | 89 | # add an instructions label 90 | instructions = tkinter.Label(root, text = "Type in the colour" 91 | "of the words, and not the word text!", 92 | font = ('Helvetica', 12)) 93 | instructions.pack() 94 | 95 | # add a score label 96 | scoreLabel = tkinter.Label(root, text = "Press enter to start", 97 | font = ('Helvetica', 12)) 98 | scoreLabel.pack() 99 | 100 | # add a time left label 101 | timeLabel = tkinter.Label(root, text = "Time left: " + 102 | str(timeleft), font = ('Helvetica', 12)) 103 | 104 | timeLabel.pack() 105 | 106 | # add a label for displaying the colours 107 | label = tkinter.Label(root, font = ('Helvetica', 60)) 108 | label.pack() 109 | 110 | # add a text entry box for 111 | # typing in colours 112 | e = tkinter.Entry(root) 113 | 114 | # run the 'startGame' function 115 | # when the enter key is pressed 116 | root.bind('', startGame) 117 | e.pack() 118 | 119 | # set focus on the entry box 120 | e.focus_set() 121 | 122 | # start the GUI 123 | root.mainloop() 124 | -------------------------------------------------------------------------------- /guiprojects/guiform.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | fields = ('Annual Rate', 'Number of Payments', 'Loan Principle', 'Monthly Payment', 'Remaining Loan') 3 | def monthly_payment(entries): 4 | # period rate: 5 | r = (float(entries['Annual Rate'].get()) / 100) / 12 6 | print("r", r) 7 | # principal loan: 8 | loan = float(entries['Loan Principle'].get()) 9 | n = float(entries['Number of Payments'].get()) 10 | remaining_loan = float(entries['Remaining Loan'].get()) 11 | q = (1 + r)** n 12 | monthly = r * ( (q * loan - remaining_loan) / ( q - 1 )) 13 | monthly = ("%8.2f" % monthly).strip() 14 | entries['Monthly Payment'].delete(0,END) 15 | entries['Monthly Payment'].insert(0, monthly ) 16 | print("Monthly Payment: %f" % float(monthly)) 17 | def final_balance(entries): 18 | # period rate: 19 | r = (float(entries['Annual Rate'].get()) / 100) / 12 20 | print("r", r) 21 | # principal loan: 22 | loan = float(entries['Loan Principle'].get()) 23 | n = float(entries['Number of Payments'].get()) 24 | q = (1 + r)** n 25 | monthly = float(entries['Monthly Payment'].get()) 26 | q = (1 + r)** n 27 | remaining = q * loan - ( (q - 1) / r) * monthly 28 | remaining = ("%8.2f" % remaining).strip() 29 | entries['Remaining Loan'].delete(0,END) 30 | entries['Remaining Loan'].insert(0, remaining ) 31 | print("Remaining Loan: %f" % float(remaining)) 32 | def makeform(root, fields): 33 | entries = {} 34 | for field in fields: 35 | row = Frame(root) 36 | lab = Label(row, width=22, text=field+": ", anchor='w') 37 | ent = Entry(row) 38 | ent.insert(0,"0") 39 | row.pack(side = TOP, fill = X, padx = 5 , pady = 5) 40 | lab.pack(side = LEFT) 41 | ent.pack(side = RIGHT, expand = YES, fill = X) 42 | entries[field] = ent 43 | return entries 44 | if __name__ == '__main__': 45 | root = Tk() 46 | ents = makeform(root, fields) 47 | root.bind('', (lambda event, e = ents: fetch(e))) 48 | b1 = Button(root, text = 'Final Balance', 49 | command=(lambda e = ents: final_balance(e))) 50 | b1.pack(side = LEFT, padx = 5, pady = 5) 51 | b2 = Button(root, text='Monthly Payment', 52 | command=(lambda e = ents: monthly_payment(e))) 53 | b2.pack(side = LEFT, padx = 5, pady = 5) 54 | b3 = Button(root, text = 'Quit', command = root.quit) 55 | b3.pack(side = LEFT, padx = 5, pady = 5) 56 | root.mainloop() 57 | -------------------------------------------------------------------------------- /guiprojects/interestcalculator.py: -------------------------------------------------------------------------------- 1 | # import all classes / functions from the tkinter 2 | from tkinter import * 3 | 4 | # Function for clearing the 5 | # contents of all entry boxes 6 | def clear_all() : 7 | 8 | # whole content of entry boxes is deleted 9 | principle_field.delete(0, END) 10 | rate_field.delete(0, END) 11 | time_field.delete(0, END) 12 | compound_field.delete(0, END) 13 | 14 | # set focus on the principle_field entry box 15 | principle_field.focus_set() 16 | 17 | 18 | # Function to find compound interest 19 | def calculate_ci(): 20 | 21 | # get a content from entry box 22 | principle = int(principle_field.get()) 23 | 24 | rate = float(rate_field.get()) 25 | 26 | time = int(time_field.get()) 27 | 28 | # Calculates compound interest 29 | CI = principle * (pow((1 + rate / 100), time)) 30 | 31 | # insert method inserting the 32 | # value in the text entry box. 33 | compound_field.insert(10, CI) 34 | 35 | 36 | 37 | # Driver code 38 | if __name__ == "__main__" : 39 | 40 | # Create a GUI window 41 | root = Tk() 42 | 43 | # Set the background colour of GUI window 44 | root.configure(background = 'light green') 45 | 46 | # Set the configuration of GUI window 47 | root.geometry("400x250") 48 | 49 | # set the name of tkinter GUI window 50 | root.title("Compound Interest Calculator") 51 | 52 | # Create a Principle Amount : label 53 | label1 = Label(root, text = "Principle Amount(Rs) : ", 54 | fg = 'black', bg = 'red') 55 | 56 | # Create a Rate : label 57 | label2 = Label(root, text = "Rate(%) : ", 58 | fg = 'black', bg = 'red') 59 | 60 | # Create a Time : label 61 | label3 = Label(root, text = "Time(years) : ", 62 | fg = 'black', bg = 'red') 63 | 64 | # Create a Compound Interest : label 65 | label4 = Label(root, text = "Compound Interest : ", 66 | fg = 'black', bg = 'red') 67 | 68 | # grid method is used for placing 69 | # the widgets at respective positions 70 | # in table like structure . 71 | 72 | # padx keyword argument used to set padding along x-axis . 73 | # pady keyword argument used to set padding along y-axis . 74 | label1.grid(row = 1, column = 0, padx = 10, pady = 10) 75 | label2.grid(row = 2, column = 0, padx = 10, pady = 10) 76 | label3.grid(row = 3, column = 0, padx = 10, pady = 10) 77 | label4.grid(row = 5, column = 0, padx = 10, pady = 10) 78 | 79 | # Create a entry box 80 | # for filling or typing the information. 81 | principle_field = Entry(root) 82 | rate_field = Entry(root) 83 | time_field = Entry(root) 84 | compound_field = Entry(root) 85 | 86 | # grid method is used for placing 87 | # the widgets at respective positions 88 | # in table like structure . 89 | 90 | # padx keyword argument used to set padding along x-axis . 91 | # pady keyword argument used to set padding along y-axis . 92 | principle_field.grid(row = 1, column = 1, padx = 10, pady = 10) 93 | rate_field.grid(row = 2, column = 1, padx = 10, pady = 10) 94 | time_field.grid(row = 3, column = 1, padx = 10, pady = 10) 95 | compound_field.grid(row = 5, column = 1, padx = 10, pady = 10) 96 | 97 | # Create a Submit Button and attached 98 | # to calculate_ci function 99 | button1 = Button(root, text = "Submit", bg = "red", 100 | fg = "black", command = calculate_ci) 101 | 102 | # Create a Clear Button and attached 103 | # to clear_all function 104 | button2 = Button(root, text = "Clear", bg = "red", 105 | fg = "black", command = clear_all) 106 | 107 | button1.grid(row = 4, column = 1, pady = 10) 108 | button2.grid(row = 6, column = 1, pady = 10) 109 | 110 | # Start the GUI 111 | root.mainloop() 112 | 113 | 114 | -------------------------------------------------------------------------------- /guiprojects/loancalculator.py: -------------------------------------------------------------------------------- 1 | # Import tkinter 2 | from tkinter import * 3 | class LoanCalculator: 4 | 5 | def __init__(self): 6 | 7 | window = Tk() # Create a window 8 | window.title("Loan Calculator") # Set title 9 | # create the input boxes. 10 | Label(window, text = "Annual Interest Rate").grid(row = 1, 11 | column = 1, sticky = W) 12 | Label(window, text = "Number of Years").grid(row = 2, 13 | column = 1, sticky = W) 14 | Label(window, text = "Loan Amount").grid(row = 3, 15 | column = 1, sticky = W) 16 | Label(window, text = "Monthly Payment").grid(row = 4, 17 | column = 1, sticky = W) 18 | Label(window, text = "Total Payment").grid(row = 5, 19 | column = 1, sticky = W) 20 | 21 | # for taking inputs 22 | self.annualInterestRateVar = StringVar() 23 | Entry(window, textvariable = self.annualInterestRateVar, 24 | justify = RIGHT).grid(row = 1, column = 2) 25 | self.numberOfYearsVar = StringVar() 26 | 27 | Entry(window, textvariable = self.numberOfYearsVar, 28 | justify = RIGHT).grid(row = 2, column = 2) 29 | self.loanAmountVar = StringVar() 30 | 31 | Entry(window, textvariable = self.loanAmountVar, 32 | justify = RIGHT).grid(row = 3, column = 2) 33 | self.monthlyPaymentVar = StringVar() 34 | lblMonthlyPayment = Label(window, textvariable = 35 | self.monthlyPaymentVar).grid(row = 4, 36 | column = 2, sticky = E) 37 | 38 | self.totalPaymentVar = StringVar() 39 | lblTotalPayment = Label(window, textvariable = 40 | self.totalPaymentVar).grid(row = 5, 41 | column = 2, sticky = E) 42 | 43 | # create the button 44 | btComputePayment = Button(window, text = "Compute Payment", 45 | command = self.computePayment).grid( 46 | row = 6, column = 2, sticky = E) 47 | window.mainloop() # Create an event loop 48 | 49 | 50 | # compute the total payment. 51 | def computePayment(self): 52 | 53 | monthlyPayment = self.getMonthlyPayment( 54 | float(self.loanAmountVar.get()), 55 | float(self.annualInterestRateVar.get()) / 1200, 56 | int(self.numberOfYearsVar.get())) 57 | 58 | self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f')) 59 | totalPayment = float(self.monthlyPaymentVar.get()) * 12 \ 60 | * int(self.numberOfYearsVar.get()) 61 | 62 | self.totalPaymentVar.set(format(totalPayment, '10.2f')) 63 | 64 | def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears): 65 | # compute the monthly payment. 66 | monthlyPayment = loanAmount * monthlyInterestRate / (1 67 | - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12)) 68 | return monthlyPayment; 69 | root = Tk() # create the widget 70 | 71 | # call the class to run the program. 72 | LoanCalculator() 73 | -------------------------------------------------------------------------------- /guiprojects/notepad.py: -------------------------------------------------------------------------------- 1 | import tkinter 2 | import os 3 | from tkinter import * 4 | from tkinter.messagebox import * 5 | from tkinter.filedialog import * 6 | 7 | class Notepad: 8 | 9 | __root = Tk() 10 | 11 | # default window width and height 12 | __thisWidth = 300 13 | __thisHeight = 300 14 | __thisTextArea = Text(__root) 15 | __thisMenuBar = Menu(__root) 16 | __thisFileMenu = Menu(__thisMenuBar, tearoff=0) 17 | __thisEditMenu = Menu(__thisMenuBar, tearoff=0) 18 | __thisHelpMenu = Menu(__thisMenuBar, tearoff=0) 19 | 20 | # To add scrollbar 21 | __thisScrollBar = Scrollbar(__thisTextArea) 22 | __file = None 23 | 24 | def __init__(self,**kwargs): 25 | 26 | # Set icon 27 | try: 28 | self.__root.wm_iconbitmap("Notepad.ico") 29 | except: 30 | pass 31 | 32 | # Set window size (the default is 300x300) 33 | 34 | try: 35 | self.__thisWidth = kwargs['width'] 36 | except KeyError: 37 | pass 38 | 39 | try: 40 | self.__thisHeight = kwargs['height'] 41 | except KeyError: 42 | pass 43 | 44 | # Set the window text 45 | self.__root.title("Untitled - Notepad") 46 | 47 | # Center the window 48 | screenWidth = self.__root.winfo_screenwidth() 49 | screenHeight = self.__root.winfo_screenheight() 50 | 51 | # For left-align 52 | left = (screenWidth / 2) - (self.__thisWidth / 2) 53 | 54 | # For right-align 55 | top = (screenHeight / 2) - (self.__thisHeight /2) 56 | 57 | # For top and bottom 58 | self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth, 59 | self.__thisHeight, 60 | left, top)) 61 | 62 | # To make the textarea auto resizable 63 | self.__root.grid_rowconfigure(0, weight=1) 64 | self.__root.grid_columnconfigure(0, weight=1) 65 | 66 | # Add controls (widget) 67 | self.__thisTextArea.grid(sticky = N + E + S + W) 68 | 69 | # To open new file 70 | self.__thisFileMenu.add_command(label="New", 71 | command=self.__newFile) 72 | 73 | # To open a already existing file 74 | self.__thisFileMenu.add_command(label="Open", 75 | command=self.__openFile) 76 | 77 | # To save current file 78 | self.__thisFileMenu.add_command(label="Save", 79 | command=self.__saveFile) 80 | 81 | # To create a line in the dialog 82 | self.__thisFileMenu.add_separator() 83 | self.__thisFileMenu.add_command(label="Exit", 84 | command=self.__quitApplication) 85 | self.__thisMenuBar.add_cascade(label="File", 86 | menu=self.__thisFileMenu) 87 | 88 | # To give a feature of cut 89 | self.__thisEditMenu.add_command(label="Cut", 90 | command=self.__cut) 91 | 92 | # to give a feature of copy 93 | self.__thisEditMenu.add_command(label="Copy", 94 | command=self.__copy) 95 | 96 | # To give a feature of paste 97 | self.__thisEditMenu.add_command(label="Paste", 98 | command=self.__paste) 99 | 100 | # To give a feature of editing 101 | self.__thisMenuBar.add_cascade(label="Edit", 102 | menu=self.__thisEditMenu) 103 | 104 | # To create a feature of description of the notepad 105 | self.__thisHelpMenu.add_command(label="About Notepad", 106 | command=self.__showAbout) 107 | self.__thisMenuBar.add_cascade(label="Help", 108 | menu=self.__thisHelpMenu) 109 | 110 | self.__root.config(menu=self.__thisMenuBar) 111 | 112 | self.__thisScrollBar.pack(side=RIGHT,fill=Y) 113 | 114 | # Scrollbar will adjust automatically according to the content 115 | self.__thisScrollBar.config(command=self.__thisTextArea.yview) 116 | self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set) 117 | 118 | 119 | def __quitApplication(self): 120 | self.__root.destroy() 121 | # exit() 122 | 123 | def __showAbout(self): 124 | showinfo("Notepad","you can edit your file here") 125 | 126 | def __openFile(self): 127 | 128 | self.__file = askopenfilename(defaultextension=".txt", 129 | filetypes=[("All Files","*.*"), 130 | ("Text Documents","*.txt")]) 131 | 132 | if self.__file == "": 133 | 134 | # no file to open 135 | self.__file = None 136 | else: 137 | 138 | # Try to open the file 139 | # set the window title 140 | self.__root.title(os.path.basename(self.__file) + " - Notepad") 141 | self.__thisTextArea.delete(1.0,END) 142 | 143 | file = open(self.__file,"r") 144 | 145 | self.__thisTextArea.insert(1.0,file.read()) 146 | 147 | file.close() 148 | 149 | 150 | def __newFile(self): 151 | self.__root.title("Untitled - Notepad") 152 | self.__file = None 153 | self.__thisTextArea.delete(1.0,END) 154 | 155 | def __saveFile(self): 156 | 157 | if self.__file == None: 158 | # Save as new file 159 | self.__file = asksaveasfilename(initialfile='Untitled.txt', 160 | defaultextension=".txt", 161 | filetypes=[("All Files","*.*"), 162 | ("Text Documents","*.txt")]) 163 | 164 | if self.__file == "": 165 | self.__file = None 166 | else: 167 | 168 | # Try to save the file 169 | file = open(self.__file,"w") 170 | file.write(self.__thisTextArea.get(1.0,END)) 171 | file.close() 172 | 173 | # Change the window title 174 | self.__root.title(os.path.basename(self.__file) + " - Notepad") 175 | 176 | 177 | else: 178 | file = open(self.__file,"w") 179 | file.write(self.__thisTextArea.get(1.0,END)) 180 | file.close() 181 | 182 | def __cut(self): 183 | self.__thisTextArea.event_generate("<>") 184 | 185 | def __copy(self): 186 | self.__thisTextArea.event_generate("<>") 187 | 188 | def __paste(self): 189 | self.__thisTextArea.event_generate("<>") 190 | 191 | def run(self): 192 | 193 | # Run main application 194 | self.__root.mainloop() 195 | 196 | 197 | 198 | 199 | # Run main application 200 | notepad = Notepad(width=600,height=400) 201 | notepad.run() 202 | 203 | -------------------------------------------------------------------------------- /guiprojects/spellcorrector.py: -------------------------------------------------------------------------------- 1 | # import all functions / classes from the tkinter 2 | from tkinter import * 3 | from textblob import TextBlob 4 | 5 | # Function to clear both the text entry boxes 6 | def clearAll() : 7 | 8 | # whole content of text entry area is deleted 9 | word1_field.delete(0, END) 10 | word2_field.delete(0, END) 11 | 12 | # Function to get a corrected word 13 | def correction() : 14 | 15 | # get a content from entry box 16 | input_word = word1_field.get() 17 | 18 | # create a TextBlob object 19 | blob_obj = TextBlob(input_word) 20 | 21 | # get a corrected word 22 | corrected_word = str(blob_obj.correct()) 23 | 24 | # insert method inserting the 25 | # value in the text entry box. 26 | word2_field.insert(10, corrected_word) 27 | 28 | 29 | # Driver code 30 | if __name__ == "__main__" : 31 | 32 | # Create a GUI window 33 | root = Tk() 34 | 35 | # Set the background colour of GUI window 36 | root.configure(background = 'light green') 37 | 38 | # Set the configuration of GUI window (WidthxHeight) 39 | root.geometry("400x150") 40 | 41 | # set the name of tkinter GUI window 42 | root.title("Spell Corrector") 43 | 44 | # Create Welcome to Spell Corrector Application: label 45 | headlabel = Label(root, text = 'Welcome to Spell Corrector Application', 46 | fg = 'black', bg = "red") 47 | 48 | # Create a "Input Word": label 49 | label1 = Label(root, text = "Input Word", 50 | fg = 'black', bg = 'dark green') 51 | 52 | # Create a "Corrected Word": label 53 | label2 = Label(root, text = "Corrected Word", 54 | fg = 'black', bg = 'dark green') 55 | 56 | 57 | # grid method is used for placing 58 | # the widgets at respective positions 59 | # in table like structure . 60 | # padx keyword argument used to set padding along x-axis . 61 | headlabel.grid(row = 0, column = 1) 62 | label1.grid(row = 1, column = 0) 63 | label2.grid(row = 3, column = 0, padx = 10) 64 | 65 | 66 | # Create a text entry box 67 | # for filling or typing the information. 68 | word1_field = Entry() 69 | word2_field = Entry() 70 | 71 | # padx keyword argument used to set padding along x-axis . 72 | # pady keyword argument used to set padding along y-axis . 73 | word1_field.grid(row = 1, column = 1, padx = 10, pady = 10) 74 | word2_field.grid(row = 3, column = 1, padx = 10, pady = 10) 75 | 76 | 77 | # Create a Correction Button and attached 78 | # with correction function 79 | button1 = Button(root, text = "Correction", bg = "red", fg = "black", 80 | command = correction) 81 | 82 | button1.grid(row = 2, column = 1) 83 | 84 | # Create a Clear Button and attached 85 | # with clearAll function 86 | button2 = Button(root, text = "Clear", bg = "red", 87 | fg = "black", command = clearAll) 88 | 89 | button2.grid(row = 4, column = 1) 90 | 91 | # Start the GUI 92 | root.mainloop() 93 | -------------------------------------------------------------------------------- /guiprojects/switchpages.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import ttk 3 | 4 | 5 | LARGEFONT =("Verdana", 35) 6 | 7 | class tkinterApp(tk.Tk): 8 | 9 | # __init__ function for class tkinterApp 10 | def __init__(self, *args, **kwargs): 11 | 12 | # __init__ function for class Tk 13 | tk.Tk.__init__(self, *args, **kwargs) 14 | 15 | # creating a container 16 | container = tk.Frame(self) 17 | container.pack(side = "top", fill = "both", expand = True) 18 | 19 | container.grid_rowconfigure(0, weight = 1) 20 | container.grid_columnconfigure(0, weight = 1) 21 | 22 | # initializing frames to an empty array 23 | self.frames = {} 24 | 25 | # iterating through a tuple consisting 26 | # of the different page layouts 27 | for F in (StartPage, Page1, Page2): 28 | 29 | frame = F(container, self) 30 | 31 | # initializing frame of that object from 32 | # startpage, page1, page2 respectively with 33 | # for loop 34 | self.frames[F] = frame 35 | 36 | frame.grid(row = 0, column = 0, sticky ="nsew") 37 | 38 | self.show_frame(StartPage) 39 | 40 | # to display the current frame passed as 41 | # parameter 42 | def show_frame(self, cont): 43 | frame = self.frames[cont] 44 | frame.tkraise() 45 | 46 | # first window frame startpage 47 | 48 | class StartPage(tk.Frame): 49 | def __init__(self, parent, controller): 50 | tk.Frame.__init__(self, parent) 51 | 52 | # label of frame Layout 2 53 | label = ttk.Label(self, text ="Startpage", font = LARGEFONT) 54 | 55 | # putting the grid in its place by using 56 | # grid 57 | label.grid(row = 0, column = 4, padx = 10, pady = 10) 58 | 59 | button1 = ttk.Button(self, text ="Page 1", 60 | command = lambda : controller.show_frame(Page1)) 61 | 62 | # putting the button in its place by 63 | # using grid 64 | button1.grid(row = 1, column = 1, padx = 10, pady = 10) 65 | 66 | ## button to show frame 2 with text layout2 67 | button2 = ttk.Button(self, text ="Page 2", 68 | command = lambda : controller.show_frame(Page2)) 69 | 70 | # putting the button in its place by 71 | # using grid 72 | button2.grid(row = 2, column = 1, padx = 10, pady = 10) 73 | 74 | 75 | 76 | 77 | # second window frame page1 78 | class Page1(tk.Frame): 79 | 80 | def __init__(self, parent, controller): 81 | 82 | tk.Frame.__init__(self, parent) 83 | label = ttk.Label(self, text ="Page 1", font = LARGEFONT) 84 | label.grid(row = 0, column = 4, padx = 10, pady = 10) 85 | 86 | # button to show frame 2 with text 87 | # layout2 88 | button1 = ttk.Button(self, text ="StartPage", 89 | command = lambda : controller.show_frame(StartPage)) 90 | 91 | # putting the button in its place 92 | # by using grid 93 | button1.grid(row = 1, column = 1, padx = 10, pady = 10) 94 | 95 | # button to show frame 2 with text 96 | # layout2 97 | button2 = ttk.Button(self, text ="Page 2", 98 | command = lambda : controller.show_frame(Page2)) 99 | 100 | # putting the button in its place by 101 | # using grid 102 | button2.grid(row = 2, column = 1, padx = 10, pady = 10) 103 | 104 | 105 | 106 | 107 | # third window frame page2 108 | class Page2(tk.Frame): 109 | def __init__(self, parent, controller): 110 | tk.Frame.__init__(self, parent) 111 | label = ttk.Label(self, text ="Page 2", font = LARGEFONT) 112 | label.grid(row = 0, column = 4, padx = 10, pady = 10) 113 | 114 | # button to show frame 2 with text 115 | # layout2 116 | button1 = ttk.Button(self, text ="Page 1", 117 | command = lambda : controller.show_frame(Page1)) 118 | 119 | # putting the button in its place by 120 | # using grid 121 | button1.grid(row = 1, column = 1, padx = 10, pady = 10) 122 | 123 | # button to show frame 3 with text 124 | # layout3 125 | button2 = ttk.Button(self, text ="Startpage", 126 | command = lambda : controller.show_frame(StartPage)) 127 | 128 | # putting the button in its place by 129 | # using grid 130 | button2.grid(row = 2, column = 1, padx = 10, pady = 10) 131 | 132 | 133 | # Driver Code 134 | app = tkinterApp() 135 | app.mainloop() 136 | -------------------------------------------------------------------------------- /guiprojects/textdetection.py: -------------------------------------------------------------------------------- 1 | import time 2 | import pandas as pd 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | from tkinter import * 6 | import tkinter.messagebox 7 | from nltk.sentiment.vader import SentimentIntensityAnalyzer 8 | 9 | 10 | class analysis_text(): 11 | 12 | # Main function in program 13 | def center(self, toplevel): 14 | 15 | toplevel.update_idletasks() 16 | w = toplevel.winfo_screenwidth() 17 | h = toplevel.winfo_screenheight() 18 | size = tuple(int(_) for _ in 19 | toplevel.geometry().split('+')[0].split('x')) 20 | 21 | x = w/2 - size[0]/2 22 | y = h/2 - size[1]/2 23 | toplevel.geometry("%dx%d+%d+%d" % (size + (x, y))) 24 | 25 | def callback(self): 26 | if tkinter.messagebox.askokcancel("Quit", 27 | "Do you want to leave?"): 28 | self.main.destroy() 29 | 30 | def setResult(self, type, res): 31 | 32 | #calculated comments in vader analysis 33 | if (type == "neg"): 34 | self.negativeLabel.configure(text = 35 | "you typed negative comment : " 36 | + str(res) + " % \n") 37 | elif (type == "neu"): 38 | self.neutralLabel.configure( text = 39 | "you typed comment : " 40 | + str(res) + " % \n") 41 | elif (type == "pos"): 42 | self.positiveLabel.configure(text 43 | = "you typed positive comment: " 44 | + str(res) + " % \n") 45 | 46 | 47 | def runAnalysis(self): 48 | 49 | sentences = [] 50 | sentences.append(self.line.get()) 51 | sid = SentimentIntensityAnalyzer() 52 | 53 | for sentence in sentences: 54 | 55 | # print(sentence) 56 | ss = sid.polarity_scores(sentence) 57 | 58 | if ss['compound'] >= 0.05 : 59 | self.normalLabel.configure(text = 60 | " you typed positive statement: ") 61 | 62 | elif ss['compound'] <= - 0.05 : 63 | self.normalLabel.configure(text = 64 | " you typed negative statement") 65 | 66 | else : 67 | self.normalLabel.configure(text = 68 | " you normal typed statement: ") 69 | for k in sorted(ss): 70 | self.setResult(k, ss[k]) 71 | print() 72 | 73 | 74 | def editedText(self, event): 75 | self.typedText.configure(text = self.line.get() + event.char) 76 | 77 | 78 | def runByEnter(self, event): 79 | self.runAnalysis() 80 | 81 | 82 | def __init__(self): 83 | # Create main window 84 | self.main = Tk() 85 | self.main.title("Text Detector system") 86 | self.main.geometry("600x600") 87 | self.main.resizable(width=FALSE, height=FALSE) 88 | self.main.protocol("WM_DELETE_WINDOW", self.callback) 89 | self.main.focus() 90 | self.center(self.main) 91 | 92 | # addition item on window 93 | self.label1 = Label(text = "type a text here :") 94 | self.label1.pack() 95 | 96 | # Add a hidden button Enter 97 | self.line = Entry(self.main, width=70) 98 | self.line.pack() 99 | 100 | self.textLabel = Label(text = "\n", 101 | font=("Helvetica", 15)) 102 | self.textLabel.pack() 103 | self.typedText = Label(text = "", 104 | fg = "blue", 105 | font=("Helvetica", 20)) 106 | self.typedText.pack() 107 | 108 | self.line.bind("",self.editedText) 109 | self.line.bind("",self.runByEnter) 110 | 111 | 112 | self.result = Label(text = "\n", 113 | font=("Helvetica", 15)) 114 | self.result.pack() 115 | self.negativeLabel = Label(text = "", 116 | fg = "red", 117 | font=("Helvetica", 20)) 118 | self.negativeLabel.pack() 119 | self.neutralLabel = Label(text = "", 120 | font=("Helvetica", 20)) 121 | self.neutralLabel.pack() 122 | self.positiveLabel = Label(text = "", 123 | fg = "green", 124 | font=("Helvetica", 20)) 125 | self.positiveLabel.pack() 126 | self.normalLabel =Label (text ="", 127 | fg ="red", 128 | font=("Helvetica", 20)) 129 | self.normalLabel.pack() 130 | 131 | # Driver code 132 | myanalysis = analysis_text() 133 | mainloop() 134 | -------------------------------------------------------------------------------- /guiprojects/weightconversion.py: -------------------------------------------------------------------------------- 1 | # Python program to create a simple GUI 2 | # weight converter using Tkinter 3 | 4 | 5 | from tkinter import * 6 | 7 | 8 | # Create a GUI window 9 | window = Tk() 10 | 11 | # Function to convert weight 12 | # given in kg to grams, pounds 13 | # and ounces 14 | def from_kg(): 15 | 16 | # convert kg to gram 17 | gram = float(e2_value.get())*1000 18 | 19 | # convert kg to pound 20 | pound = float(e2_value.get())*2.20462 21 | 22 | # convert kg to ounce 23 | ounce = float(e2_value.get())*35.274 24 | 25 | # Enters the converted weight to 26 | # the text widget 27 | t1.delete("1.0", END) 28 | t1.insert(END,gram) 29 | 30 | t2.delete("1.0", END) 31 | t2.insert(END,pound) 32 | 33 | t3.delete("1.0", END) 34 | t3.insert(END,ounce) 35 | 36 | # Create the Label widgets 37 | e1 = Label(window, text = "Enter the weight in Kg") 38 | e2_value = StringVar() 39 | e2 = Entry(window, textvariable = e2_value) 40 | e3 = Label(window, text = 'Gram') 41 | e4 = Label(window, text = 'Pounds') 42 | e5 = Label(window, text = 'Ounce') 43 | 44 | # Create the Text Widgets 45 | t1 = Text(window, height = 1, width = 20) 46 | t2 = Text(window, height = 1, width = 20) 47 | t3 = Text(window, height = 1, width = 20) 48 | 49 | # Create the Button Widget 50 | b1 = Button(window, text = "Convert", command = from_kg) 51 | 52 | # grid method is used for placing 53 | # the widgets at respective positions 54 | # in table like structure 55 | e1.grid(row = 0, column = 0) 56 | e2.grid(row = 0, column = 1) 57 | e3.grid(row = 1, column = 0) 58 | e4.grid(row = 1, column = 1) 59 | e5.grid(row = 1, column = 2) 60 | t1.grid(row = 2, column = 0) 61 | t2.grid(row = 2, column = 1) 62 | t3.grid(row = 2, column = 2) 63 | b1.grid(row = 0, column = 2) 64 | 65 | # Start the GUI 66 | window.mainloop() 67 | -------------------------------------------------------------------------------- /guiprojects/youtubedownloader.py: -------------------------------------------------------------------------------- 1 | # Importing necessary packages 2 | import tkinter as tk 3 | from tkinter import * 4 | from pytube import YouTube 5 | from tkinter import messagebox, filedialog 6 | 7 | 8 | # Defining CreateWidgets() function 9 | # to create necessary tkinter widgets 10 | def Widgets(): 11 | 12 | head_label = Label(root, text="YouTube Video Downloader Using Tkinter", 13 | padx=15, 14 | pady=15, 15 | font="SegoeUI 14", 16 | bg="palegreen1", 17 | fg="red") 18 | head_label.grid(row=1, 19 | column=1, 20 | pady=10, 21 | padx=5, 22 | columnspan=3) 23 | 24 | link_label = Label(root, 25 | text="YouTube link :", 26 | bg="salmon", 27 | pady=5, 28 | padx=5) 29 | link_label.grid(row=2, 30 | column=0, 31 | pady=5, 32 | padx=5) 33 | 34 | root.linkText = Entry(root, 35 | width=35, 36 | textvariable=video_Link, 37 | font="Arial 14") 38 | root.linkText.grid(row=2, 39 | column=1, 40 | pady=5, 41 | padx=5, 42 | columnspan=2) 43 | 44 | 45 | destination_label = Label(root, 46 | text="Destination :", 47 | bg="salmon", 48 | pady=5, 49 | padx=9) 50 | destination_label.grid(row=3, 51 | column=0, 52 | pady=5, 53 | padx=5) 54 | 55 | 56 | root.destinationText = Entry(root, 57 | width=27, 58 | textvariable=download_Path, 59 | font="Arial 14") 60 | root.destinationText.grid(row=3, 61 | column=1, 62 | pady=5, 63 | padx=5) 64 | 65 | 66 | browse_B = Button(root, 67 | text="Browse", 68 | command=Browse, 69 | width=10, 70 | bg="bisque", 71 | relief=GROOVE) 72 | browse_B.grid(row=3, 73 | column=2, 74 | pady=1, 75 | padx=1) 76 | 77 | Download_B = Button(root, 78 | text="Download Video", 79 | command=Download, 80 | width=20, 81 | bg="thistle1", 82 | pady=10, 83 | padx=15, 84 | relief=GROOVE, 85 | font="Georgia, 13") 86 | Download_B.grid(row=4, 87 | column=1, 88 | pady=20, 89 | padx=20) 90 | 91 | 92 | # Defining Browse() to select a 93 | # destination folder to save the video 94 | 95 | def Browse(): 96 | # Presenting user with a pop-up for 97 | # directory selection. initialdir 98 | # argument is optional Retrieving the 99 | # user-input destination directory and 100 | # storing it in downloadDirectory 101 | download_Directory = filedialog.askdirectory( 102 | initialdir="YOUR DIRECTORY PATH", title="Save Video") 103 | 104 | # Displaying the directory in the directory 105 | # textbox 106 | download_Path.set(download_Directory) 107 | 108 | # Defining Download() to download the video 109 | 110 | 111 | def Download(): 112 | 113 | # getting user-input Youtube Link 114 | Youtube_link = video_Link.get() 115 | 116 | # select the optimal location for 117 | # saving file's 118 | download_Folder = download_Path.get() 119 | 120 | # Creating object of YouTube() 121 | getVideo = YouTube(Youtube_link) 122 | 123 | # Getting all the available streams of the 124 | # youtube video and selecting the first 125 | # from the 126 | videoStream = getVideo.streams.first() 127 | 128 | # Downloading the video to destination 129 | # directory 130 | videoStream.download(download_Folder) 131 | 132 | # Displaying the message 133 | messagebox.showinfo("SUCCESSFULLY", 134 | "DOWNLOADED AND SAVED IN\n" 135 | + download_Folder) 136 | 137 | 138 | # Creating object of tk class 139 | root = tk.Tk() 140 | 141 | # Setting the title, background color 142 | # and size of the tkinter window and 143 | # disabling the resizing property 144 | root.geometry("520x280") 145 | root.resizable(False, False) 146 | root.title("YouTube Video Downloader") 147 | root.config(background="PaleGreen1") 148 | 149 | # Creating the tkinter Variables 150 | video_Link = StringVar() 151 | download_Path = StringVar() 152 | 153 | # Calling the Widgets() function 154 | Widgets() 155 | 156 | # Defining infinite loop to run 157 | # application 158 | root.mainloop() 159 | -------------------------------------------------------------------------------- /intermediateprojects/bubblesortvisualizer.py: -------------------------------------------------------------------------------- 1 | # importing pygame 2 | import pygame 3 | 4 | pygame.init() 5 | 6 | # setting window size 7 | win = pygame.display.set_mode((500, 400)) 8 | 9 | # setting title to the window 10 | pygame.display.set_caption("Bubble sort") 11 | 12 | # initial position 13 | x = 40 14 | y = 40 15 | 16 | # width of each bar 17 | width = 20 18 | 19 | # height of each bar (data to be sorted) 20 | height = [200, 50, 130, 90, 250, 61, 110, 21 | 88, 33, 80, 70, 159, 180, 20] 22 | 23 | run = True 24 | 25 | # method to show the list of height 26 | def show(height): 27 | 28 | # loop to iterate each item of list 29 | for i in range(len(height)): 30 | 31 | # drawing each bar with respective gap 32 | pygame.draw.rect(win, (255, 0, 0), (x + 30 * i, y, width, height[i])) 33 | 34 | # infinite loop 35 | while run: 36 | 37 | # execute flag to start sorting 38 | execute = False 39 | 40 | # time delay 41 | pygame.time.delay(10) 42 | 43 | # getting keys pressed 44 | keys = pygame.key.get_pressed() 45 | 46 | # iterating events 47 | for event in pygame.event.get(): 48 | 49 | # if event is to quit 50 | if event.type == pygame.QUIT: 51 | 52 | # making run = false so break the while loop 53 | run = False 54 | 55 | # if space bar is pressed 56 | if keys[pygame.K_SPACE]: 57 | # make execute flag to true 58 | execute = True 59 | 60 | # checking if execute flag is false 61 | if execute == False: 62 | 63 | # fill the window with black color 64 | win.fill((0, 0, 0)) 65 | 66 | # call the height method to show the list items 67 | show(height) 68 | 69 | # update the window 70 | pygame.display.update() 71 | 72 | # if execute flag is true 73 | else: 74 | 75 | # start sorting using bubble sort technique 76 | for i in range(len(height) - 1): 77 | 78 | # after this iteration max element will come at last 79 | for j in range(len(height) - i - 1): 80 | 81 | # starting is greater then next element 82 | if height[j] > height[j + 1]: 83 | 84 | # save it in temporary variable 85 | # and swap them using temporary variable 86 | t = height[j] 87 | height[j] = height[j + 1] 88 | height[j + 1] = t 89 | 90 | # fill the window with black color 91 | win.fill((0, 0, 0)) 92 | 93 | # call show method to display the list items 94 | show(height) 95 | 96 | # create a time delay 97 | pygame.time.delay(50) 98 | 99 | # update the display 100 | pygame.display.update() 101 | 102 | # exiting the main window 103 | pygame.quit() -------------------------------------------------------------------------------- /intermediateprojects/rotatescreen.py: -------------------------------------------------------------------------------- 1 | import rotatescreen 2 | import keyboard 3 | 4 | screen = rotatescreen.get_primary_display() 5 | 6 | keyboard.add_hotkey('ctrl+alt+up', screen.set_landscape, suppress=True) 7 | keyboard.add_hotkey('ctrl+alt+right', screen.set_portrait_flipped, suppress=True) 8 | keyboard.add_hotkey('ctrl+alt+down', screen.set_landscape_flipped, suppress=True) 9 | keyboard.add_hotkey('ctrl+alt+left', screen.set_portrait, suppress=True) 10 | 11 | keyboard.wait() -------------------------------------------------------------------------------- /intermediateprojects/weatherreport.py: -------------------------------------------------------------------------------- 1 | # import required libraries 2 | import requests 3 | from bs4 import BeautifulSoup 4 | from win10toast import ToastNotifier 5 | 6 | # create an object to ToastNotifier class 7 | n = ToastNotifier() 8 | 9 | # define a function 10 | def getdata(url): 11 | r = requests.get(url) 12 | return r.text 13 | 14 | htmldata = getdata("https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/") 15 | 16 | soup = BeautifulSoup(htmldata, 'html.parser') 17 | 18 | current_temp = soup.find_all("span", class_= "_-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY") 19 | 20 | chances_rain = soup.find_all("div", class_= "_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf") 21 | 22 | temp = (str(current_temp)) 23 | 24 | temp_rain = str(chances_rain) 25 | 26 | result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" + temp_rain[131:-14] 27 | n.show_toast("live Weather update", 28 | result, duration = 10) 29 | -------------------------------------------------------------------------------- /intermediateprojects/websiteblocker.py: -------------------------------------------------------------------------------- 1 | # Run this script as root 2 | 3 | import time 4 | from datetime import datetime as dt 5 | 6 | # change hosts path according to your OS 7 | hosts_path = "/etc/hosts" 8 | # localhost's IP 9 | redirect = "127.0.0.1" 10 | 11 | # websites That you want to block 12 | website_list = ["www.facebook.com","facebook.com","dub119.mail.live.com","www.dub119.mail.live.com","www.gmail.com","gmail.com"] 13 | 14 | while True: 15 | 16 | # time of your work 17 | if dt(dt.now().year, dt.now().month, dt.now().day,8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,16): 18 | print("Working hours...") 19 | with open(hosts_path, 'r+') as file: 20 | content = file.read() 21 | for website in website_list: 22 | if website in content: 23 | pass 24 | else: 25 | # mapping hostnames to your localhost IP address 26 | file.write(redirect + " " + website + "\n") 27 | else: 28 | with open(hosts_path, 'r+') as file: 29 | content=file.readlines() 30 | file.seek(0) 31 | for line in content: 32 | if not any(website in line for website in website_list): 33 | file.write(line) 34 | 35 | # removing hostnmes from host file 36 | file.truncate() 37 | 38 | print("Fun hours...") 39 | time.sleep(5) 40 | -------------------------------------------------------------------------------- /python/pythongame1.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | from random import * 3 | from time import * 4 | bgcolor('light blue') 5 | p1 = Turtle() 6 | p2 = Turtle() 7 | p2.shape('turtle') 8 | p1.shape('turtle') 9 | p1.color('green') 10 | p2.color('black') 11 | p1.penup() 12 | p2.penup() 13 | p1.goto(-300,200) 14 | p2.goto(-300,-200) 15 | p2.goto(310,-300) 16 | p2.left(90) 17 | p2.pendown() 18 | p2.forward(550) 19 | p2.write('Finish',font=30) 20 | p2.penup() 21 | p2.goto(-300,-200) 22 | p2.right(90) 23 | for i in range(30): 24 | if p1.pos() >= (310,250): 25 | color('light blue') 26 | pencolor('red') 27 | penup() 28 | backward(200) 29 | pendown() 30 | write('player one wins the game',font=('courier',24,('bold'))) 31 | hideturtle() 32 | print('player one wins the game') 33 | break 34 | elif p2.pos() >= (310,-250): 35 | color('light blue') 36 | pencolor('red') 37 | penup() 38 | backward(200) 39 | pendown() 40 | write('player two wins the game', font=('courier',24,('bold'))) 41 | hideturtle() 42 | print('player two wins the game') 43 | break 44 | else: 45 | p1.forward(randint(60,80)) 46 | sleep(1) 47 | p2.forward(randint(60,80)) 48 | sleep(1) 49 | 50 | 51 | 52 | done() -------------------------------------------------------------------------------- /pythongames/2048game.py: -------------------------------------------------------------------------------- 1 | # logic.py to be 2 | # imported in the 2048.py file 3 | 4 | # importing random package 5 | # for methods to generate random 6 | # numbers. 7 | import random 8 | 9 | # function to initialize game / grid 10 | # at the start 11 | def start_game(): 12 | 13 | # declaring an empty list then 14 | # appending 4 list each with four 15 | # elements as 0. 16 | mat =[] 17 | for i in range(4): 18 | mat.append([0] * 4) 19 | 20 | # printing controls for user 21 | print("Commands are as follows : ") 22 | print("'W' or 'w' : Move Up") 23 | print("'S' or 's' : Move Down") 24 | print("'A' or 'a' : Move Left") 25 | print("'D' or 'd' : Move Right") 26 | 27 | # calling the function to add 28 | # a new 2 in grid after every step 29 | add_new_2(mat) 30 | return mat 31 | 32 | # function to add a new 2 in 33 | # grid at any random empty cell 34 | def add_new_2(mat): 35 | 36 | # choosing a random index for 37 | # row and column. 38 | r = random.randint(0, 3) 39 | c = random.randint(0, 3) 40 | 41 | # while loop will break as the 42 | # random cell chosen will be empty 43 | # (or contains zero) 44 | while(mat[r] != 0): 45 | r = random.randint(0, 3) 46 | c = random.randint(0, 3) 47 | 48 | # we will place a 2 at that empty 49 | # random cell. 50 | mat[r] = 2 51 | 52 | # function to get the current 53 | # state of game 54 | def get_current_state(mat): 55 | 56 | # if any cell contains 57 | # 2048 we have won 58 | for i in range(4): 59 | for j in range(4): 60 | if(mat[i][j]== 2048): 61 | return 'WON' 62 | 63 | # if we are still left with 64 | # atleast one empty cell 65 | # game is not yet over 66 | for i in range(4): 67 | for j in range(4): 68 | if(mat[i][j]== 0): 69 | return 'GAME NOT OVER' 70 | 71 | # or if no cell is empty now 72 | # but if after any move left, right, 73 | # up or down, if any two cells 74 | # gets merged and create an empty 75 | # cell then also game is not yet over 76 | for i in range(3): 77 | for j in range(3): 78 | if(mat[i][j]== mat[i + 1][j] or mat[i][j]== mat[i][j + 1]): 79 | return 'GAME NOT OVER' 80 | 81 | for j in range(3): 82 | if(mat[3][j]== mat[3][j + 1]): 83 | return 'GAME NOT OVER' 84 | 85 | for i in range(3): 86 | if(mat[i][3]== mat[i + 1][3]): 87 | return 'GAME NOT OVER' 88 | 89 | # else we have lost the game 90 | return 'LOST' 91 | 92 | # all the functions defined below 93 | # are for left swap initially. 94 | 95 | # function to compress the grid 96 | # after every step before and 97 | # after merging cells. 98 | def compress(mat): 99 | 100 | # bool variable to determine 101 | # any change happened or not 102 | changed = False 103 | 104 | # empty grid 105 | new_mat = [] 106 | 107 | # with all cells empty 108 | for i in range(4): 109 | new_mat.append([0] * 4) 110 | 111 | # here we will shift entries 112 | # of each cell to it's extreme 113 | # left row by row 114 | # loop to traverse rows 115 | for i in range(4): 116 | pos = 0 117 | 118 | # loop to traverse each column 119 | # in respective row 120 | for j in range(4): 121 | if(mat[i][j] != 0): 122 | 123 | # if cell is non empty then 124 | # we will shift it's number to 125 | # previous empty cell in that row 126 | # denoted by pos variable 127 | new_mat[i][pos] = mat[i][j] 128 | 129 | if(j != pos): 130 | changed = True 131 | pos += 1 132 | 133 | # returning new compressed matrix 134 | # and the flag variable. 135 | return new_mat, changed 136 | 137 | # function to merge the cells 138 | # in matrix after compressing 139 | def merge(mat): 140 | 141 | changed = False 142 | 143 | for i in range(4): 144 | for j in range(3): 145 | 146 | # if current cell has same value as 147 | # next cell in the row and they 148 | # are non empty then 149 | if(mat[i][j] == mat[i][j + 1] and mat[i][j] != 0): 150 | 151 | # double current cell value and 152 | # empty the next cell 153 | mat[i][j] = mat[i][j] * 2 154 | mat[i][j + 1] = 0 155 | 156 | # make bool variable True indicating 157 | # the new grid after merging is 158 | # different. 159 | changed = True 160 | 161 | return mat, changed 162 | 163 | # function to reverse the matrix 164 | # means reversing the content of 165 | # each row (reversing the sequence) 166 | def reverse(mat): 167 | new_mat =[] 168 | for i in range(4): 169 | new_mat.append([]) 170 | for j in range(4): 171 | new_mat[i].append(mat[i][3 - j]) 172 | return new_mat 173 | 174 | # function to get the transpose 175 | # of matrix means interchanging 176 | # rows and column 177 | def transpose(mat): 178 | new_mat = [] 179 | for i in range(4): 180 | new_mat.append([]) 181 | for j in range(4): 182 | new_mat[i].append(mat[j][i]) 183 | return new_mat 184 | 185 | # function to update the matrix 186 | # if we move / swipe left 187 | def move_left(grid): 188 | 189 | # first compress the grid 190 | new_grid, changed1 = compress(grid) 191 | 192 | # then merge the cells. 193 | new_grid, changed2 = merge(new_grid) 194 | 195 | changed = changed1 or changed2 196 | 197 | # again compress after merging. 198 | new_grid, temp = compress(new_grid) 199 | 200 | # return new matrix and bool changed 201 | # telling whether the grid is same 202 | # or different 203 | return new_grid, changed 204 | 205 | # function to update the matrix 206 | # if we move / swipe right 207 | def move_right(grid): 208 | 209 | # to move right we just reverse 210 | # the matrix 211 | new_grid = reverse(grid) 212 | 213 | # then move left 214 | new_grid, changed = move_left(new_grid) 215 | 216 | # then again reverse matrix will 217 | # give us desired result 218 | new_grid = reverse(new_grid) 219 | return new_grid, changed 220 | 221 | # function to update the matrix 222 | # if we move / swipe up 223 | def move_up(grid): 224 | 225 | # to move up we just take 226 | # transpose of matrix 227 | new_grid = transpose(grid) 228 | 229 | # then move left (calling all 230 | # included functions) then 231 | new_grid, changed = move_left(new_grid) 232 | 233 | # again take transpose will give 234 | # desired results 235 | new_grid = transpose(new_grid) 236 | return new_grid, changed 237 | 238 | # function to update the matrix 239 | # if we move / swipe down 240 | def move_down(grid): 241 | 242 | # to move down we take transpose 243 | new_grid = transpose(grid) 244 | 245 | # move right and then again 246 | new_grid, changed = move_right(new_grid) 247 | 248 | # take transpose will give desired 249 | # results. 250 | new_grid = transpose(new_grid) 251 | return new_grid, changed 252 | 253 | # this file only contains all the logic 254 | # functions to be called in main function 255 | # present in the other file 256 | -------------------------------------------------------------------------------- /pythongames/21numbergame.py: -------------------------------------------------------------------------------- 1 | # Python code to play 21 Number game 2 | 3 | # returns the nearest multiple to 4 4 | def nearestMultiple(num): 5 | if num >= 4: 6 | near = num + (4 - (num % 4)) 7 | else: 8 | near = 4 9 | return near 10 | 11 | def lose1(): 12 | print ("\n\nYOU LOSE !") 13 | print("Better luck next time !") 14 | exit(0) 15 | 16 | # checks whether the numbers are consecutive 17 | def check(xyz): 18 | i = 1 19 | while i ') 33 | 34 | # player takes the first chance 35 | if chance == "F": 36 | while True: 37 | if last == 20: 38 | lose1() 39 | else: 40 | print ("\nYour Turn.") 41 | print ("\nHow many numbers do you wish to enter?") 42 | inp = int(input('> ')) 43 | 44 | if inp > 0 and inp <= 3: 45 | comp = 4 - inp 46 | else: 47 | print ("Wrong input. You are disqualified from the game.") 48 | lose1() 49 | 50 | i, j = 1, 1 51 | 52 | print ("Now enter the values") 53 | while i <= inp: 54 | a = input('> ') 55 | a = int(a) 56 | xyz.append(a) 57 | i = i + 1 58 | 59 | # store the last element of xyz. 60 | last = xyz[-1] 61 | 62 | # checks whether the input 63 | # numbers are consecutive 64 | if check(xyz) == True: 65 | if last == 21: 66 | lose1() 67 | 68 | else: 69 | #"Computer's turn." 70 | while j <= comp: 71 | xyz.append(last + j) 72 | j = j + 1 73 | print ("Order of inputs after computer's turn is: ") 74 | print (xyz) 75 | last = xyz[-1] 76 | else: 77 | print ("\nYou did not input consecutive integers.") 78 | lose1() 79 | 80 | # player takes the second chance 81 | elif chance == "S": 82 | comp = 1 83 | last = 0 84 | while last < 20: 85 | #"Computer's turn" 86 | j = 1 87 | while j <= comp: 88 | xyz.append(last + j) 89 | j = j + 1 90 | print ("Order of inputs after computer's turn is:") 91 | print (xyz) 92 | if xyz[-1] == 20: 93 | lose1() 94 | 95 | else: 96 | print ("\nYour turn.") 97 | print ("\nHow many numbers do you wish to enter?") 98 | inp = input('> ') 99 | inp = int(inp) 100 | i = 1 101 | print ("Enter your values") 102 | while i <= inp: 103 | xyz.append(int(input('> '))) 104 | i = i + 1 105 | last = xyz[-1] 106 | if check(xyz) == True: 107 | # print (xyz) 108 | near = nearestMultiple(last) 109 | comp = near - last 110 | if comp == 4: 111 | comp = 3 112 | else: 113 | comp = comp 114 | else: 115 | # if inputs are not consecutive 116 | # automatically disqualified 117 | print ("\nYou did not input consecutive integers.") 118 | # print ("You are disqualified from the game.") 119 | lose1() 120 | print ("\n\nCONGRATULATIONS !!!") 121 | print ("YOU WON !") 122 | exit(0) 123 | 124 | else: 125 | print ("wrong choice") 126 | 127 | 128 | game = True 129 | while game == True: 130 | print ("Player 2 is Computer.") 131 | print("Do you want to play the 21 number game? (Yes / No)") 132 | ans = input('> ') 133 | if ans =='Yes': 134 | start1() 135 | else: 136 | print ("Do you want quit the game?(yes / no)") 137 | nex = input('> ') 138 | if nex == "yes": 139 | print ("You are quitting the game...") 140 | exit(0) 141 | elif nex == "no": 142 | print ("Continuing...") 143 | else: 144 | print ("Wrong choice") 145 | 146 | --------------------------------------------------------------------------------