Search This Blog

Showing posts with label 100DaysOfCode. Show all posts
Showing posts with label 100DaysOfCode. Show all posts

Python Mail Merge Project - Automating Recipient Writing in a Letter


Project Description:
  1. Automates the recipient writing part in the same letter.
  2. Recipient names are given in a separate file named invited_names.txt
  3. A sample letter is given in a separate file named starting_letter.txt
  4. Code is to be written inside main.py whose purpose is to fetch the sample letter, replace the [name] in a sample letter with recipient names &  generate an individual letter following this naming convention: letter_for_{recipient_name}.txt
  5. The number of names given in invited_names.txt file generates a similar number of letters. Suppose, 5 names are given in invited_names.txt then, 5 letters will be generated.


Folder Structure:

Folder Structure

Output:






./Input/Letters/starting_letter.txt


./Input/Names/invited_names.txt


./Output/ReadyToSend/example.txt


main.py

Crossing the Turtle : Python Turtle Project for Beginners

 

Game Rules:

  1. One turtle of unique color can only move forward.
    • Neither left nor right. Turtle cannot even move backward.    
  2. Turtle has to save itself from the collision with cars.
  3. If crosses all the cars, its level increases & along with all the car's speed!
  4. Random count cars & each car of random color are coming from the left & right.
  5. The scoreboard is maintained for every level.

How the game looks like?


crossing the turtle -gif


main.py



player.py



car_manager.py



scoreboard.py

Turtle Race : Python Project for Beginners


Game Rules:

1. 5 turtles of unique colors compete against each other.

2. User gets a chance to guess which color turtle will win the race.

3. If the user's guess is right it says you've won otherwise you lose!


Few screenshots of the game:





CODE:

Doodle it: Imagine, Draw, Erase and Repeat - Python Project for Beginners


 Doodle it: Imagine, Draw, Erase and Repeat

In order to create this game first step is to know a way of being able to listen to things the user does, like when a user taps a specific key on the keyboard. And the code that allows us to do this are called  Event Listeners.

Go to python documentation > listen method()


It has a whole bunch of section-on-screen events, including listening to key presses or listening to a click or other things that you can listen to. So the important thing is this listen method.


This allows turtle screen to start listening and waiting for the events that the user might trigger, like tapping on a key.

So for this first thing, we'll be going to do is we'll import the turtle class and the screen class from the turtle module. And then, we'll use them to create our Ted the turtle, and also create a screen object.


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()


This is basically going to control the window when we run our code.
Now in order to start listening for events, we have to get hold of the screen object and then tell it to start listening.


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

screen.listen()


And once it starts listening, we have to bind a function that will be triggered when a particular key is pressed on the keyboard. Now, in order to bind a keystroke to an event in our code, we have to use an event listener.

So the one that we're going to be using is this onkey method. And you can see it expects a function with no arguments and also a key, like the 'a' key on your keyboard or a key symbol, so the space or up or down.



So I'm going to say screen.onkey and then I have to bind some sort of function to this method.

So let's create a function named ted_move_right and all that this function is going to do is it's going to get Ted to go forward by 10 paces. 


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

def ted_move_right():
    ted.forward(10)

screen.listen()
screen.onkey() 




Now, coming back to our onkey method, we are going to say when the 'w', is pressed, then trigger the function move_forward.


def move_forward():
    ted.forward(10)

screen.listen()
screen.onkey(key='w',fun=move_forward)


Next, added the concerning triggered function move_backward to move backward when the 's' key is pressed.



from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

def move_forward():
    ted.forward(10)

def move_backward():
    ted.backward(10)
    
screen.listen()
screen.onkey(key='w',fun=move_forward)
screen.onkey(key='s',fun=move_backward)

screen.exitonclick()


Such that, functions to move counter-clockwise(left), clockwise(right) and to clear screen(reset screen) are written and binded them with the following keys 'a','d', & 'c' respectively.


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

def move_forward():
    ted.forward(10)

def move_backward():
    ted.backward(10)
    

def move_left():
    new_headingted.heading()+10
    ted.setheading(new_heading)

def move_right():
    new_headingted.heading()-10
    ted.setheading(new_heading)


def clear_screen():
    ted.clear()
    ted.penup()
    ted.home()
    ted.pendown()

screen.listen()

screen.onkey(key='w',fun=move_forward)
screen.onkey(key='s',fun=move_backward)

screen.onkey(key='a',fun=move_left)
screen.onkey(key='d',fun=move_right)
screen.onkey(key='c',fun=clear_screen)

screen.exitonclick()


And now what I'm going to try is when I hit the 'w' key on the keyboard, you should see my turtle move forwards by 10 paces each time. And, when 's' key is pressed it moves backward. So we're now controlling our turtle using a keystroke. That's pretty much in Doodle it: just imagine,draw & repeat.


Object Oriented Quiz Project - Python


QUIZ GAME RULES:

  1. In this quiz project, there is a total of 12 questions. And on the basis of the user's typed answer, the score will be awarded to them. Each question is of 1 mark. The answer can be either True or False. 
  2. The program is using an object-oriented approach.
  3. When a user types the wrong or right answer, share these remarks with them: 
  • If wrong: print("That's wrong")
  • If right: print("You got it right!")

When the quiz ends final output should be:

  • You've completed the quiz.
  • Your final score was: final_score/question_number

TODOs

File- main.py :

# TODO 1: the list to store the question data

# TODO 2: import all the dependent classes, methods

# TODO 3: Get the data from the dat.py and allocate the memory to the data(question, answer)

# TODO 4: Append each  allocated data to the list

# TODO 5: Pass the question list to the quiz brain for actions

