Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Top10 Python Projects With Source Code
2.1.
Random Story Generator
2.1.1.
Source Code
2.2.
Python
2.2.1.
Output 1
2.2.2.
Output 2
2.2.3.
Explanation
2.3.
Simple Email Slicer
2.3.1.
Source Code
2.4.
Python
2.4.1.
Input
2.4.2.
Output
2.4.3.
Explanation
2.5.
Acronyms Creator
2.5.1.
Source Code
2.6.
Python
2.6.1.
Input
2.6.2.
Output
2.6.3.
Explanation
2.7.
Body Mass Index(BMI) Calculator
2.7.1.
Source Code
2.8.
Python
2.8.1.
Input
2.8.2.
Output
2.8.3.
Explanation
2.9.
Dice Roll Simulator
2.9.1.
Source Code
2.10.
Python
2.10.1.
Output 1
2.10.2.
Output 2
2.10.3.
Explanation
2.11.
Basic Quiz Game
2.11.1.
Source Code
2.12.
Python
2.12.1.
Output
2.12.2.
Explanation
2.13.
Rock, Paper, and Scissors Game
2.13.1.
Source Code
2.14.
Python
2.14.1.
Output
2.14.2.
Explanation
2.15.
Chatbot
2.15.1.
Source Code
2.16.
Python
2.16.1.
Starting Conversation
2.16.2.
Output
2.17.
Text to Speech
2.17.1.
Source Code
2.18.
Python
2.18.1.
Running TTS
2.19.
Tic Tac Toe Project
2.19.1.
Source Code
2.20.
Python
2.20.1.
 
2.20.2.
Output
2.20.3.
Explanation
3.
Frequently Asked Questions
3.1.
What is a Random module in Python?
3.2.
What is NLTK in Python?
3.3.
Why do we use the os module in Python?
3.4.
What is the use of the punkt package in NLTK?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Python Projects with Source Code

Author Nidhi Kumari
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Looking to build a project for your college or to improve your resume? One of the best choices of languages for a project is Python. For many reasons, Python is a well-liked language for web-based and software development. Coders can express ideas in Python with fewer lines of code than in other languages.

Python Projects with Source Code

Here's a closer look at several valuable and user-friendly Python projects with source code for coders.

See more, Python for Data Science

Top10 Python Projects With Source Code

List of amazing top 10 Python Projects with source code are:

  • Random Story Generator
  • Simple Email Slicer
  • Acronyms Creator
  • Body Mass Index(BMI) Calculator
  • Dice Roll Simulator
  • Basic Quiz Game
  • Rock, Paper, and Scissors Game
  • Chatbot
  • Text to Speech
  • Tic Tac Toe Project

Random Story Generator

It is one of the exciting beginner Python projects with source code. Every time a user runs the code, the random story generator project tries to produce a different and random story.

Used Module: Random module.

Source Code

  • Python

Python

#importing module
import random
#Defining a list of phrases for sentence making
topic = ['DSA', 'Python', 'Java', 'Computer Networks',' Operating Systems']
adj = ['an important', 'an essential', 'very important', 'an interesting']
to = ['Developers', 'Student',' Professionals', 'Freshers']
supportive = ['learn it',' master it', 'read it', 'see it']
where = ['Coding Ninjas.', 'Code Studio.',' Code Studio Library.', 'CN guided paths.']
#generating the output
print(random.choice(topic) + ' is ' + random.choice(adj) + ' topic for ' + random.choice(to) + ', You can ' + random.choice(supportive) + ' from ' + random.choice(where))

 

Output 1

Operating Systems is an important topic for Freshers, You can read it from CN guided paths.

 

Output 2

Computer Networks is an important topic for Freshers, You can see it from Code Studio.

 

Explanation

We are getting random output every time we compile and run this code. The story's random fragments, which are listed in various lists, can be selected through the random module.

Simple Email Slicer

Email Slicer is an essential project that accepts an email address as its input and produces the username and domain of the entered email address.

Used Function: Slicing Function

Source Code

  • Python

Python

#user input
email = input("Please enter your email:").strip()


