Fundamentals 11 min read

Five Beginner Python Projects: Number Guessing Game, Calculator, Word Frequency Counter, Ledger, and Simple Chatroom

This article presents five beginner‑friendly Python projects— a number‑guessing game, a calculator, a word‑frequency counter, a simple ledger, and a chatroom—each with background, implementation steps, and complete source code to help new programmers practice core language concepts.

DevOps Operations Practice
DevOps Operations Practice
DevOps Operations Practice
Five Beginner Python Projects: Number Guessing Game, Calculator, Word Frequency Counter, Ledger, and Simple Chatroom

1. Number Guessing Game

Project background: A classic beginner project that practices basic Python syntax, control flow, and logic by having the player guess a randomly generated number.

Implementation steps:

Generate a random number using the random module.

Prompt the user for input.

Compare the guess with the target number and give feedback.

Repeat until the correct number is guessed.

Code implementation:

import random

def guess_number():
    number_to_guess = random.randint(1, 100)
    attempts = 0
    guessed = False
    print("欢迎来到猜数字游戏!数字在1到100之间。")
    while not guessed:
        guess = int(input("请输入你的猜测:"))
        attempts += 1
        if guess < number_to_guess:
            print("猜的数字太小了。")
        elif guess > number_to_guess:
            print("猜的数字太大了。")
        else:
            guessed = True
            print(f"恭喜你,猜中了!你一共猜了 {attempts} 次。")

if __name__ == "__main__":
    guess_number()

2. Calculator

Project background: A simple calculator that demonstrates basic arithmetic operations and function definitions.

Implementation steps:

Define functions for addition, subtraction, multiplication, and division.

Collect user input for two operands and the desired operation.

Call the appropriate function and display the result.

Code implementation:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "除数不能为零"
    return x / y

def calculator():
    print("选择运算:")
    print("1. 加")
    print("2. 减")
    print("3. 乘")
    print("4. 除")
    choice = input("请输入选择(1/2/3/4): ")
    num1 = float(input("请输入第一个数字: "))
    num2 = float(input("请输入第二个数字: "))
    if choice == '1':
        print(f"结果是:{add(num1, num2)}")
    elif choice == '2':
        print(f"结果是:{subtract(num1, num2)}")
    elif choice == '3':
        print(f"结果是:{multiply(num1, num2)}")
    elif choice == '4':
        print(f"结果是:{divide(num1, num2)}")
    else:
        print("无效的输入")

if __name__ == "__main__":
    calculator()

3. Word Frequency Counter

Project background: An interesting text‑analysis project that teaches file I/O, string handling, and dictionary usage by counting how often each word appears in a document.

Implementation steps:

Read the content of a text file.

Remove punctuation, convert to lowercase, and split into words.

Use a dictionary to tally word occurrences.

Sort the dictionary by frequency and print the results.

Code implementation:

import string

def word_frequency(file_path):
    with open(file_path, 'r') as file:
        text = file.read()
    # Remove punctuation and convert to lowercase
    text = text.translate(str.maketrans('', '', string.punctuation)).lower()
    words = text.split()
    # Count frequencies
    frequency = {}
    for word in words:
        if word in frequency:
            frequency[word] += 1
        else:
            frequency[word] = 1
    # Sort and output
    sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
    for word, count in sorted_frequency:
        print(f"{word}: {count}")

if __name__ == "__main__":
    file_path = 'text.txt'  # Ensure this file exists
    word_frequency(file_path)

4. Simple Ledger

Project background: A practical utility for recording daily income and expenses, illustrating file persistence and a minimal command‑line interface.

Implementation steps:

Provide a UI for entering income or expense records.

Append records to a file.

Read and display stored records.

Code implementation:

import os

def add_record(records, record):
    records.append(record)

def save_records(records, file_path):
    with open(file_path, 'w') as file:
        for record in records:
            file.write(f"{record}
")

def load_records(file_path):
    if not os.path.exists(file_path):
        return []
    with open(file_path, 'r') as file:
        records = [line.strip() for line in file]
    return records

def main():
    file_path = 'records.txt'
    records = load_records(file_path)
    while True:
        print("选择操作:")
        print("1. 添加记录")
        print("2. 查看记录")
        print("3. 退出")
        choice = input("请输入选择(1/2/3): ")
        if choice == '1':
            date = input("请输入日期 (YYYY-MM-DD): ")
            amount = input("请输入金额: ")
            description = input("请输入描述: ")
            record = f"{date} {amount} {description}"
            add_record(records, record)
            save_records(records, file_path)
            print("记录已添加!")
        elif choice == '2':
            print("当前记录:")
            for record in records:
                print(record)
        elif choice == '3':
            break
        else:
            print("无效的选择")

if __name__ == "__main__":
    main()

5. Simple Chatroom

Project background: A slightly more advanced example that introduces network programming and multithreading, consisting of a server that forwards messages and multiple clients that can chat simultaneously.

Implementation steps:

Create a server that accepts multiple client connections.

Develop a client that connects to the server and can send/receive messages.

Use threading to handle concurrent client connections.

Code implementation – Server:

import socket
import threading

clients = []

def handle_client(client_socket):
    while True:
        try:
            message = client_socket.recv(1024).decode('utf-8')
            if message:
                print(f"收到消息: {message}")
                broadcast(message, client_socket)
            else:
                remove_client(client_socket)
                break
        except:
            continue

def broadcast(message, client_socket):
    for client in clients:
        if client != client_socket:
            try:
                client.send(message.encode('utf-8'))
            except:
                remove_client(client)

def remove_client(client_socket):
    if client_socket in clients:
        clients.remove(client_socket)

def server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('0.0.0.0', 9999))
    server_socket.listen(5)
    print("服务器已启动,等待连接...")
    while True:
        client_socket, addr = server_socket.accept()
        clients.append(client_socket)
        print(f"客户端连接: {addr}")
        threading.Thread(target=handle_client, args=(client_socket,)).start()

if __name__ == "__main__":
    server()

Code implementation – Client:

import socket
import threading

def receive_messages(client_socket):
    while True:
        try:
            message = client_socket.recv(1024).decode('utf-8')
            if message:
                print(f"收到消息: {message}")
            else:
                break
        except:
            continue

def client():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(('127.0.0.1', 9999))
    threading.Thread(target=receive_messages, args=(client_socket,)).start()
    while True:
        message = input()
        client_socket.send(message.encode('utf-8'))

if __name__ == "__main__":
    client()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CLIPythonNetworkingprogramming fundamentalsbeginner projects
DevOps Operations Practice
Written by

DevOps Operations Practice

We share professional insights on cloud-native, DevOps & operations, Kubernetes, observability & monitoring, and Linux systems.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.