Zum Inhalt

Einsteiger-Miniprojekte

Willkommen in der Galerie der Miniprojekte! Diese praktischen Programme kombinieren grundlegende Python-Regeln – wie Schleifensteuerung, Eingabeaufforderungen, mathematische Operatoren und Listen – zu funktionalen Skripten.


Projekt 1: Textdatei-Übersetzer

Dieses Skript öffnet auf sichere Weise ein englisches Textdokument (test.txt), liest die darin enthaltenen Wörter, übersetzt sie ins Japanische (ja) und speichert die Ergebnisse in einem brandneuen Dokument namens test-ja.txt.

from translate import Translator

translator = Translator(to_lang='ja')

try:
    # 1. Try to open and read the file
    with open("test.txt", mode='r') as my_file:
        text = my_file.read()

        # 2. Translate the text
        translation = translator.translate(text)

        # 3. Write the translation into a new file
        with open('./test-ja.txt', 'w') as my_file2:
            my_file2.write(translation)

except FileNotFoundError as err:
    # If "test.txt" does not exist, Python skips down here instead of crashing!
    print('file not found')

Projekt 2: Zufälliger Passwort-Generator

Dieses Projekt erstellt automatisch ein starkes Passwort für dich, indem es zufällige Zeichen aus Zeichen-Arrays, Ziffern und mathematischen Symbolen auswählt.

import random
import string

# Define how long you want your password to be
pass_length = 8

# string.ascii_letters gives you: a-z and A-Z
# string.digits gives you: 0-9
# string.punctuation gives you symbols like !, @, #, $
char_values = string.ascii_letters + string.digits + string.punctuation

# The clean, quick way to pick 8 characters and join them together:
password = ''.join(random.choices(char_values, k=pass_length))

# --- Alternative Manual Way ---
# You could also write this using a basic 'for loop' like this:
# password = ""
# for i in range(pass_length):
#     password += random.choice(char_values)

print("Generated password is:", password)

Projekt 3: Zahlenratenspiel

Dieses Spiel wählt eine geheime Zielzahl zwischen 1 und 100 und verwendet eine bedingte Schleife (while True), um Eingaben so lange zu überprüfen, bis du richtig rätst oder dich entscheidest, das Spiel zu beenden.

import random

# The computer picks a secret target number
target = random.randint(1, 100)

while True:
    # Ask the user for their guess input
    guess = (input("Enter your guess (1-100) or 'Q' to Quit: "))

    # Check if the user wants to give up and quit
    if guess == 'Q' or guess == 'q':
        print("You chose to quit the game. Goodbye!")
        break

    # Convert the user's input text into a whole number (integer)
    guess = int(guess)

    # Check the guess against our secret target
    if guess < target:
        print("Too low! Try again.")
    elif guess > target:
        print("Too high! Try again.")
    else:
        print("Congratulations! You've guessed the number.")
        break  # This ends the loop and finishes the game!

print("Game Over")

Projekt 4: Einfacher Taschenrechner

Dieses Taschenrechner-Projekt fordert dich auf, eine mathematische Operation auszuwählen und zwei Zahlen einzugeben. Es zeigt, wie einfache if-elif-else-Verzweigungen Entscheidungen verarbeiten.

print("Welcome to the Simple Calculator!")
print("Select an operation:")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")

while True:
    choice = input("Enter choice (1/2/3/4) or 'Q' to Quit: ")

    if choice == 'Q' or choice == 'q':
        print("Thank you for using the calculator. Goodbye!")
        break

    # Ask the user for two numbers
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

    # Check the user's choice and do the math
    if choice == '1':
        print(f"Result: {num1} + {num2} = {num1 + num2}")
    elif choice == '2':
        print(f"Result: {num1} - {num2} = {num1 - num2}")
    elif choice == '3':
        print(f"Result: {num1} * {num2} = {num1 * num2}")
    elif choice == '4':
        # Safety rule: you cannot divide a number by zero!
        if num2 == 0:
            print("Error! You cannot divide by zero.")
        else:
            print(f"Result: {num1} / {num2} = {num1 / num2}")
    else:
        print("Invalid Input! Please choose a number from 1 to 4.")

    print("-" * 20)  # Prints a visual separator line between calculations