#definig username and domain parts
username_part = email[:email.index("@")]
domain_name = email[email.index("@")+1:]


output = (f"Your user name is '{username_part}' and your domain is '{domain_name}'")


#genrating the output
print(output)

 

Input

Please enter your email:nidhi.singh@codingninjas.com

 

Output

Your user name is 'nidhi.singh' and your domain is 'codingninjas.com'

 

Explanation

We are using the strip function to remove any whitespace. The code will search for the index of the "@" sign in the user input. The index is used to divide the mail into username and domain parts.

Acronyms Creator

This project creates an acronym from the input string. An acronym is a short form of a word. For example, CN is an acronym for Coding Ninjas.

Used Functions: Splitting and Indexing

Source Code

  • Python

Python

#User Input
input_string = str(input("Enter your Phrase: "))

#Using the splitting function
txt = input_string.split()

#Using indexing via for loop
n = " "
for i in txt:
   n = n+str(i[0]).upper()
print(n)

 

Input

Enter your Phrase: Natural language processing

 

Output

NLP

 

Explanation

In the code above, We first accept a string input from the user.

We will use Python's split() method for splitting the user input. We created a new variable, "n", to hold a phrase's acronym. We use the upper() method to get the Capital letters as acronyms.

Body Mass Index(BMI) Calculator

The formula for calculating a person's body mass index is to divide their weight(kg) by their height in meters squared. Let's now look at how to build a BMI calculator in Python.

Source Code

  • Python

Python

H = float(input('Enter your height in meters: '))
W = float(input('Enter your Weight in Kg: '))
BMI = W / (H * H)
print ('Your Body Mass Index is: ', BMI)
if BMI > 0:
if BMI <= 16:
print 'You are severely underweight :('
elif BMI <= 18.5:
print 'You are underweight :('
elif BMI <= 25:
print 'Hooray! You are Healthy :)'
elif BMI <= 30:
print 'Oops! You are overweight :('
else:
print 'You are suffering from obesity.'
else:("Kindly enter valid details")

 

Input

Enter your height in meters: 1.54
Enter your Weight in Kg: 48

 

Output

Your Body Mass Index is:  20.23950075898128
Hooray! You are Healthy :)

 

Explanation

In the code above, We first accept height and weight from the user.

We will use basic if-else statements to provide the output.

Dice Roll Simulator

We will see one of the basic Python projects with source code to simulate a die roll.

Used Module: Random Module

Used Function: random.randint() function

Source Code

  • Python

Python

#importing random module for random number generation
import random

#range of a dice
minimum = 1
maximum = 6

#to loop the rolling through user input
Diceroll_again = "yes"

while Diceroll_again == "yes" or Diceroll_again == "y":
   print("Rolling your Dice...")
   print("The Values are :")
  
   #generating and printing 1st random value
   print(random.randint(minimum,maximum))
  
   #generating and printing 2nd random value
   print(random.randint(minimum,maximum))
  
   Diceroll_again = input("Do you want to roll the Dice Again? ")

 

Output 1

Rolling your Dice...
The Values are :
5
6
Do you want to roll the Dice Again?

 

Output 2

Rolling your Dice...
The Values are :
3
6
Do you want to roll the Dices Again? yes
Rolling your Dice...
The Values are :
6
5

 

Explanation

The code mentioned above can imitate a dice roll because the minimum and maximum values of a dice roll are 1 and 6, respectively. This provides the start and finish numbers for the random.randint() function that we will employ.

Basic Quiz Game

We will create a basic quiz game. The Quiz is over after all of the questions have been solved.

Source Code

  • Python

Python

def check_ans(que, answer):
   global score
   still_answering = True
   attempt = 0
   while still_answering and attempt < 3:
       if que.lower() == answer.lower():
           print("Correct Answer")
           score = score + 1
           still_answering = False
       else:
           if attempt < 2:
               que = input("Sorry Wrong Answer, try again")
           attempt = attempt + 1
   if attempt == 3:
       print("The Correct answer is ",answer )
  
