Blog

10 Easy Python Projects with Source Code for Beginners - identicalcloud.com

10 Easy Python Projects with Source Code for Beginners

10 Easy Python Projects with Source Code for Beginners

Python is a powerful and versatile programming language that is used for a wide variety of tasks, from data analysis to web development. It is also a great language for beginners to learn, as it is relatively easy to read and write.

If you are new to Python, one of the best ways to learn is by working on projects. Projects can help you solidify your understanding of the language and its concepts, and they can also be a lot of fun.

In this blog post, I will share 10 easy Python projects that you can start with as a beginner. These projects are all well-documented and have source code available, so you can easily follow along and learn from them.

10 Easy Python Projects for Beginners

  1. FizzBuzz

This is a classic programming interview question that is used to test basic coding skills. The task is to print the numbers from 1 to 100, but with a few exceptions. For multiples of 3, print “Fizz” instead of the number. For multiples of 5, print “Buzz” instead of the number. And for numbers that are multiples of both 3 and 5, print “FizzBuzz”.

Here is a simple Python code to solve the FizzBuzz problem:

def fizzbuzz(n):
  for i in range(1, n + 1):
    if i % 3 == 0 and i % 5 == 0:
      print("FizzBuzz")
    elif i % 3 == 0:
      print("Fizz")
    elif i % 5 == 0:
      print("Buzz")
    else:
      print(i)

fizzbuzz(100)

This code first defines a function called fizzbuzz(). This function takes an integer as input and prints the FizzBuzz sequence up to that number.

The function works by looping through the numbers from 1 to n. For each number, the function checks if it is divisible by 3 and 5. If it is, the function prints “FizzBuzz”. If it is divisible by 3 but not 5, the function prints “Fizz”. If it is divisible by 5 but not 3, the function prints “Buzz”. Otherwise, the function prints the number itself.

The last line of the code calls the fizzbuzz() function with a parameter of 100. This tells the function to print the FizzBuzz sequence up to 100.

When this code is executed, it will print the following output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
...

As you can see, the code correctly prints the FizzBuzz sequence up to 100.

The FizzBuzz problem is a simple task, but it can be a helpful way to learn the basics of programming. It can also help you to practice your logic and problem-solving skills.

  1. Rock, Paper, Scissors

This is a simple game that can be played between two people. The goal is to choose the winning move, which is rock, paper, or scissors. The computer will randomly choose a move, and you will need to choose a move that beats the computer’s move.

Here is a simple Python code to play Rock, Paper, Scissors:

import random

def rock_paper_scissors():
  """Plays a game of Rock, Paper, Scissors."""

  # Get the player's move.
  player_move = input("Rock, Paper, or Scissors? ")

  # Get the computer's move.
  computer_move = random.choice(["rock", "paper", "scissors"])

  # Compare the moves and determine the winner.
  if player_move == computer_move:
    return "Tie"
  elif player_move == "rock" and computer_move == "scissors":
    return "Player wins"
  elif player_move == "scissors" and computer_move == "paper":
    return "Player wins"
  elif player_move == "paper" and computer_move == "rock":
    return "Player wins"
  else:
    return "Computer wins"

print(rock_paper_scissors())

This code first defines a function called rock_paper_scissors(). This function takes no input and returns a string indicating the outcome of the game.

The function works by first getting the player’s move from the user. Then, the function gets the computer’s move by randomly choosing one of the three moves. Finally, the function compares the two moves and determines the winner.

The last line of the code calls the rock_paper_scissors() function and prints the results.

When this code is executed, it will prompt the user to choose between “Rock, Paper, or Scissors?”. The user will then enter their choice. The computer will then randomly choose a move. The code will then compare the two moves and determine the winner. The results will be printed to the console.

For example, if the user chooses “rock” and the computer chooses “scissors”, the code will print “Player wins”. If the user chooses “scissors” and the computer chooses “paper”, the code will print “Computer wins”. If the user chooses “paper” and the computer chooses “rock”, the code will print “Tie”.

The Rock, Paper, Scissors game is a simple game, but it can be a lot of fun. It can also be a helpful way to learn about conditional statements and random numbers in Python.

  1. Dice Rolling Simulator

