Top 10 Advanced Python Projects with Source Code in 2022

Top 10 Advanced Python Projects with Source Code in 2022

Here is the list of the top 10 advanced python projects with source code in 2022

Python has been in the top 10 popular programming languages for a long time. Almost, 8.2 million developers all over the globe use Python for their projects which is more than Java now. Due to its readability and beginner-friendly nature, it has been accepted by various industries. So to master Python for any field, you have to work on python projects. If you have learned the fundamental Python libraries and some of the external libraries, you should now know how to install external libraries and work with them. So, if you are at that level now, you can work on all the advanced Python projects. This article features the list of the top 10 advanced python projects with source code in 2022:

Number Guessing

A fun python project to guess the number after getting a few hints from the computer. So, the system will generate a number from 0 to 200 and ask the user to guess it after a clue. Every time a user gives a wrong answer, another hint pops up to make it easier for them. It is one of the best advanced python projects with source code to try in 2022.

Source Code:

import random #bring in the random number

import time

number=random.randint(1, 200) #pick the number between 1 and 200

def intro():

    print("May I ask you for your name?")

    name=input() #asks for the name

    print(name + ", we are going to play a game. I am thinking of a number between 1 and 200")

    time.sleep(.5)

    print("Go ahead. Guess!")

def pick():

    guessesTaken = 0

    while guessesTaken < 6: #if the number of guesses is less than 6

        time.sleep(.25)

        enter=input("Guess: ") #inserts the place to enter guess

        try: #check if a number was entered

            guess = int(enter) #stores the guess as an integer instead of a string    

            if guess<=200 and guess>=1: #if they are in range

                guessesTaken=guessesTaken+1 #adds one guess each time the player is wrong

                if guessesTaken<6:

                    if guess

                        print("The guess of the number that you have entered is too low")

                    if guess>number:

                        print("The guess of the number that you have entered is too high")

                    if guess != number:

                        time.sleep(.5)

                        print("Try Again!")

                if guess==number:

                    break #if the guess is right, then we are going to jump out of the while block

            if guess>200 or guess<1: #if they aren't in the range

                print("Silly Goose! That number isn't in the range!")

                time.sleep(.25)

                print("Please enter a number between 1 and 200")

        except: #if a number wasn't entered

            print("I don't think that "+enter+" is a number. Sorry")

    if guess == number:

        guessesTaken = str(guessesTaken)

        print('Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!')

    if guess != number:

        print('Nope. The number I was thinking of was ' + str(number))

playagain="yes"

while playagain=="yes" or playagain=="y" or playagain=="Yes":

    intro()

    pick()

    print("Do you want to play again?")

    playagain=input()

Voice Assistant Python Project

Voice assistant is one of the best python projects to try in 2022. Siri, Alexa, and OkGoogle are already leading the market. How about you have a personal assistant of your own> Create your own voice assistant using this Python program. 

Source Code:

import pyttsx3

import speech_recognition as sr

import wikipedia

import webbrowser

import os

# init pyttsx

engine = pyttsx3.init("sapi5")

voices = engine.getProperty("voices")

engine.setProperty('voice', voices[1].id)  # 1 for female and 0 for male voice

def speak(audio):

    engine.say(audio)

    engine.runAndWait()

def take_command():

    r = sr.Recognizer()

    with sr.Microphone() as source:

        print("Listening…")

        r.pause_threshold = 1

        audio = r.listen(source)

    try:

        print("Recognizing…")

        query = r.recognize_google(audio, language='en-in')

        print("User said:" + query + "\n")

    except Exception as e:

        print(e)

        speak("I didnt understand")

        return "None"

    return query

if __name__ == '__main__':

    speak("Amigo assistance activated ")

    speak("How can i help you")

    while True:

        query = take_command().lower()

        if 'wikipedia' in query:

speak("Searching Wikipedia …")

            query = query.replace("wikipedia", ")

            results = wikipedia.summary(query, sentences=2)

            speak("According to wikipedia")

            speak(results)

        elif 'are you' in query:

            speak("I am amigo developed by Jaspreet Singh")

        elif 'open youtube' in query:

            speak("opening youtube")

            webbrowser.open("youtube.com")

        elif 'open google' in query:

            speak("opening google")

            webbrowser.open("google.com")

        elif 'open github' in query:

            speak("opening github")

            webbrowser.open("github.com")

        elif 'open stackoverflow' in query:

            speak("opening stackoverflow")

            webbrowser.open("stackoverflow.com")

        elif 'open spotify' in query:

            speak("opening spotify")

            webbrowser.open("spotify.com")

        elif 'open whatsapp' in query:

            speak("opening whatsapp")

            loc = "C:\\Users\\jaspr\\AppData\\Local\\WhatsApp\\WhatsApp.exe"

            os.startfile(loc)

        elif 'play music' in query:

            speak("opening music")

            webbrowser.open("spotify.com")

        elif 'play music' in query:

            speak("opening music")

            webbrowser.open("spotify.com")

        elif 'local disk d' in query:

            speak("opening local disk D")

            webbrowser.open("D://")

        elif 'local disk c' in query:

            speak("opening local disk C")

            webbrowser.open("C://")

        elif 'local disk e' in query:

            speak("opening local disk E")

            webbrowser.open("E://")

        elif 'sleep' in query:

            exit(0)

Password Generator

Next in the list of the top 10 advanced python projects with source code in 2022 is Password Generator. The most difficult part of managing multiple accounts is generating a different strong password for each. A strong password is a mix of alphabets, numbers, and alphanumeric characters. Therefore, the best use of Python could be building a project where you could generate random passwords for any of your accounts. 

Source Code:

import random

def generatePassword(pwlength):

    alphabet = "abcdefghijklmnopqrstuvwxyz"

    passwords = [] 

    for i in pwlength:   

        password = "" 

        for j in range(i):

            next_letter_index = random.randrange(len(alphabet))

            password = password + alphabet[next_letter_index]

        password = replaceWithNumber(password)

        password = replaceWithUppercaseLetter(password)

        passwords.append(password) 

    return passwords

def replaceWithNumber(pword):

    for i in range(random.randrange(1,3)):

        replace_index = random.randrange(len(pword)//2)

        pword = pword[0:replace_index] + str(random.randrange(10)) + pword[replace_index+1:]

        return pword

def replaceWithUppercaseLetter(pword):

    for i in range(random.randrange(1,3)):

        replace_index = random.randrange(len(pword)//2,len(pword))

        pword = pword[0:replace_index] + pword[replace_index].upper() + pword[replace_index+1:]

        return pword

def main():

    numPasswords = int(input("How many passwords do you want to generate? "))

    print("Generating " +str(numPasswords)+" passwords")

    passwordLengths = []

    print("Minimum length of password should be 3")

    for i in range(numPasswords):

        length = int(input("Enter the length of Password #" + str(i+1) + " "))

        if length<3:

            length = 3

        passwordLengths.append(length)

    Password = generatePassword(passwordLengths)

    for i in range(numPasswords):

        print ("Password #"+str(i+1)+" = " + Password[i])

main()

Reddit Bot Python Project

Reddit is used for one purpose or the other. The famous question-answer app can now also have a bot linked to it. The bot will automate comments on the posts based on specified criteria. It is surely one of the best advanced python projects to try.

Source Code:

Pick a subreddit to scan

Designate a specific comment to search for

Set your bot's reply

Create a config.py file with your Reddit account details and Reddit.py file with the bot requirements

Pre-requisites: Python, Praw, and A reddit account

Config.py

username = "RedditUsername"

password = "password"

client_id = "idGoesHere"

client_secret = "secretGoesHere"

Reddit.py

import praw

import config

import time

import os

def bot_login():

    print "Logging in…"

    r = praw.Reddit(username = config.username,

                password = config.password,

                client_id = config.client_id,

                client_secret = config.client_secret,

                user_agent = "The Reddit Commenter v1.0")

    print "Logged in!"

    return r

def run_bot(r, comments_replied_to):

    print "Searching last 1,000 comments"

    for comment in r.subreddit('test').comments(limit=1000):

        if "sample user comment" in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me():

            print "String with \"sample user comment\" found in comment " + comment.id

            comment.reply("Hey, I like your comment!")

            print "Replied to comment " + comment.id

            comments_replied_to.append(comment.id)

            with open ("comments_replied_to.txt", "a") as f:

                f.write(comment.id + "\n")

    print "Search Completed."

    print comments_replied_to

    print "Sleeping for 10 seconds…"

    #Sleep for 10 seconds…

    time.sleep(10)

def get_saved_comments():

if not os.path.isfile("comments_replied_to.txt"):

        comments_replied_to = []

    else:

        with open("comments_replied_to.txt", "r") as f:

            comments_replied_to = f.read()

            comments_replied_to = comments_replied_to.split("\n")

            comments_replied_to = filter(None, comments_replied_to)

    return comments_replied_to

r = bot_login()

comments_replied_to = get_saved_comments()

print comments_replied_to

while True:

    run_bot(r, comments_replied_to)

Black Jack

Creating the most famous card game of the casinos in Python would be one of the most wonderful python projects. This game is played with a deck of 52 cards where the strategies play at best. Shuffle the cards, announce the buy-in amount, and decide the ranking of the cards. 

Source Code:

#!/Users/Utsav/downloads/udemy python

# For using the same code in either Python 2 or 3

# from __future__ import print_function

# Importing libraries — used for shuffling cards

import random

# Boolean type to know whether play is in hand

playing = False

# Amount for buy-in

chip_pool = 100

# raw_input('Enter the amount for buy-in: ')

print 'Your buy-in amount is: ',chip_pool

bet = 1

restart_phrase = "Press d to deal the cards again, or press q to quit."

# Hearts, Diamonds, Clubs, Spades

suits = ('H','D','S','C')

# Possible Card Ranks

ranking = ('A','2′,'3′,'4′,'5′,'6′,'7′,'8′,'9′,'10','J','Q','K')

# Point Val Dict (Dual existence of Ace is defined later)

card_val = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10}

# Creating Card Class

class Card:

    def __init__(self, suit, rank):

        self.suit = suit

        self.rank = rank

    def __str__(self):

        return self.suit + self.rank

    def grab_suit(self):

        return self.suit

    def grab_rank(rank):

        return self.rank

    def draw(self):

        print (self.suit + self.rank)

# Creating Hand Class

# Gives dual existence to Ace

class Hand:

    def __init__(self):

        self.cards = []

        self.value = 0

        # Aces can be 1 0r 11 as defined below

        self.ace = False

def __str__(self):

        "'Return a string of current hand composition"'

        hand_comp = ""

        # List Comprehension

        for card in self.cards:

            card_name = card.__str__()

            hand_comp += " " + card_name

        return 'The hand has %s' %hand_comp

    def card_add(self,card):

        "'Add another card to the hand"'

        self.cards.append(card)

        # Checking for Aces

        if card.rank == 'A':

            self.ace = True

        self.value += card_val[card.rank]

    def calc_val(self):

        "'Calculating value of hand, making aces = 1 if they don't bust the hand"'

        if (self.ace == True and self.value < 12):

            return self.value + 10

        else:

            return self.value

    def draw(self, hidden):

        if hidden == True and playing == True:

            # Don't show first hidden card

            starting_card = 1

        else:

            starting_card = 0

        for x in range(starting_card, len(self.cards)):

            self.cards[x].draw()

# Creating Class Deck

class Deck:

    def __init__(self):

        "'Creating a deck in order"'

        self.deck = []

for suit in suits:

            for rank in ranking:

                self.deck.append(Card(suit,rank))

    def shuffle(self):

        "'Shuffles the deck, using python's built-in random library"'

        random.shuffle(self.deck)

    def deal(self):

        "'Grabbing the first item in the deck"'

        single_card = self.deck.pop()

        return single_card

    def __str__(self):

        deck_comp = " "

        for card in self.cards:

            deck_comp += " " + deck_comp.__str__()

        return "The deck has " + deck_comp

# End of Classes

# First Bet

def make_bet():

    "'Ask the player for the bet amount and "'

    global bet

    bet = 0

    print 'What amount of chips would you like to bet? (Please enter whole integer) '

    # While loop to keep asking for the bet

    while bet == 0:

        # Using bet_comp as a checker

        bet_comp = raw_input()

        bet_comp = int(bet_comp)

        # Check to make sure the bet is within the remaining amount of chips left

        if bet_comp >= 1 and bet_comp <= chip_pool:

            bet = bet_comp

        else:

            print "Invalid bet, you only have " + 

str(chip_pool) + " remaining"

def deal_cards():

    "'This function deals out cards and sets up round"'

    # Set up all global variables

    global result, playing, deck, player_hand, dealer_hand, chip_pool, bet

    # Creating a deck

    deck = Deck()

    # Shuffle it

    deck.shuffle()

    # Set up the bet

    make_bet()

    # Set up both player and dealer hands

    player_hand = Hand()

    dealer_hand = Hand()

    # Deal out initial cards

    player_hand.card_add(deck.deal())

    player_hand.card_add(deck.deal())

    result = "Hit or Stand? Press h for hit or s for stand: "

    if playing == True:

        print 'Fold, Sorry'

        chip_pool -= bet

    # Set up to know currently playing hand

    playing = True

    game_step()

# Hit Function

def hit():

    "'Implementing the hit button"'

    global playing, chip_pool, deck, player_hand, dealer_hand, result, bet

    # If hand is in play add card

if playing:

        if player_hand.calc_val() <= 21:

            player_hand.card_add(deck.deal())

        print "Player hand is %s" %player_hand

        if player_hand.calc_val() > 21:

            result = 'Busted!' + restart_phrase

            chip_pool -= bet

            playing = False

    else:

        result = "Sorry, can't hit" + restart_phrase

    game_step()

# Stand Function

def stand():

    global playing, chip_pool, deck, player_hand, dealer_hand, result, bet

    "'This function plays the dealers hand, since stand was chosen"'

    if playing == False:

        if player_hand.calc_val() > 0:

            result = "Sorry, you can't stand!"

    # Going through all other possible options

    else:

        # Sfot 17 Rule

        while dealer_hand.calc_val() < 17:

            dealer_hand.card_add(deck.deal())

        # Dealer Busts

        if dealer_hand.calc_val() > 21:

            result = 'Dealer busts! You win! ' + restart_phrase

            chip_pool += bet

            playing = False

        # Player has better hand than dealer

elif dealer_hand.calc_val() < player_hand.calc_val():

            result = 'You beat the dealer, you win! ' + restart_phrase

            chip_pool += bet

            playing = False

        # Push

        elif dealer_hand.calc_val == player_hand.calc_val():

            result = 'Tied up, push!' + restart_phrase

            playing = False

        # Dealer beats player

        else:

            result = 'Dealer Wins! ' + restart_phrase

            chip_pool -= bet

            playing = False

    game_step()

# Function to print results and ask user for next step

def game_step():

    "'Function to print game step/status on output"'

    # Display Player Hand

    print ""

    print ('Player Hand is: '),player_hand.draw(hidden = False)

    print "

    print 'Player hand total is: ' +str(player_hand.calc_val())

    # Display Dealer Hand

    print "

    print('Dealer Hand is: '), dealer_hand.draw(hidden = True)

    # If game round is over

    if playing == False:

        print " — for a total of " + str(dealer_hand.calc_val())

        print "Chip Total: " +str(chip_pool)

    # Otherwise, don't know the second card yet

    else:

        print " with another card hidden upside down"

    # Print result of hit or stand

print "

    print result

    player_input()

# Function to exit the game

def game_exit():

    print 'Thanks for playing!'

    exit()

# Function to read user input

def player_input():

    "'Read user input, lower case it jsuts to be safe"'

    plin = raw_input().lower()

    if plin == 'h':

        hit()

    elif plin == 's':

        stand()

    elif plin == 'd':

        deal_cards()

    elif plin == 'q':

        game_exit()

    else:

        print "Invalid Input. Enter h, s, d, or q: "

        player_input()

# Intro to game

def intro():

    statement = "'Welcome to BlackJack! Get as close to 21 as you can without getting over! 

Dealer hits until she reaches 17. Aces count as 1 or 11. Card output goes a letter followed by a number of face notation. "'

    print statement

    print "

# Playing the Game

"'The following code will initiate the game! 

(Note: Need to Run a 11 Cells)"'

# Create a Deck

deck = Deck()

# Shuffle it

deck.shuffle()

# Create player and dealer hands

print "

player_hand = Hand()

print "

deal_hand = Hand()

# Print the intro

intro()

# Deal out the cards and start the game!

deal_cards()

Recursive Triangle

This is one of the best advanced python projects to try in 2022. 

Source Code:

def triangle(n):

    return recursive_triangle(n, n)

def recursive_triangle(x, n):

    # First we must verify that both input values are integers.

    if type(x) != int or type(n) != int:

        return 'error'

    # If x is bigger than n, we will still only print the full triangle, so we can set them equal.

    if x > n:

        x = n

    # If either value is zero, the output should be an empty string because there are no lines or triangle to print.

    if x == 0 or n == 0:

        return "

    # Let's set some variable names to help us out.

    star_print = n

    line_number = x

    # I'll create an empty string that we can concatenate values to.

    line_print = "

# The difference value will determine how many shapes are needed to fill the line before the stars are printed.

    difference = star_print – line_number

    # If difference is not zero, we will print that value of spaces before the stars. The star print will be the

    # remainder, also known as line number.

    if difference != 0:

        line_print += ' '*difference

        line_print += '*'*line_number

    # If difference is zero, then we can just fill the line with stars.

    else:

        line_print += '*'*star_print

    # If the line number is greater than one, we can return our string and use the recursive call to run the function

    # again with the line number as one value less.

    if line_number > 1:

        return line_print+'\n'+str(recursive_triangle(line_number-1, star_print))

    # If the line number is exactly one, then we don't need to use the recursive call.

    elif line_number == 1:

        return line_print

Queue

Implements queue data structure. A queue is an entity that maintains the data in a linear format and processes it in FIFO order. 

class Node:

    def __init__(self, value):

        self.value = value  

        self.next = None 

    def __str__(self):

        return "Node({})".format(self.value) 

    __repr__ = __str__

class Queue:

    def __init__(self): 

        self.head=None

        self.tail=None

    def __str__(self):

temp=self.head

        out=[]

        while temp:

            out.append(str(temp.value))

            temp=temp.next

        out=' '.join(out)

        return ('Head:{}\nTail:{}\nQueue:{}'.format(self.head,self.tail,out))

    __repr__=__str__

    def isEmpty(self):

        # This is where my code begins. I will check to see if self.head is none: if it is, the queue must be empty.

        if self.head is None:

            return True

        else:

            # Otherwise, the queue is not empty and we return False.

            return False

    def __len__(self):

        # I'll create a temp value starting at self.head, the "front" of the queue. I'll also set a count variable to 0.

        temp = self.head

        count = 0

        # We'll traverse the list until the temp value is none, meaning we've reached the end of the queue. For each

        # item, we increase our count value by 1.

        while temp is not None:

            count += 1

            temp = temp.next

        # Then we return our count variable.

        return count

    def enqueue(self, value):

        # If the queue is not empty, we need to examine the tail of the queue.

        if self.head is not None:

            # We'll create an instance of class Node at our value and call it new_node.

            new_node = Node(value)

            # I'll set a temp value to the existing tail of the queue.

            temp = self.tail

            # I'll let the value after the temp variable equal our 

new node.

            temp.next = new_node

            # Then, I'll reassign self.tail as the new_node.

            self.tail = new_node

        else:

            # If the queue is empty, we still instantiate class Node at our value.

            new_node = Node(value)

            # Because the queue is empty, self.head and self.tail will both equal new_node until new items are enqueued.

            self.head = new_node

            self.tail = new_node

    def dequeue(self):

        # First, we must check if the queue is empty.

        if self.head is not None:

            # Then, we need to check if the queue has only one value.

            if self.head == self.tail:

                # I'll set a variable at self.head, chosen arbitrarily over self.tail since there is only one item.

                item = self.head

                # I'll save the value of my item for returning later.

                return_value = item.value

                # I'm setting both self.head and self.tail to "item.next," which is simply None. When we have dequeued

                # the item variable, these values should both be none.

                self.head = item.next

                self.tail = item.next

                # Then I delete my single item.

                del item

                # We return the value that we saved earlier.

                return return_value

            else:

                # If the queue has at least two values, we only examine self.head. I'll call it an item variable.

                item = self.head

                # I'll save the value of my item for returning later.

                return_value = item.value

                # I'll set the new self.head to the next item in the queue after my item.

                self.head = item.next

                # Then I delete my item.

                del item

                # We return the value that we saved earlier.

                return return_value

        else:

            # If the queue is empty, we cannot dequeue anything.

            return 'Queue is empty'

Email Slicer

One of the easiest python projects to start with is getting an email ID as input and slicing it into username and domain name. 

Source Code:

email = input("Enter Your Email: ").strip()

username = email[:email.index('@')]

domain = email[email.index('@') + 1:]

3D Graphs 

The most basic three-dimensional plot is a line or scatter plot created from sets of (x,y,z) triples. This is surely one of the best advanced python projects with source code to try in 2022.

Source code:

import numpy as np

import matplotlib.colors as col

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

#Data for a three dimensional line

z = np.linspace(0, 15, 1000)

x = np.sin(z)

y = np.cos(z)

ax.plot3D(x, y, z, 'grey')

#Data for three dimensional scattered points

z = 15 * np.random.random(100)

x = np.sin(z) + 0.1 * np.random.randn(100)

y = np.cos(z) + 0.1 * np.random.randn(100)

ax.scatter3D(x, y, z, c=z, cmap='Greens')

plt.show()

Related Stories

No stories found.
logo
Analytics Insight
www.analyticsinsight.net