score = 0
print("Guess Correct Answer")
que1 = input(" Who developed the Python language? ")
check_ans(que1, "Guido van Rossum")
que2 = input(" What is the correct extension of the Python file? ")
check_ans(que2, ".py")
que3 = input("What do we use to define a block of code in Python language? ")
check_ans(que3, "Indentation")
print("Your total score is "+ str(score))

 

Output

Guess Correct Answer
Who developed the Python language? Guido van Rossum
Correct Answer
What is the correct extension of the Python file? .py
Correct Answer
What do we use to define a block of code in Python language? Indentation
Correct Answer
Your total score is 3

 

Explanation

we'll begin by developing the questions and the process for answering them. The code that provides the player three chances to respond to each question will then be added.

Rock, Paper, and Scissors Game

We will use Python here to develop a Rock, Paper, and Scissors game.

Used Module: Random Module

Source Code

  • Python

Python

#importing random module
import random
#Declaring available resourses
options = ["Rock", "Paper", "Scissors"]

#Selecting random option for machine
machine = random.choice(options)

#Declaring scores
user = False
machine_score = 0
user_score = 0

while True:
   user = input("Rock, Paper or  Scissors? ").capitalize()
   # Conditions of Rock, Paper and Scissors
   if user == machine:
       print("Tie!")
   elif user == "Rock":
       if machine == "Paper":
           print("You lose!", machine, "covers", user)
           machine_score+=1
       else:
           print("You win!", user, "smashes", machine)
           user_score+=1
   elif user == "Paper":
       if machine  == "Scissors":
           print("You lose!", machine, "cut", user)
           machine_score+=1
       else:
           print("You win!", user, "covers", machine)
           user_score+=1
   elif user == "Scissors":
       if machine == "Rock":
           print("You lose...", machine, "smashes", user)
           machine_score+=1
       else:
           print("You win!", user, "cut", machine)
           user_score+=1
   elif user =='End':
       print("Final Scores:")
       print(f"Computer's score is:{machine_score}")
       print(f"Your score is:{user_score}")
       break

 

Output

Rock, Paper or  Scissors? paper
Tie!
Rock, Paper or  Scissors? end
Final Scores:
Computer's score is:0
Your score is:0

 

Explanation

We are comparing the user’s choice with the computer(machine). The machine's choice is selected using the random module in Python from a list of choices. If the user wins, then the user_score will increase by 1; else, machine_score will increase by 1.

Chatbot

A chatbot is a computer programme designed to simulate interaction with human users, particularly online. Generally, there are two types of chatbots:

  • Rule-based: based on some predefined rules.
     
  • Self-learning: based on machine learning algorithms.
     

Here, we will design a rule-based chatbot.

Used Library: NLTK( Natural Language Toolkit)
 

Used Module: Chat
 

Used Dictionary: Reflections

Source Code

  • Python

Python

# Importing libraries
from nltk.chat.util import Chat, reflections

#Creating a list of responses
responses = [
  
   [
       r"(hi|hey|hello|hola|holla)(.*)",
       ["Hello", "Hey there","Hello user", "Hello friend"]
   ],
  
   [
       r"(.*) your name ?",
       ["My name is Ninja and I'm a chatbot.",]
   ],


   [
       r"(.*)help(.*) ",
       ["I can help you.",]
   ],


   [
       r"how are you (.*) ?",
       ["i am great !, i am fine., i am good."]
   ],
   [
       r"sorry (.*)",
       ["Its alright","Its OK, never mind that",]
   ],


   [
       r"quit",
       ["Bye. See you soon :) ","Have a great day. See you soon :) ","It was nice talking to you. See you soon :)"]
   ],
   [
       r"(.*)",
       ['That is nice to hear']
   ],
]


#Generating reflections
print(reflections)

#Output
{'i': 'you',
'your': 'my',
'yours': 'mine',
'i was': 'you were',
'you were': 'I was',
"i'll": 'you will',
"you'll": 'I will',
'you are': 'I am',
"you've": 'I have',
"i'd": 'you would'
}

#default message
print("Hi, I'm a bot, and my name is Ninja. \nPlease type your query. Type quit to leave. ")
#Creating Chat Bot
chat = Chat(responses, reflections)

 