# TODO 6: Continue asking questions until the end of the question list

# TODO 7: Display the final score and quiz is ended remark


Code- main.py :


from question_model import Question
from data import question_data
from quiz_brain import QuizBrain

question_bank = []


for question in question_data:
    q_text=question['text']
    q_answer=question['answer']

    new_question = Question(q_text,q_answer)
    question_bank.append(new_question)

quiz=QuizBrain(question_bank)


while quiz.still_has_questions():
    quiz.next_question()

print("You've completed the quiz.")
print(f"You final score was: {quiz.score}/{quiz.question_no}")


File- data.py :

# TODO 1: Store the dictionary data into a list.

Code- data.py :

question_data = [
    {"text""A slug's blood is green.""answer""True"},
    {"text""The loudest animal is the African Elephant.""answer""False"},
    {"text""Approximately one quarter of human bones are in the feet.""answer""True"},
    {"text""The total surface area of a human lungs is the size of a football pitch.""answer""True"},
    {"text""In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take "
             "it home to eat.""answer""True"},
    {"text""In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.""answer""False"},
    {"text""It is illegal to pee in the Ocean in Portugal.""answer""True"},
    {"text""You can lead a cow down stairs but not up stairs.""answer""False"},
    {"text""Google was originally called 'Backrub'.""answer""True"},
    {"text""Buzz Aldrin's mother's maiden name was 'Moon'.""answer""True"},
    {"text""No piece of square dry paper can be folded in half more than 7 times.""answer""False"},
    {"text""A few ounces of chocolate can to kill a small dog.""answer""True"}


File- question_model.py :

# TODO 1: Design a template for each question to store questions and answers at the right place.

Code- question_model.py :

class Question:
    def __init__(self,q_text,q_answer):
        self.text=q_text
        self.answer=q_answer

File- quiz_brain.py :

# TODO 1: asking the questions

# TODO 2: checking if the answer was correct

# TODO 3: checking if we're at the end of the quiz

Code- quiz_brain.py :


class QuizBrain:

    def __init__(self,question):
        self.score=0
        self.question_list=question
        self.question_no=0

    def still_has_questions(self):
        return len(self.question_list) > self.question_no

    def check_answer(selfuser_answer,correct_answer):
        if user_answer.lower()==correct_answer.lower():
            print('You got it right!')
            self.score+=1
        elif user_answer=='end' or user_answer=='END':
            exit()
        else:
            print("That's wrong!")
            
            
        print(f'The correct answer was: {correct_answer}')
        print(f"Your current score is {self.score}/{self.question_no}")
        print('\n')


    def next_question(self):
        
        #if you'll not add the .text after current question then it will
        #show the memory allocatons of the object so better use
        #current_location.text to access the text of queston
        current_questionself.question_list[self.question_no]
        self.question_no+=1
        user_answer=input(f"Q.{self.question_no}{current_question.text}  (True/False): ")
        
        correct_answer=current_question.answer

        self.check_answer(user_answer,correct_answer)


Object Oriented Coffee Maker Machine : Python

 

Object Oriented Coffee Maker Machine : Python
Object Oriented Coffee 
Maker Machine
( Python Based ) 

The functionality given to the virtual coffee machine is a replica of our actual coffee machine. But, this oops-oriented coffee machine can only take order one out of latte/espresso/cappuccino.

The code is designed after determining 5 conditions to serve the coffee:

  • Turn On & Off the machine
  • Print the available quantity of the resources & money
  • Process the made payment by the user
  • Here, check out the given payment is ok?
  • Serve the coffee
Before solving the above-mentioned conditions, the modules containing these functionalities are imported. And the functionality of these modules can be understood from below given class's documentation:

MenuItem Class

Attributes:

        

  • name

(str) The name of the drink.

e.g. “latte”

  • cost

(float) The price of the drink.

e.g 1.5

  • ingredients

(dictionary) The ingredients and amounts required to make the drink.

e.g. {“water”: 100, “coffee”: 16}

Menu Class

Methods:

  • get_items()

Returns all the names of the available menu items as a concatenated string.

e.g. “latte/espresso/cappuccino”

  • find_drink(order_name)

Parameter order_name: (str) The name of the drinks order.

Searches the menu for a particular drink by name. Returns a MenuItem object if it exists, otherwise returns None.

CoffeeMaker Class

Methods:

  • report()

Prints a report of all resources.

e.g.

Water: 300ml

Milk: 200ml

Coffee: 100g

  • is_resource_sufficient(drink)

Parameter drink: (MenuItem) The MenuItem object to make.

Returns True when the drink order can be made, False if ingredients are insufficient.

e.g.

True

  • make_coffee(order)

Parameter order: (MenuItem) The MenuItem object to make.

Deducts the required ingredients from the resources.

MoneyMachine Class

Methods:

  • report()

Prints the current profit

e.g.

Money: $0

  • make_payment(cost)

Parameter cost: (float) The cost of the drink.

Returns True when payment is accepted, or False if insufficient.

e.g. False


Final Code Structure

1. Turn On & Off the machine

is_on=True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on =
False
2. Print the available quantity of the resources & money - The final report

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
menu = Menu()

is_on = True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
3. & 4. Process the made payment by the user. Also, check out the given payment is ok?

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
# menuitem = MenuItem()
menu = Menu()
is_on=True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
else:
drink = menu.find_drink(choice)
if coffee.is_resource_sufficient(drink):
if money.make_payment(drink.cost):
5. Serve the coffee

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
menu = Menu()

is_on = True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
else:
drink = menu.find_drink(choice)
if coffee.is_resource_sufficient(drink):
if money.make_payment(drink.cost):
coffee.make_coffee(drink)
Thank You :)