Logo
Published on

Beginner Python Projects That Anyone Can Start Coding Right Away

Authors

It always will be an unforgettable feeling, to write your first code and then run it successfully. However, times have changed. Now, we're above the initial programming languages that required several lines of code just to define an integer.

With advanced languages like Python, you can code freely without letting the overwhelming thought of defining an entity in your code. Speaking of which, did you know that Python is the second most popular programming language in the entire world?

Yes, that's right, it has a manifold of applications from gaming to social media and streaming platforms like YouTube and Instagram. What's interesting is that this language does not require a compiler and is also Google's official programming language!

With these fascinating facts, you must be intrigued about beginning your journey with Python. Fortunately, if you've followed The Zen of Python, then be ready to be amazed at some of the most intriguing beginner-level Python coding projects that you can begin with.

All you need is your game face, a laptop/ PC, a coding platform, a good internet to you know find the code or watch tutorials online, and well, the attitude to code, and you can get started. We don't know about the rest but we recommend connecting with Xfinity customer service and acquiring a solid internet. With that settled, let's begin with some beginner-level Python projects:

1. Hangman

We're familiar with the original Hangman, right? But what if this game was built in Python? Yes, that's right! This is an easy project to begin with. For this, you'll need to write the following code:

#importing the time module
import time
#welcoming the user
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
#wait for 1 second
time.sleep(1)
print ("Start guessing...")
time.sleep(0.5)
#here we set the secret. You can select any word to play with.
word = ("secret")
#creates an variable with an empty value
guesses = ''
#determine the number of turns
turns = 10
# Create a while loop
#check if the turns are more than zero
while turns > 0:
# make a counter that starts with zero
failed = 0
# for every character in secret_word
for char in word:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print (char,end=""),
else:
# if not found, print a dash
print ("_",end=""),
# and increase the failed counter with one
failed += 1
# if failed is equal to zero
# print You Won
if failed == 0:
print ("You won")
# exit the script
break
# ask the user go guess a character
guess = input("guess a character:")
# set the players guess to guesses
guesses += guess
# if the guess is not found in the secret word
if guess not in word:
# turns counter decreases with 1 (now 9)
turns -= 1
# print wrong
print ("Wrong")
# how many turns are left
print ("You have", + turns, 'more guesses' )
# if the turns are equal to zero
if turns == 0:
# print "You Lose"
print ("You Lose" )

Here's how the code will work:

  • The code will ask for the user's name through the input() method and add it to the string.
  • The code will then choose a word and ask the user to guess while defining the maximum number of available guesses.
  • Using 'while loop', the code will repeat asking the user to guess the word until the word is guessed or the attempts have expired.
  • If the word is guessed within the loop, it will be displayed in the result alongside the remaining attempts.
  • If not, then the loop will be concluded showing that the user failed to guess the word.

2. Rock, Paper, Scissors

Ah yes, the iconic rock, paper scissors to decide who's going to do the dishes or who loses the bet. Well, if you're looking to begin with Python, you might as well have some fun, and what good way than to code a game and try to win against your own creation? Well then, to get started, here's the code for this game:

import random
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"nYou chose {user_action}, computer chose {computer_action}.n")
if user_action == computer_action:
print(f"Both players selected {user_action}. It's a tie!")
elif user_action == "rock":
if computer_action == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif user_action == "paper":
if computer_action == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")
elif user_action == "scissors":
if computer_action == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")

Here's how it'll work:

  • First, you'll need to import the module for simulating computer choices using the 'import' command with 'random' followed by importing 'user_action'.
  • Next, you can add 'random.choice' that will enable the computer to make a random choice by defining a string of variables 'possible_actions'.
  • Once done, you'll need to add conditional statements to determine the winner, and voila! Your rock, paper, scissors game in Python is ready!

3. Mad Libs Generator

Although this is an interactive game for kids, still, it's still one of the easiest coding projects to get started with Python. The good thing is that it'll enable you to use some of the most commonly used elements in the language. Here's what the code will be like:

from Tkinter import *
root = Tk()
root.geometry('300x300')
root.title('DataFlair-Mad Libs Generator')
Label(root, text= 'Mad Libs Generator n Have Fun!' , font = 'arial 20 bold').pack()
Label(root, text = 'Click Any One :', font = 'arial 15 bold').place(x=40, y=80)
def madlib1():
animals= input('enter a animal name : ')
profession = input('enter a profession name: ')
cloth = input('enter a piece of cloth name: ')
things = input('enter a thing name: ')
name= input('enter a name: ')
place = input('enter a place name: ')
verb = input('enter a verb in ing form: ')
food = input('food name: ')
print('say ' + food + ', the photographer said as the camera flashed! ' + name + ' and I had gone to ' + place +' to get our photos taken on my birthday. The first photo we really wanted was a picture of us dressed as ' + animals + ' pretending to be a ' + profession + '. when we saw the second photo, it was exactly what I wanted. We both looked like ' + things + ' wearing ' + cloth + ' and ' + verb + ' - exactly what I had in mind')
def madlib2():
adjactive = input('enter adjective : ')
color = input('enter a color name : ')
thing = input('enter a thing name :')
place = input('enter a place name : ')
person= input('enter a person name : ')
adjactive1 = input('enter a adjactive : ')
insect= input('enter a insect name : ')
food = input('enter a food name : ')
verb = input('enter a verb name : ')
print('Last night I dreamed I was a ' +adjactive+ ' butterfly with ' + color+ ' splocthes that looked like '+thing+ ' .I flew to ' + place+ ' with my bestfriend and '+person+ ' who was a '+adjactive1+ ' ' +insect +' .We ate some ' +food+ ' when we got there and then decided to '+verb+ ' and the dream ended when I said - lets ' +verb+ '.')
def madlib3():
person = input('enter person name: ')
color = input('enter color : ')
foods = input('enter food name : ')
adjective = input('enter aa adjective name: ')
thing = input('enter a thing name : ')
place = input('enter place : ')
verb = input('enter verb : ')
adverb = input('enter adverb : ')
food = input('enter food name: ')
things = input('enter a thing name : ')
print('Today we picked apple from '+person+ "'s Orchard. I had no idea there were so many different varieties of apples. I ate " +color+ ' apples straight off the tree that tested like '+foods+ '. Then there was a '+adjective+ ' apple that looked like a ' + thing + '.When our bag were full, we went on a free hay ride to '+place+ ' and back. It ended at a hay pile where we got to ' +verb+ ' ' +adverb+ '. I can hardly wait to get home and cook with the apples. We are going to make appple '+food+ ' and '+things+' pies!.')

Here's how the code will work:

  • The tricky part is to create a display window that will run the code in a game-like interface. For that purpose, we're using the Tkinter module.
  • Next, the code will define functions that will comprise functions. These functions will define entities such as animals, things, name, etc. that we want to answer.
  • Next, we'll define the entities using the input() function that will ask the user to input information, which then will be printed using the print() function.
  • Once done, we move to the button creation via the button() widget so that everything operates via click and only inputs are requested. Setting this together and our Mad Libs generator is ready!

4. Tic Tac Toe

The classic tic-tac-toe game can also be created using Python. This is somewhat an advanced level of coding since you need to create several elements for the game as well as add conditional statements for combinations and create grid lines for the game as well.

For this, you'll need to dive into some important prerequisites, including the GUI programming with Tkinter, loops, Model-view-controller, etc. Let's check out its code below:

import tkinter as tk
from itertools import cycle
from tkinter import font
from typing import NamedTuple
class Player(NamedTuple):
label: str
color: str
class Move(NamedTuple):
row: int
col: int
label: str = ""
BOARD_SIZE = 3
DEFAULT_PLAYERS = (
Player(label="X", color="blue"),
Player(label="O", color="green"),
)
class TicTacToeGame:
def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE):
self._players = cycle(players)
self.board_size = board_size
self.current_player = next(self._players)
self.winner_combo = []
self._current_moves = []
self._has_winner = False
self._winning_combos = []
self._setup_board()
def _setup_board(self):
self._current_moves = [
[Move(row, col) for col in range(self.board_size)]
for row in range(self.board_size)
]
self._winning_combos = self._get_winning_combos()
def _get_winning_combos(self):
rows = [
[(move.row, move.col) for move in row]
for row in self._current_moves
]
columns = [list(col) for col in zip(*rows)]
first_diagonal = [row[i] for i, row in enumerate(rows)]
second_diagonal = [col[j] for j, col in enumerate(reversed(columns))]
return rows + columns + [first_diagonal, second_diagonal]
def toggle_player(self):
"""Return a toggled player."""
self.current_player = next(self._players)
def is_valid_move(self, move):
"""Return True if move is valid, and False otherwise."""
row, col = move.row, move.col
move_was_not_played = self._current_moves[row][col].label == ""
no_winner = not self._has_winner
return no_winner and move_was_not_played
def process_move(self, move):
"""Process the current move and check if it's a win."""
row, col = move.row, move.col
self._current_moves[row][col] = move
for combo in self._winning_combos:
results = set(self._current_moves[n][m].label for n, m in combo)
is_win = (len(results) == 1) and ("" not in results)
if is_win:
self._has_winner = True
self.winner_combo = combo
break
def has_winner(self):
"""Return True if the game has a winner, and False otherwise."""
return self._has_winner
def is_tied(self):
"""Return True if the game is tied, and False otherwise."""
no_winner = not self._has_winner
played_moves = (
move.label for row in self._current_moves for move in row
)
return no_winner and all(played_moves)
def reset_game(self):
"""Reset the game state to play again."""
for row, row_content in enumerate(self._current_moves):
for col, _ in enumerate(row_content):
row_content[col] = Move(row, col)
self._has_winner = False
self.winner_combo = []
class TicTacToeBoard(tk.Tk):
def __init__(self, game):
super().__init__()
self.title("Tic-Tac-Toe Game")
self._cells = {}
self._game = game
self._create_menu()
self._create_board_display()
self._create_board_grid()
def _create_menu(self):
menu_bar = tk.Menu(master=self)
self.config(menu=menu_bar)
file_menu = tk.Menu(master=menu_bar)
file_menu.add_command(label="Play Again", command=self.reset_board)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=quit)
menu_bar.add_cascade(label="File", menu=file_menu)
def _create_board_display(self):
display_frame = tk.Frame(master=self)
display_frame.pack(fill=tk.X)
self.display = tk.Label(
master=display_frame,
text="Ready?",
font=font.Font(size=28, weight="bold"),
)
self.display.pack()
def _create_board_grid(self):
grid_frame = tk.Frame(master=self)
grid_frame.pack()
for row in range(self._game.board_size):
self.rowconfigure(row, weight=1, minsize=50)
self.columnconfigure(row, weight=1, minsize=75)
for col in range(self._game.board_size):
button = tk.Button(
master=grid_frame,
text="",
font=font.Font(size=36, weight="bold"),
fg="black",
width=3,
height=2,
highlightbackground="lightblue",
)
self._cells[button] = (row, col)
button.bind("<ButtonPress-1>", self.play)
button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
def play(self, event):
"""Handle a player's move."""
clicked_btn = event.widget
row, col = self._cells[clicked_btn]
move = Move(row, col, self._game.current_player.label)
if self._game.is_valid_move(move):
self._update_button(clicked_btn)
self._game.process_move(move)
if self._game.is_tied():
self._update_display(msg="Tied game!", color="red")
elif self._game.has_winner():
self._highlight_cells()
msg = f'Player "{self._game.current_player.label}" won!'
color = self._game.current_player.color
self._update_display(msg, color)
else:
self._game.toggle_player()
msg = f"{self._game.current_player.label}'s turn"
self._update_display(msg)
def _update_button(self, clicked_btn):
clicked_btn.config(text=self._game.current_player.label)
clicked_btn.config(fg=self._game.current_player.color)
def _update_display(self, msg, color="black"):
self.display["text"] = msg
self.display["fg"] = color
def _highlight_cells(self):
for button, coordinates in self._cells.items():
if coordinates in self._game.winner_combo:
button.config(highlightbackground="red")
def reset_board(self):
"""Reset the game's board to play again."""
self._game.reset_game()
self._update_display(msg="Ready?")
for button in self._cells.keys():
button.config(highlightbackground="lightblue")
button.config(text="")
button.config(fg="black")
def main():
"""Create the game's board and run its main loop."""
game = TicTacToeGame()
board = TicTacToeBoard(game)
board.mainloop()
if __name__ == "__main__":
main()

Before running the code, ensure that you're using the updated Tkinter version with the standard Python library. Version 8.6 or greater can be used for this purpose. You can check for the version using the following code:

import tkinter
tkinter.TkVersion
8.6

The code will run in the following manner:

  • Using the TK class, you'll create the main window for your Tkinter app where you'll add the facing grid and frame comprising cells.
  • For that, you'll need to import Tkinter and objects accordingly. The primary class named TicTacToeBoard will inherit from Tk forming the GUI window we need.
  • The ._cells will hold an empty dictionary initially so that it can map the buttons on the grid. These will be integers reflecting the row and the column.
  • Using the Frame widget, you'll create a display panel and illustrate the information using the Label widget.
  • The .pack() geometry manager will place the object on the main window's top border. This is to ensure that the width remains the same even if the user resizes the window.
  • You need to use the Label Object to illustrate messages such as ready? This label must be inside the frame; hence, the master argument will be set for this.
  • The Frame object will hold the cell grid for the game while the .pack() geometry manager will place the frame on the main window.
  • You will need to start a loop as well to define rows and columns in the cells.
  • This is followed by Button Object for all grid cells that are added to the .cells dictionary expressing the coordinates in terms of row and column

Closing Thoughts

These are some of the basic projects that you can work with using Python. Remember, the prerequisite is that you have beginner-level expertise in the common elements used for the language. Once you grasp those intelligently do, you can move forward with these amazing games and enjoy your time coding!