Table of Contents
AI, ML, and Data Science dominate many fields and industries today - all of them make heavy use of the Python programming language in some way or another.
Becoming a master in Python can open many doors in your career and land in some of the best opportunities across the planet. No matter wherever you rate yourself in the Python skill, working on Python projects is a surefire way to boost your skills and build up your profile. While Python books and Python tutorials are helpful, nothing beats getting your hands dirty with actual coding.
We list several Python projects for beginners for you to challenge yourself and get better at Python coding.
Top 10 Python Project Ideas for Beginners
1. Mad Libs Generator
This Python beginner project is a good start for beginners as it makes use of strings, variables, and concatenation. The Mad Libs Generator manipulates input data, which could be anything: an adjective, a pronoun, or verb. After taking in the input, the program takes the data and arranges it to build a story. This is a very cool Python project to try out if you’re new to coding.
Sample Code:
""" Mad Libs Generator----------------------------------------"""#Loop back to this point once code finishesloop = 1while (loop < 10):# All the questions that the program asks the usernoun = input("Choose a noun: ")p_noun = input("Choose a plural noun: ")noun2 = input("Choose a noun: ")place = input("Name a place: ")adjective = input("Choose an adjective (Describing word): ")noun3 = input("Choose a noun: ")#Displays the story based on the users inputprint ("------------------------------------------")print ("Be kind to your",noun,"- footed", p_noun)print ("For a duck may be somebody's", noun2,",")print ("Be kind to your",p_noun,"in",place)print ("Where the weather is always",adjective,".")print ()print ("You may think that is this the",noun3,",")print ("Well it is.")print ("------------------------------------------")# Loop back to "loop = 1"loop = loop + 1
2. Number Guessing
This project is a fun game that generates a random number in a certain specified range and the user must guess the number after receiving hints. Every time a user’s guess is wrong they are prompted with more hints to make it easier — at the cost of reducing the score.
The program also requires functions to check if an actual number is entered by the user, and finds the difference between the two numbers.
Sample Code:
""" Number Guessing Game----------------------------------------"""import randomattempts_list = []def show_score():if len(attempts_list) <= 0:print("There is currently no high score, it's yours for the taking!")else:print("The current high score is {} attempts".format(min(attempts_list)))def start_game():random_number = int(random.randint(1, 10))print("Hello traveler! Welcome to the game of guesses!")player_name = input("What is your name? ")wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))# Where the show_score function USED to beattempts = 0show_score()while wanna_play.lower() == "yes":try:guess = input("Pick a number between 1 and 10 ")if int(guess) < 1 or int(guess) > 10:raise ValueError("Please guess a number within the given range")if int(guess) == random_number:print("Nice! You got it!")attempts += 1attempts_list.append(attempts)print("It took you {} attempts".format(attempts))play_again = input("Would you like to play again? (Enter Yes/No) ")attempts = 0show_score()random_number = int(random.randint(1, 10))if play_again.lower() == "no":print("That's cool, have a good one!")breakelif int(guess) > random_number:print("It's lower")attempts += 1elif int(guess) < random_number:print("It's higher")attempts += 1except ValueError as err:print("Oh no!, that is not a valid value. Try again...")print("({})".format(err))else:print("That's cool, have a good one!")if __name__ == '__main__':start_game()
3. Rock Paper Scissors
This rock paper scissors program uses a number of functions so this is a good way of getting that critical concept under your belt.
- Random function: to generate rock, paper, or scissors.
- Valid function: to check the validity of the move.
- Result function: to declare the winner of the round.
- Scorekeeper: to keep track of the score.
The program requires the user to make the first move before it makes a move. The input could be a string or an alphabet representing either rock, paper or scissors. After evaluating the input string, a winner is decided by the result function and the score of the round is updated by the scorekeeper function.
Sample Code:
""" Rock Paper Scissors----------------------------------------"""import randomimport osimport reos.system('cls' if os.name=='nt' else 'clear')while (1 < 2):print ("\n")print ("Rock, Paper, Scissors - Shoot!")userChoice = input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ")if not re.match("[SsRrPp]", userChoice):print ("Please choose a letter:")print ("[R]ock, [S]cissors or [P]aper.")continue# Echo the user's choiceprint ("You chose: " + userChoice)choices = ['R', 'P', 'S']opponenetChoice = random.choice(choices)print ("I chose: " + opponenetChoice)if opponenetChoice == str.upper(userChoice):print ("Tie! ")#if opponenetChoice == str("R") and str.upper(userChoice) == "P"elif opponenetChoice == 'R' and userChoice.upper() == 'S':print ("Scissors beats rock, I win! ")continueelif opponenetChoice == 'S' and userChoice.upper() == 'P':print ("Scissors beats paper! I win! ")continueelif opponenetChoice == 'P' and userChoice.upper() == 'R':print ("Paper beat rock, I win!")continueelse:print ("You win!")
4. Dice Roll Generator
This dice roll generator is a fairly simple program that makes use of the random function to simulate dice rolls. You can change the maximum value to any number, making it possible to simulate polyhedral dice used in many board games and roleplaying games.
Sample Code:
import random#Enter the minimum and maximum limits of the dice rolls belowmin_val = 1max_val = 6#the variable that stores the user’s decisionroll_again = "yes"#The dice roll loop if the user wants to continuewhile roll_again == "yes" or roll_again == "y":print("Dices rolling...")print("The values are :")#Printing the randomly generated variable of the first diceprint(random.randint(min_val, max_val))#Printing the randomly generated variable of the second diceprint(random.randint(min_val, max_val))#Here the user enters yes or y to continue and any other input ends the programroll_again = input("Roll the Dices Again?")
5. Binary Search Algorithm
The binary search algorithm is a very important one, and requires you to create a list of numbers between 0 and an upper limit, with every succeeding number having a difference of 2 between them.
When the user inputs a random number to be searched the program begins its search by dividing the list into two halves. First, the first half is searched for the required number and if found, the other half is rejected and vice versa. The search continues until the number is found or the subarray size becomes zero.
Sample Code:
# Recursive Binary Search algorithm in Pythondef binarySearch(array, x, low, high):if high >= low:mid = low + (high - low)//2# If found at mid, return the valueif array[mid] == x:return mid# Search the first halfelif array[mid] > x:return binarySearch(array, x, low, mid-1)# Search the second halfelse:return binarySearch(array, x, mid + 1, high)else:return -1array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]x = int(input("Enter a number between 1 and 10:"))result = binarySearch(array, x, 0, len(array)-1)if result != -1:print("Element is present at position" + str(result))else:print("Element not found")
6. Calculator
This project teaches you to design a graphical interface and is a good way to get familiar with a library like Tkinter. This library lets you create buttons to perform different operations and display results on the screen.
Sample Code:
# Calculatordef addition ():print("Addition")n = float(input("Enter the number: "))t = 0 #Total number enterans = 0while n != 0:ans = ans + nt+=1n = float(input("Enter another number (0 to calculate): "))return [ans,t]def subtraction ():print("Subtraction");n = float(input("Enter the number: "))t = 0 #Total number entersum = 0while n != 0:ans = ans - nt+=1n = float(input("Enter another number (0 to calculate): "))return [ans,t]def multiplication ():print("Multiplication")n = float(input("Enter the number: "))t = 0 #Total number enterans = 1while n != 0:ans = ans * nt+=1n = float(input("Enter another number (0 to calculate): "))return [ans,t]def average():an = []an = addition()t = an[1]a = an[0]ans = a / treturn [ans,t]# main...while True:list = []print(" My first python program!")print(" Simple Calculator in python by Malik Umer Farooq")print(" Enter 'a' for addition")print(" Enter 's' for substraction")print(" Enter 'm' for multiplication")print(" Enter 'v' for average")print(" Enter 'q' for quit")c = input(" ")if c != 'q':if c == 'a':list = addition()print("Ans = ", list[0], " total inputs ",list[1])elif c == 's':list = subtraction()print("Ans = ", list[0], " total inputs ",list[1])elif c == 'm':list = multiplication()print("Ans = ", list[0], " total inputs ",list[1])elif c == 'v':list = average()print("Ans = ", list[0], " total inputs ",list[1])else:print ("Sorry, invilid character")else:break
7. Alarm Clock
This Command Line Interface (CLI) Python application is a good step up for a beginner developer. More than just setting off an alarm, this program allows certain YouTube links to be added to a text file. When a user sets an alarm, the code picks a random video and starts playing it.
Sample Code:
""" Alarm Clock----------------------------------------"""import datetimeimport osimport timeimport randomimport webbrowser# If video URL file does not exist, create oneif not os.path.isfile("youtube_alarm_videos.txt"):print('Creating "youtube_alarm_videos.txt"...')with open("youtube_alarm_videos.txt", "w") as alarm_file:alarm_file.write("https://www.youtube.com/watch?v=anM6uIZvx74")def check_alarm_input(alarm_time):"""Checks to see if the user has entered in a valid alarm time"""if len(alarm_time) == 1: # [Hour] Formatif alarm_time[0] < 24 and alarm_time[0] >= 0:return Trueif len(alarm_time) == 2: # [Hour:Minute] Formatif alarm_time[0] < 24 and alarm_time[0] >= 0 and \alarm_time[1] < 60 and alarm_time[1] >= 0:return Trueelif len(alarm_time) == 3: # [Hour:Minute:Second] Formatif alarm_time[0] < 24 and alarm_time[0] >= 0 and \alarm_time[1] < 60 and alarm_time[1] >= 0 and \alarm_time[2] < 60 and alarm_time[2] >= 0:return Truereturn False# Get user input for the alarm timeprint("Set a time for the alarm (Ex. 06:30 or 18:30:00)")while True:alarm_input = input(">> ")try:alarm_time = [int(n) for n in alarm_input.split(":")]if check_alarm_input(alarm_time):breakelse:raise ValueErrorexcept ValueError:print("ERROR: Enter time in HH:MM or HH:MM:SS format")# Convert the alarm time from [H:M] or [H:M:S] to secondsseconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Secondalarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])# Get the current time of day in secondsnow = datetime.datetime.now()current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])# Calculate the number of seconds until alarm goes offtime_diff_seconds = alarm_seconds - current_time_seconds# If time difference is negative, set alarm for next dayif time_diff_seconds < 0:time_diff_seconds += 86400 # number of seconds in a day# Display the amount of time until the alarm goes offprint("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))# Sleep until the alarm goes offtime.sleep(time_diff_seconds)# Time for the alarm to go offprint("Wake Up!")# Load list of possible video URLswith open("youtube_alarm_videos.txt", "r") as alarm_file:videos = alarm_file.readlines()# Open a random video from the listwebbrowser.open(random.choice(videos))
8. Tic-Tac-Toe
Tic-Tac-Toe is a two-player game that involves a nine-square grid. Each player marks their space with an O or an X alternately. The player who manages to mark three Os or Xs diagonally, horizontally, or vertically wins. Each player must block their opponent while attempting to make their chain. For this project, we use the Pygame Python library.
Sample Code:
""" Tic Tac Toe----------------------------------------"""import randomimport sysboard=[i for i in range(0,9)]player, computer = '',''# Corners, Center and Others, respectivelymoves=((1,7,3,9),(5,),(2,4,6,8))# Winner combinationswinners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))# Tabletab=range(1,10)def print_board():x=1for i in board:end = ' | 'if x%3 == 0:end = ' \n'if i != 1: end+='---------\n';char=' 'if i in ('X','O'): char=i;x+=1print(char,end=end)def select_char():chars=('X','O')if random.randint(0,1) == 0:return chars[::-1]return charsdef can_move(brd, player, move):if move in tab and brd[move-1] == move-1:return Truereturn Falsedef can_win(brd, player, move):places=[]x=0for i in brd:if i == player: places.append(x);x+=1win=Truefor tup in winners:win=Truefor ix in tup:if brd[ix] != player:win=Falsebreakif win == True:breakreturn windef make_move(brd, player, move, undo=False):if can_move(brd, player, move):brd[move-1] = playerwin=can_win(brd, player, move)if undo:brd[move-1] = move-1return (True, win)return (False, False)# AI goes heredef computer_move():move=-1# If I can win, others do not matter.for i in range(1,10):if make_move(board, computer, i, True)[1]:move=ibreakif move == -1:# If player can win, block him.for i in range(1,10):if make_move(board, player, i, True)[1]:move=ibreakif move == -1:# Otherwise, try to take one of desired places.for tup in moves:for mv in tup:if move == -1 and can_move(board, computer, mv):move=mvbreakreturn make_move(board, computer, move)def space_exist():return board.count('X') + board.count('O') != 9player, computer = select_char()print('Player is [%s] and computer is [%s]' % (player, computer))result='%%% Deuce ! %%%'while space_exist():print_board()print('#Make your move ! [1-9] : ', end='')move = int(input())moved, won = make_move(board, player, move)if not moved:print(' >> Invalid number ! Try again !')continueif won:result='*** Congratulations ! You won ! ***'breakelif computer_move()[1]:result='=== You lose ! =='break;print_board()print(result)
9. Countdown Timer
This countdown timer program takes in the number of seconds as input, and countdowns second by second until it displays a message. It implements the time module, which is worth knowing about and a fairly easy module to make of.
Sample Code:
import time# The countdown function is defined belowdef countdown(t):while t:mins, secs = divmod(t, 60)timer = '{:02d}:{:02d}'.format(mins, secs)print(timer, end="\r")time.sleep(1)t -= 1print('Lift off!')# Ask the user to enter the countdown period in secondst = input("Enter the time in seconds: ")# function callcountdown(int(t))
10. Merge Sort
Sorting is an important concept to have in any programmer’s toolbelt, and merge sort is a particularly important one. While there are sorting functions like insertion sort, bubble sort and selection sort, merge sort is worth knowing because it is effective for sorting large amounts of data.
Sample Code:
def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Find the midpoint and divide the list into two
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
# Merge the sorted halves
def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print(merge_sort(unsorted_list))
Conclusion
There you go — ten beginner Python projects that can be a lot of fun at the same time. These projects put your theoretical python learning to the test and help better your practical handling of Python knowledge.
If you want a good course on building Python applications, Python Mega Course: Build 10 Real World Applications is a highly rated and recommended one. You should also look at Python Interview Questions for further preparation.
Frequently Asked Questions
1. What Python Projects Should I Build to Get a Job?
The truth is you need to do a lot more than these beginner projects to get a job. First, you should focus on getting the basics. Projects like the merge sort and calculator go over some of these important concepts. When you hit the intermediate level, you can begin focusing on projects that will help you land a job.
2. What are Some Good Python Projects?
For beginners, the merge sort, calculator, tic-tac-toe, and binary search algorithm projects are good places to start. However, all the projects in this list are worth implementing, as they all have something to offer.
3. How Do I Start my First Python Project?
By actually coding! There’s no other way to do it. You start your first Python project by actually trying the code out.
People are also reading:
- Best Python Courses
- Best Python Certifications
- Best Python IDE
- Best Python Compilers
- Best Python Interpreters
- Best way to learn python
- How to Run a Python Script?
- What is PyCharm?
- Python for Data Science
- Top Python Libraries
FAQs
What are good beginner coding projects? ›
- Build a Simple Application. ...
- Develop a Basic Game Using JavaScript. ...
- Create a Simple Tool. ...
- Build a Basic Website Using HTML and CSS. ...
- Contribute to an Open-Source Project. ...
- Develop Your Own Chess Game in Java. ...
- Create Your Own Calculator. ...
- Redesign a Website.
- Animate the Galaxy: ...
- Create a chatbot using python: (Trending) ...
- Mouse control with hand gestures: (Trending) ...
- Image caption generation: ...
- Make an art piece: ...
- Code a Rock, Paper, Scissors game: ...
- Spam Email Detection: (Trending) ...
- Make your calculator:
- Break the Project Down into Smaller Units. Photo by Markus Spiske / Unsplash. ...
- Write Your First Line of Code and Get Stuck ...
- No Project is Perfect – Including Google ...
- Every Project is Built on Other Projects. ...
- Don't Be Afraid to Google. ...
- You'll Always Get Stuck – and That's OK.
- Write a blog post. A blog post is a web article you can write on any topic that interests you. ...
- Write a poem. ...
- Write a short story. ...
- Create custom bookmarks. ...
- Create a poster. ...
- Create digital artwork. ...
- Take a photo series. ...
- Create a vision board.
Python can build a wide range of different data visualizations, like line and bar graphs, pie charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and Keras.
Can I make games with Python? ›Creating your own computer games in Python is a great way to learn the language. To build a game, you'll need to use many core programming skills. The kinds of skills that you'll see in real-world programming.
What should I create with Python? ›You can use Python to create arcade games, adventure games, and puzzle games that you can deploy within a few hours. You can also code classic games, such as hangman, tic-tac-toe, rock paper scissors, and more with your newly acquired programming skills.
What code is Python games? ›Video games
Battlefield 2 uses Python for all of its add-ons and a lot of its functionality. Disney's Toontown Online is written in Python and uses Panda3D for graphics. Eve Online uses Stackless Python. Mount & Blade is written in Python.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
How do you write hello in Python? ›How do you write hello world python? The easiest way to display anything on the output screen in the python programming screen is by using the print() function. To print hello world, we can design a python hello world program that will print “Hello world” to the output screen using the print() function.
How do I make a Python script? ›
Create a Python file
In the Project tool window, select the project root (typically, it is the root node in the project tree), right-click it, and select File | New .... Select the option Python File from the context menu, and then type the new filename. PyCharm creates a new Python file and opens it for editing.
- Download Thonny IDE.
- Run the installer to install Thonny on your computer.
- Go to: File > New. Then save the file with .py extension. ...
- Write Python code in the file and save it. ...
- Then Go to Run > Run current script or simply click F5 to run it.
Using python3, the hangman game was created. This is a two player game where the first player inputs a word, and the second player repeatedly guesses letter by letter. Code includes visuals as well. Hangman.py. import sys.
What is hangman game in Python? ›Using python3, the hangman game was created. This is a two player game where the first player inputs a word, and the second player repeatedly guesses letter by letter. Code includes visuals as well. Hangman.py. import sys.
How do Python skills make money? ›- Get a Developer Job.
- Create a StartUp.
- Freelancing.
- Teach Coding Online.
- Create a YouTube channel and Monetize it.
- Create a Blog and Monetize it.
- Join Coding Contests.
Mad libs generator is a fun game that is usually played by kids. In this python game user has to enter substitutes for blanks in the story without knowing the story. It will be fun to read aloud the stories after filling the blanks.
What is the hardest word to spell in Hangman? ›The hardest word to guess in hangman, according to science, is: Jazz. Composed of 75 percent uncommon letters (J and Z) and allowing only three chances at picking correctly, jazz is the perfect storm of Hangman trickery. It's kind of fitting, really. They say jazz is all about the notes they don't play.
How do you print in Python? ›Python print() Function
The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.
In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.).
How do I get paid for coding? ›- Upwork/Fiverr. ...
- Create a Course on Udemy. ...
- Start a YouTube Channel. ...
- Create Your Own Website/Blog. ...
- Make an App. ...
- Sell Themes/Templates. ...
- Create a Plugin on WordPress or Shopify. ...
- Sell eBooks.
Can I sell my Python code? ›
Create a sales page
To be able to sell your Python application you can create a web page for your app where you will host the executable package. Then you could create a way for the customer to enter their payment info and after valid payment have it allow them to download the app.
💻 Join a Freelancing Site
Another way to find paid beginner programming jobs as you're learning to code is by using freelancing sites that connect you to coding projects and clients, such as Fiverr, Upwork and Freelancer. Start with simpler coding jobs and keep your bids low in the beginning.
Python provides a built-in library called pygame, which used to develop the game. Once we understand the basic concepts of Python programming, we can use the pygame library to make games with attractive graphics, suitable animation, and sound. Pygame is a cross-platform library that is used to design video games.
How do I run a Python script? ›To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
What are the important programs in Python? ›- Python Program to Print Hello world!
- Python Program to Add Two Numbers.
- Python Program to Find the Square Root.
- Python Program to Calculate the Area of a Triangle.
- Python Program to Solve Quadratic Equation.
- Python Program to Swap Two Variables.
- Python Program to Generate a Random Number.
Python Code:
import random target_num, guess_num = random. randint(1, 10), 0 while target_num != guess_num: guess_num = int(input('Guess a number between 1 and 10 until you get it right : ')) print('Well guessed!')
Mad Libs (a play on ad lib, from Latin ad libitum - as you wish) is a word game where one player prompts another for a list of words to substitute for blanks in a story; these word substitutions have a humorous effect when the resulting story is then read aloud.
How do you write a Mad Lib? ›- Write a story.
- Erase random words.
- Under those new blank spaces, add labels for parts of speech (noun, verb, adjective, adverb, etc)
- Have a friend fill in the blanks using their own words.
- Read your very own story.