Starting Conversation

#To start a conversation with the chatbot
chat.converse()

 

Output

Hi, I'm a bot, and my name is Ninja.
Please type your query. Type quit to leave.
>hey
Hello
>what is your name?
My name is Ninja and I'm a chatbot.
>will you help me?
I can help you.
>quit
Bye. See you soon :)

Text to Speech

An example of assistive technology that reads digital text aloud is text-to-speech (TTS). Technology for "read aloud" is another name for it. Here, we will create a TTS project using Python.

Used Libraries: NLTK( Natural Language Toolkit), Newspaper, gTTS(google Text to Speech).

Source Code

  • Python

Python

#Importing required libraries
import nltk
from newspaper import Article
from gtts import gTTS
import os
#Selecting the article
post = Article('https://www.codingninjas.com/studio/library/building-a-qr-code-generator-in-python')

#Downloading and parsing the article
post.download()
post.parse()


#Downloading punkt package
nltk.download('punkt')
post.nlp()


#Getting the text
txt = post.text


#Choosing language of speech
language = 'en'
#English

#Storing text in a variable
#Slow = falsewill allow the audio at high speed
obj = gTTS(text=txt, lang=language, slow=False)

 

Running TTS

#save the speech to an mp3 file
obj.save("read_post.mp3")
#To play the converted audio
os.system("start read_post.mp3")

Tic Tac Toe Project

Tic Tac Toe is a famous game. Everyone has played it in their childhood. Let us try to develop a Python project for it. We will simply use the game's logic, if-else statements, user-defined functions, loops, and try-exception block.

Source Code

  • Python

Python

def tictactoe(val):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(val[0], val[1], val[2]))
print('\t_____|_____|_____')

print("\t | |")
print("\t {} | {} | {}".format(val[3], val[4], val[5]))
print('\t_____|_____|_____')

print("\t | |")

print("\t {} | {} | {}".format(val[6], val[7], val[8]))
print("\t | |")
print("\n")

def myscore_board(score_board):
print("\t********************************")
print("\t SCORE BOARD ")
print("\t********************************")

list_of_players = list(score_board.keys())
print("\t ", list_of_players[0], "\t ", score_board[list_of_players[0]])
print("\t ", list_of_players[1], "\t ", score_board[list_of_players[1]])

print("\t********************************\n")

def check_Victory(playerposition, current_player):

solution = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]

for i in solution:
if all(k in playerposition[current_player] for k in i):

return True


return False

def check_Tie(playerposition):
if len(playerposition['X']) + len(playerposition['O']) == 9:
return True
return False

def singlegame(current_player):

val = [' ' for i in range(9)]

playerposition = {'X' : [], 'O' : []}

while True:
tictactoe(val)

try:
print(current_player, "'s turn. Choose the Block for your turn : ", end="")
chance = int(input())
except ValueError:
print("Invalid Input!!! Try Again")
continue


if chance < 1 or chance > 9:
print("Wrong Input!!! Please Try Again")
continue

if val[chance - 1] != ' ':
print("Wrong Input!!! Please Try Again")
continue
val[chance - 1] = current_player

playerposition[current_player].append(chance)


if check_Victory(playerposition, current_player):
tictactoe(val)
print("Congrats!", current_player, " has won!!")
print("\n")
return current_player


if check_Tie(playerposition):
tictactoe(val)
print("Tie")
print("\n")
return 'D'


if current_player == 'X':
current_player = 'O'
else:
current_player = 'X'


if __name__ == "__main__":


print("First Player")
FirstPlayer = input("Name: ")
print("\n")


print("Second Player")
SecondPlayer = input("Name: ")
print("\n")


current_player = FirstPlayer

playerchoice = {'X' : "", 'O' : ""}

opt = ['X', 'O']

score_board = {FirstPlayer: 0, SecondPlayer: 0}
myscore_board(score_board)

while True:

print(current_player, "will make the choice:")
print("Press 1 for X")
print("Press 2 for O")
print("Press 3 to Quit")