print("Calculator Closed")

Projekt 5: Schere, Stein, Papier Spiel

Spiele den Spieleklassiker gegen den Computer! Dieses Projekt verarbeitet Texteingaben von deiner Tastatur und gleicht sie mithilfe von random.choice() mit der Auswahl des Computers ab.

import random

# A list of choices for the game
game_choices = ["rock", "paper", "scissors"]

print("Welcome to Rock, Paper, Scissors!")

while True:
    user_choice = input("Enter Rock, Paper, or Scissors (or 'Q' to Quit): ").lower()

    if user_choice == 'q':
        print("Thanks for playing! Goodbye.")
        break

    # Check if the user typed a correct option
    if user_choice not in game_choices:
        print("Invalid choice! Please type Rock, Paper, or Scissors.")
        continue  # This skips the rest of the code and restarts the loop round

    # The computer makes its random choice
    computer_choice = random.choice(game_choices)
    print(f"Computer chose: {computer_choice}")

    # Determine the winner using game logic rules
    if user_choice == computer_choice:
        print("It's a tie!")
    elif (user_choice == "rock" and computer_choice == "scissors") or \
         (user_choice == "paper" and computer_choice == "rock") or \
         (user_choice == "scissors" and computer_choice == "paper"):
        print("You win!")
    else:
        print("Computer wins!")

    print("-" * 20)

print("Game Over")

Projekt 6: Einfacher To-Do-Listen-Tracker

Dieses Skript verwaltet Einträge mithilfe einer leeren Liste []. Es zeigt, wie man Datenelemente mit .append() hinzufügt und Listen mit .clear() sauber leert.

# Start with a completely empty list to hold the tasks
todo_list = []

print("Welcome to your Personal Task Tracker!")

while True:
    print("\nWhat would you like to do?")
    print("1. View Tasks")
    print("2. Add a Task")
    print("3. Clear All Tasks")
    print("4. Exit")

    choice = input("Enter choice (1/2/3/4): ")

    if choice == '1':
        # Check if the list has items inside
        if len(todo_list) == 0:
            print("\nYour list is completely empty!")
        else:
            print("\n--- YOUR TO-DO LIST ---")
            # Loop through the list to print each task with its number index
            for index, task in enumerate(todo_list, start=1):
                print(f"{index}. {task}")

    elif choice == '2':
        new_task = input("\nEnter the task name: ")
        todo_list.append(new_task)  # Adds the new task to the end of our list
        print(f"'{new_task}' has been successfully added!")

    elif choice == '3':
        todo_list.clear()  # Wipes out all items inside the list safely
        print("\nAll tasks have been deleted.")

    elif choice == '4':
        print("\nExiting Task Tracker. Have a productive day!")
        break
    else:
        print("Invalid choice! Please pick 1, 2, 3, or 4.")

print("Program Closed")

Projekt 7: DevJokesApp

Dies ist eine schlanke, leichtgewichtige Desktop-Anwendung, die mit Pythons nativem GUI-Framework Tkinter und der Bibliothek pyjokes erstellt wurde.

import tkinter as tk
from tkinter import ttk
import pyjokes as pj

class DevJokesApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Mini Project 7 - Dev Jokes")
        self.geometry("500x550")

        # Language Mapping
        self.language_map = {
            'English': 'en', 'Czech': 'cs', 'German': 'de', 'Spanish': 'es',
            'Basque': 'eu', 'French': 'fr', 'Galician': 'gl', 'Hungarian': 'hu',
            'Italian': 'it', 'Lithuanian': 'lt', 'Polish': 'pl', 'Russian': 'ru',
            'Swedish': 'sv', 'Turkish': 'tr'
        }

        self._setup_widgets()
        self._update_status('Ready')

    def _setup_widgets(self):
        # Header
        header_label = ttk.Label(self, text='Jokes for Programmers', font=('Helvetica', 16, 'bold'))
        header_label.pack(pady=15)

        # Buttons Control Frame
        btn_frame = ttk.Frame(self)
        btn_frame.pack(pady=5)

        ttk.Button(btn_frame, text='Get Joke', command=self.get_joke).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text='Get All Jokes', command=self.show_all_jokes).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text='Clear', command=self.clear_jokes).pack(side=tk.LEFT, padx=5)

        # Radio Buttons (Category)
        radio_frame = ttk.LabelFrame(self, text=" Category ")
        radio_frame.pack(pady=10, fill=tk.X, padx=20)

        self.joke_type = tk.StringVar(value='all')
        for text, val in [('All', 'all'), ('Chuck', 'chuck'), ('Neutral', 'neutral')]:
            ttk.Radiobutton(radio_frame, text=text, variable=self.joke_type, value=val).pack(side=tk.LEFT, padx=15, pady=5)

        # Language Selection Listbox
        lang_frame = ttk.LabelFrame(self, text=" Select Language ")
        lang_frame.pack(pady=10, fill=tk.BOTH, expand=True, padx=20)

        scrollbar_lang = ttk.Scrollbar(lang_frame, orient='vertical')
        self.lb_languages = tk.Listbox(lang_frame, yscrollcommand=scrollbar_lang.set, exportselection=False)
        scrollbar_lang.config(command=self.lb_languages.yview)

        scrollbar_lang.pack(side=tk.RIGHT, fill=tk.Y)
        self.lb_languages.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        for name in self.language_map.keys():
            self.lb_languages.insert(tk.END, name)
        self.lb_languages.selection_set(0) # Default to English

        # Joke Display Box
        display_frame = ttk.LabelFrame(self, text=" Joke ")
        display_frame.pack(pady=10, fill=tk.BOTH, expand=True, padx=20)

        scrollbar_text = ttk.Scrollbar(display_frame, orient='vertical')
        self.joke_text = tk.Text(display_frame, wrap='word', height=8, yscrollcommand=scrollbar_text.set)
        scrollbar_text.config(command=self.joke_text.yview)

        scrollbar_text.pack(side=tk.RIGHT, fill=tk.Y)
        self.joke_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        # Status Bar
        self.status_var = tk.StringVar()
        status_bar = ttk.Label(self, textvariable=self.status_var, relief=tk.SUNKEN, anchor='w')
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    # ---------- Utility & Action Methods ----------
    def _update_status(self, context=''):
        lang = self.get_selected_language().upper()
        category = self.joke_type.get().upper()
        self.status_var.set(f" {context} | Language: {lang} | Category: {category}")

    def get_selected_language(self):
        selection = self.lb_languages.curselection()
        if selection:
            return self.language_map[self.lb_languages.get(selection[0])]
        return 'en'

    def get_joke(self):
        lang = self.get_selected_language()
        category = self.joke_type.get()
        self.clear_jokes()
        try:
            joke = pj.get_joke(language=lang, category=category)
            self.joke_text.insert(tk.END, joke)
            self._update_status('1 joke fetched')
        except Exception:
            self.joke_text.insert(tk.END, f"No jokes found for {category} in {lang.upper()}.")
            self._update_status('Fetch failed')

    def show_all_jokes(self):
        lang = self.get_selected_language()
        category = self.joke_type.get()
        self.clear_jokes()
        try:
            jokes = pj.get_jokes(language=lang, category=category)
            self.joke_text.insert(tk.END, '\n\n'.join(jokes))
            self._update_status(f'{len(jokes)} jokes fetched')
        except Exception:
            self.joke_text.insert(tk.END, f"Could not load jokes for configuration.")
            self._update_status('Fetch failed')

    def clear_jokes(self):
        self.joke_text.delete('1.0', tk.END)
        self._update_status('Cleared')

if __name__ == '__main__':
    app = DevJokesApp()
    app.mainloop()