This project will allow you to simulate the rolling of dice. You can specify the number of dice and the number of sides on each die, and the program will generate random numbers for each roll.

Here is a simple Python code to simulate the rolling of dice:

import random

def roll_dice(number_of_dice, number_of_sides):
  """Rolls a specified number of dice with a specified number of sides."""

  # Generate a list of random numbers.
  random_numbers = random.choices(range(1, number_of_sides + 1), k=number_of_dice)

  # Return the list of random numbers.
  return random_numbers

# Get the number of dice to roll.
number_of_dice = int(input("How many dice would you like to roll? "))

# Get the number of sides on each die.
number_of_sides = int(input("How many sides does each die have? "))

# Roll the dice.
rolled_numbers = roll_dice(number_of_dice, number_of_sides)

# Print the results.
print("The results of the dice roll are:")
for number in rolled_numbers:
  print(number)

This code first defines a function called roll_dice(). This function takes two integers as input: the number of dice to roll and the number of sides on each die. The function returns a list of random numbers.

The function works by first generating a list of random numbers from 1 to number_of_sides. The number of random numbers in the list is equal to number_of_dice.

The last two lines of the code get the number of dice to roll and the number of sides on each die from the user. Then, the code calls the roll_dice() function and prints the results.

When this code is executed, it will prompt the user to enter the number of dice to roll and the number of sides on each die. The user will then enter their choices. The code will then roll the dice and print the results to the console.

For example, if the user enters 2 for the number of dice and 6 for the number of sides, the code will roll two 6-sided dice. The results of the roll will be printed to the console, one number per line.

The Dice Rolling Simulator is a simple program, but it can be a lot of fun. It can also be a helpful way to learn about random numbers in Python.

  1. Password Generator

This project will create a random password of a specified length. The password will be generated using a variety of characters, including letters, numbers, and symbols.

Here is a simple Python code to generate a random password:

import random

def generate_password(length, special_characters=True):
  """Generates a random password of a specified length.

  Args:
    length: The length of the password to generate.
    special_characters: Whether or not to include special characters in the password.

  Returns:
    A random password of the specified length.
  """

  # Create a list of all possible characters.
  characters = []
  if special_characters:
    characters += list(string.ascii_lowercase)
    characters += list(string.ascii_uppercase)
    characters += list(string.digits)
    characters += ['!', '@', '#', '$', '%', '&', '*', '(', ')', '-', '+']
  else:
    characters += list(string.ascii_lowercase)
    characters += list(string.ascii_uppercase)
    characters += list(string.digits)

  # Generate a random password.
  password = ''.join(random.choice(characters) for _ in range(length))

  return password

# Get the length of the password to generate.
length = int(input("How long do you want the password to be? "))

# Generate the password.
password = generate_password(length)

# Print the password.
print("Your password is:", password)

This code first defines a function called generate_password(). This function takes two arguments: the length of the password to generate and whether or not to include special characters in the password. The function returns a random password of the specified length.

The function works by first creating a list of all possible characters. If the special_characters argument is True, the list will include lowercase letters, uppercase letters, digits, and special characters. If the special_characters argument is False, the list will only include lowercase letters and uppercase letters.

The function then generates a random password by randomly choosing characters from the list and joining them together.

The last few lines of the code get the length of the password to generate from the user. Then, the code calls the generate_password() function and prints the results.

When this code is executed, it will prompt the user to enter the length of the password they want to generate. The user will then enter their choice. The code will then generate a random password of the specified length and print it to the console.

For example, if the user enters 8 for the length of the password, the code will generate a random password that is 8 characters long. The password will be a combination of lowercase letters, uppercase letters, and digits.

The Password Generator is a simple program, but it can be a helpful way to generate strong passwords. Strong passwords are important to protect your accounts from being hacked.

  1. Hangman

This is a classic word guessing game. The computer will choose a secret word, and you will need to guess the word by guessing letters. For each incorrect guess, a part of the hangman will be drawn.

Here is a simple Python code to play Hangman:

import random

def hangman(secret_word):
  """Plays a game of Hangman.

  Args:
    secret_word: The secret word to guess.

  Returns:
    The number of guesses the user made before losing.
  """

  # Initialize the game state.
  guessed_letters = []
  wrong_guesses = 0
  blanks = ["_" for _ in secret_word]

  # Loop until the game is over.
  while wrong_guesses < 6 and "_" in blanks:

    # Get the user's guess.
    guess = input("Guess a letter: ").lower()

    # Check if the guess is in the secret word.
    if guess in secret_word:
      # The guess is correct.
      guessed_letters.append(guess)
      for i, letter in enumerate(secret_word):
        if letter == guess:
          blanks[i] = guess
    else:
      # The guess is incorrect.
      wrong_guesses += 1

    # Print the game state.
    print(" ".join(blanks))

  # The game is over.
  if wrong_guesses < 6:
    print("Congratulations! You guessed the word.")
  else:
    print("Sorry, you lost. The word was:", secret_word)

  return wrong_guesses

# Get the secret word.
secret_word = random.choice(["apple", "banana", "cat", "dog", "elephant"])

# Play the game.
wrong_guesses = hangman(secret_word)

# Print the number of guesses the user made.
print("You made", wrong_guesses, "wrong guesses.")

This code first defines a function called hangman(). This function takes a secret word as input and plays a game of Hangman. The function returns the number of guesses the user made before losing.

The function works by first initializing the game state. The game state includes the guessed letters, the wrong guesses, and the blanks. The blanks are a list of underscores, one for each letter in the secret word.

The function then loops until the game is over. In each iteration of the loop, the function gets the user’s guess. The function then checks if the guess is in the secret word. If the guess is correct, the function adds the guess to the list of guessed letters and updates the blanks accordingly. If the guess is incorrect, the function increments the number of wrong guesses.

The function then prints the game state. The game state is printed as a string, with each blank replaced by an underscore.

The function continues looping until the game is over. The game is over if the user has guessed the secret word or if the user has made 6 wrong guesses. If the user has guessed the secret word, the function prints a message congratulating the user. If the user has made 6 wrong guesses, the function prints a message telling the user that they lost.

The last few lines of the code get the secret word and play the game. The number of wrong guesses the user made is then printed to the console.

This is just a simple version of the Hangman game. There are many ways to improve it, such as adding a scoring system, allowing the user to choose the difficulty level, or adding a dictionary of words to choose from.

  1. Calculator

This project will create a simple calculator that can perform basic arithmetic operations, such as addition, subtraction, multiplication, and division.

Here is a simple Python code to create a calculator:

def calculator():
  """A simple calculator."""

  # Get the first number.
  first_number = float(input("Enter the first number: "))

  # Get the operation.
  operation = input("Enter the operation (+, -, *, /): ")

  # Get the second number.
  second_number = float(input("Enter the second number: "))

  # Perform the operation.
  if operation == "+":
    result = first_number + second_number
  elif operation == "-":
    result = first_number - second_number
  elif operation == "*":
    result = first_number * second_number
  elif operation == "/":
    result = first_number / second_number
  else:
    print("Invalid operation.")
    return

  # Print the result.
  print(first_number, operation, second_number, "=", result)

calculator()

This code first defines a function called calculator(). This function takes no input and prints the result of the calculation.

The function works by first getting the first number from the user. Then, the function gets the operation from the user. Finally, the function gets the second number from the user.

The function then performs the operation on the first and second numbers. The result of the operation is then printed to the console.

The last line of the code calls the calculator() function.

When this code is executed, it will prompt the user to enter the first number, the operation, and the second number. The user will then enter their choices. The code will then perform the operation on the first and second numbers and print the result to the console.

For example, if the user enters 10 for the first number, “+” for the operation, and 5 for the second number, the code will print 15.

This is just a simple version of a calculator. There are many ways to improve it, such as allowing the user to choose from a variety of operations or adding a history of calculations.

  1. To-Do List

This project will create a to-do list that allows you to add, remove, and mark items as completed.


Here is a simple Python code to create a to-do list:

import tkinter as tk

# Create the window.
window = tk.Tk()

# Create the listbox.
listbox = tk.Listbox(window)
listbox.pack()

# Add some items to the listbox.
listbox.insert(tk.END, "Buy groceries")
listbox.insert(tk.END, "Clean the house")
listbox.insert(tk.END, "Do the laundry")

# Create the buttons.
add_button = tk.Button(window, text="Add Item", command=add_item)
remove_button = tk.Button(window, text="Remove Item", command=remove_item)

# Pack the buttons.
add_button.pack()
remove_button.pack()

# Start the main loop.
window.mainloop()

def add_item():
  """Adds an item to the to-do list."""

  item = input("Enter an item: ")
  listbox.insert(tk.END, item)

def remove_item():
  """Removes an item from the to-do list."""

  index = listbox.curselection()[0]
  listbox.delete(index)

This code first defines a function called add_item(). This function takes no input and adds an item to the to-do list.

The function works by first getting the item from the user. Then, the function inserts the item into the listbox at the end.

The remove_item() function works similarly. It takes no input and removes the item that is currently selected in the listbox.

The last few lines of the code create the buttons and pack them. The main loop is then started.

When this code is executed, it will create a window with a listbox and two buttons. The listbox will contain the items in the to-do list. The buttons will allow the user to add and remove items from the list.

The user can add items to the list by typing the item into the prompt and pressing Enter. The user can remove items from the list by clicking on the item in the listbox and then clicking on the Remove Item button.

This is just a simple version of a to-do list. There are many ways to improve it, such as allowing the user to mark items as completed or adding a reminder system.

  1. Snake Game

This is a classic arcade game. The goal is to control a snake and eat food without running into the walls or its own tail.

Here is a simple Python code to create a snake game:

import random
import pygame

# Initialize the pygame library.
pygame.init()

# Set the screen size.
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# Set the caption.
pygame.display.set_caption("Snake Game")

# Create the snake.
snake = pygame.Rect(100, 100, 10, 10)

# Create the food.
food = pygame.Rect(random.randint(0, screen_width - 10),
                    random.randint(0, screen_height - 10), 10, 10)

# Set the colors.
black = (0, 0, 0)
white = (255, 255, 255)

# Create the clock.
clock = pygame.time.Clock()

# Start the main loop.
running = True
while running:
  # Get the events.
  events = pygame.event.get()

  # Check for the quit event.
  for event in events:
    if event.type == pygame.QUIT:
      running = False

  # Move the snake.
  snake.x += snake.direction[0]
  snake.y += snake.direction[1]

  # Check if the snake hit the border.
  if snake.x < 0 or snake.x >= screen_width or snake.y < 0 or snake.y >= screen_height:
    running = False

  # Check if the snake ate the food.
  if snake.colliderect(food):
    # Grow the snake.
    snake.width += 10
    # Create new food.
    food.x = random.randint(0, screen_width - 10)
    food.y = random.randint(0, screen_height - 10)

  # Check if the snake ate itself.
  for i in range(len(snake) - 1):
    if snake[i] == snake[-1]:
      running = False

  # Draw the background.
  screen.fill(black)

  # Draw the snake.
  pygame.draw.rect(screen, white, snake)

  # Draw the food.
  pygame.draw.rect(screen, red, food)

  # Update the display.
  pygame.display.flip()

  # Slow down the game.
  clock.tick(10)

This code first imports the necessary libraries. Then, it initializes the pygame library and sets the screen size, caption, and colors.

Next, it creates the snake and the food. Then, it creates the clock.

The main loop then starts. In each iteration of the loop, the code gets the events, checks for the quit event, moves the snake, checks if the snake hit the border or ate the food, and draws the background, snake, and food.

The loop ends when the user quits the game.

This is just a simple version of the Snake game. There are many ways to improve it, such as adding different levels, power-ups, or multiplayer.

  1. Maze Generator

This project will generate a maze of a specified size. The maze can be explored by the user, or it can be solved by a robot.

Here is a simple Python code to generate a maze:

import random

def generate_maze(width, height):
  """Generates a maze of the specified width and height."""

  # Create a grid of walls.
  maze = [[True for _ in range(width)] for _ in range(height)]

  # Start at a random cell.
  current_cell = (random.randint(0, width - 1), random.randint(0, height - 1))

  # While the maze is not complete, randomly choose a neighbor cell and
  # remove the wall between them.
  while not is_maze_complete(maze):
    neighbors = get_neighbors(current_cell, maze)
    next_cell = neighbors[random.randint(0, len(neighbors) - 1)]

    remove_wall(current_cell, next_cell, maze)

    current_cell = next_cell

  return maze

def get_neighbors(cell, maze):
  """Gets the neighbors of the specified cell."""

  neighbors = []

  if cell[0] > 0:
    neighbors.append((cell[0] - 1, cell[1]))
  if cell[0] < len(maze[0]) - 1:
    neighbors.append((cell[0] + 1, cell[1]))
  if cell[1] > 0:
    neighbors.append((cell[0], cell[1] - 1))
  if cell[1] < len(maze) - 1:
    neighbors.append((cell[0], cell[1] + 1))

  return neighbors

def remove_wall(cell1, cell2, maze):
  """Removes the wall between the specified cells."""

  maze[cell1[0]][cell1[1]] = False
  maze[cell2[0]][cell2[1]] = False

def is_maze_complete(maze):
  """Checks if the maze is complete."""

  for row in maze:
    for cell in row:
      if cell:
        return False
  return True

This code first defines a function called generate_maze(). This function takes the width and height of the maze as input and generates a maze of that size.

The function works by first creating a grid of walls. Then, the function randomly chooses a cell and starts exploring the maze from that cell. The function randomly chooses a neighbor cell and removes the wall between them. The function repeats this process until the maze is complete.

The function get_neighbors() gets the neighbors of the specified cell. The function returns a list of the neighbors.

The function remove_wall() removes the wall between the specified cells.

The function is_maze_complete() checks if the maze is complete. The function returns True if the maze is complete and False otherwise.

The last few lines of the code call the generate_maze() function and print the maze.

When this code is executed, it will generate a maze of the specified width and height. The maze will be printed to the console.

This is just a simple version of a maze generator. There are many ways to improve it, such as adding different maze generation algorithms or generating mazes with different features.

  1. Weather App

This project will retrieve weather data from a weather API and display it in a user-friendly way.

Here is a simple Python code to get the current weather in a city:

import requests

def get_weather(city):
  """Gets the current weather in the specified city."""

  # API key.
  API_KEY = "YOUR_API_KEY"

  # Base URL.
  BASE_URL = "https://api.openweathermap.org/data/2.5/weather"

  # Parameters.
  parameters = {
    "q": city,
    "appid": API_KEY,
    "units": "metric"
  }

  # Request the weather data.
  response = requests.get(BASE_URL, params=parameters)

  # Check the response status code.
  if response.status_code == 200:
    # The request was successful.
    data = response.json()
    return data
  else:
    # The request failed.
    print("Error getting weather data.")
    return None

# Get the user's city.
city = input("Enter the city: ")

# Get the weather data.
weather_data = get_weather(city)

# Print the weather data.
print(weather_data)

This code first defines a function called get_weather(). This function takes the city name as input and gets the current weather data for that city.

The function works by first getting the API key from the user. Then, the function constructs the URL for the API request. Finally, the function makes the API request and returns the response data.

The last few lines of the code get the user’s city and call the get_weather() function. The weather data is then printed to the console.

When this code is executed, it will ask the user to enter the city name. The code will then get the current weather data for that city and print it to the console.

This is just a simple version of a weather app. There are many ways to improve it, such as adding different weather data, displaying the weather data in a more user-friendly way, or making the app more interactive.

These 10 easy Python projects offer an excellent starting point for beginners to practice their coding skills, gain confidence, and have fun while learning. By building these projects and exploring the source code, you’ll gain a deeper understanding of Python syntax, concepts, and best practices. As you progress, don’t hesitate to modify and expand these projects to make them uniquely yours. Happy coding!

Leave a Comment