try:
the_choice = int(input())
except ValueError:
print("Invalid Input!!! Try Again\n")
continue

if the_choice == 1:
playerchoice['X'] = current_player
if current_player == FirstPlayer:
playerchoice['O'] = SecondPlayer
else:
playerchoice['O'] = FirstPlayer

elif the_choice == 2:
playerchoice['O'] = current_player
if current_player == FirstPlayer:
playerchoice['X'] = SecondPlayer
else:
playerchoice['X'] = FirstPlayer

elif the_choice == 3:
print("The Final Scores")
myscore_board(score_board)
break

else:
print("Try Again\n")

win = singlegame(opt[the_choice - 1])

if win != 'D' :
playerWon = playerchoice[win]
score_board[playerWon] = score_board[playerWon] + 1

myscore_board(score_board)
if current_player == FirstPlayer:
current_player = SecondPlayer
else:
current_player = FirstPlayer

 

Output

First Player
Name: Ninja 1

Second Player
Name: Ninja 2

       ********************************
                SCORE BOARD            
       ********************************
           Ninja 1          0
           Ninja 2          0
       ********************************
Ninja 1 will make the choice:
Press 1 for X
Press 2 for O
Press 3 to Quit
1

            |     |     
            |     |     
       _____|_____|_____
            |     |     
            |     |     
       _____|_____|_____
            |     |     
            |     |     
            |     |    

X 's turn. Choose the Block for your turn : 1

            |     |
         X  |     |
       _____|_____|_____
            |     |
            |     |
       _____|_____|_____
            |     |
            |     |
            |     |

O 's turn. Choose the Block for your turn : 2

            |     |
         X  |  O  |
       _____|_____|_____
            |     |
            |     |
       _____|_____|_____
            |     |
            |     |
            |     |

X 's turn. Choose the Block for your turn : 5

            |     |
         X  |  O  |
       _____|_____|_____
            |     |
            |  X  |
       _____|_____|_____
            |     |
            |     |
            |     |

O 's turn. Choose the Block for your turn : 8

            |     |
         X  |  O  |
       _____|_____|_____
            |     |
            |  X  |
       _____|_____|_____
            |     |
            |  O  |
            |     |

X 's turn. Choose the Block for your turn : 9

            |     |
         X  |  O  |
       _____|_____|_____
            |     |
            |  X  |
       _____|_____|_____
            |     |
            |  O  |  X
            |     |

Congrats! X  has won!!

       ********************************
                SCORE BOARD
       ********************************
           Ninja 1          1
           Ninja 2          0
       ********************************

 

Explanation

We created the tic tac toe simulation with two players. We decided to keep a score board for both the players. Then, one by one, we take the block number for the player's turn. If any pattern matches with the defined ones, that player wins and the game restarts with the second player now playing first.

Also read,  python filename extensions

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What is a Random module in Python?

Python has a built-in module called Random that can produce random integers. These are fake random numbers without actual randomness. Add from random import * to the top of your Python code to access the random module.

What is NLTK in Python?

You can use the Python library NLTK, or Natural Language Toolkit, for NLP. A large portion of the data that you might be analysing is unstructured and contains text that humans can read.  If you need a particular set of algorithms, this library is great. It is most widely used in research and education. It led to numerous advances in text analysis.

Why do we use the os module in Python?

The Python 3 standard library, or stdlib, contains the os module. Irrespective matter whether it is a Windows Platform, Macintosh, or Linux, we can focus on underlying Operating System tasks by using the features of the OS module. The name of the underlying operating system (OS) is obtained using Python's os.name function.

What is the use of the punkt package in NLTK?

PUNKT is an unsupervised trainable model in NLTK, which enables it to be trained on unlabeled data. Unlabeled data is defined as data that has not been labelled with information defining its traits, qualities, or categories. The necessary package for tokenisation is called punkt. 

Conclusion

In this article, we extensively covered valuable and user-friendly Python projects with source code for coders.

We hope this blog has helped you. We recommend you visit our articles:

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Happy Reading!!

Previous article
Snake Game in Python
Next article
Hangman Game in Python
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass