Python Code Snippets: Games, Strings, and Math Utilities

Python Code Snippets: Practical Utilities and Games

This collection features various Python code snippets, ranging from an interactive guessing game to essential string and mathematical utility functions. Each section provides a clear, functional example of common programming tasks.

Interactive Fibonacci Guessing Game in Python

Challenge your knowledge of Fibonacci numbers with this interactive guessing game. The program generates Fibonacci numbers and asks you to determine if they are even or odd.

import random

def generate_fibonacci(n):
    fib_sequence = [0, 1]
    for _ in range(2, n):
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence

def play_game():
    print("Welcome to the Fibonacci Guessing Game! Type 'even', 'odd', or 'exit' to quit.")

    fib_numbers = generate_fibonacci(20)
    score = 0

    while True:
        chosen_number = random.choice(fib_numbers)
        guess = input(f"Is the number {chosen_number} even or odd? ").strip().lower()

        if guess == "exit":
            print("Thanks for playing! Your score: ", score)
            break

        if guess not in ["even", "odd"]:
            print("Invalid input. Please try again.")
            continue

        correct_answer = "even" if chosen_number % 2 == 0 else "odd"
        if guess == correct_answer:
            print("Correct!")
            score += 1
        else:
            print(f"Wrong! It was {correct_answer}.")

if __name__ == "__main__":
    play_game()

Python String Utility: Reverse Sentences

This utility function demonstrates how to reverse the order of sentences within a given paragraph, maintaining the integrity of each sentence.

import re

def reverse_sentences(paragraph):
    sentences = re.split(r'(?<=[.!?])\s+', paragraph.strip())
    return ' '.join(sentences[::-1])

if __name__ == "__main__":
    paragraph = (
        "Python is a versatile programming language. It is widely used in data science, web development, and automation."
        " Many developers love Python for its simplicity and readability."
    )
    print("Original Paragraph:")
    print(paragraph)

    print("\nReversed Sentences:")
    print(reverse_sentences(paragraph))

Filtering and Counting Prime Numbers

Learn how to efficiently filter a list to find prime numbers and count them using a custom function.

def filter_and_count_primes(lst):
    is_prime = lambda x: x > 1 and all(x % i for i in range(2, int(x**0.5) + 1))
    primes = [x for x in lst if isinstance(x, int) and is_prime(x)]
    return primes, len(primes)

# Example usage
mixed_list = [3, 15, -7, 2, 11, 0, 8, 'hello', 19, 23, 12.5, 31]
primes, prime_count = filter_and_count_primes(mixed_list)
print("Prime Numbers:", primes)
print("Count of Prime Numbers:", prime_count)

Generate Multiplication Table in Python

This simple Python program generates and prints the multiplication table for a given number up to 10.

def printTable(n):
    for i in range (1, 11):
        # Multiples from 1 to 10
        print ("%d * %d = %d" % (n, i, n * i))

if __name__ == "__main__":
    n = 5
    printTable(n)

Python Function to Check Perfect Squares

Determine if a given number is a perfect square using this Python function, which leverages the math.isqrt method for efficiency.

import math

def is_perfect_square(num):
    if num < 0:
        return False  # Negative numbers cannot be perfect squares
    # Calculate the square root and check if it's an integer
    sqrt = math.isqrt(num)
    return sqrt * sqrt == num

# Test the function with user input
number = int(input("Enter a number: "))
if is_perfect_square(number):
    print(f"{number} is a perfect square.")
else:
    print(f"{number} is not a perfect square.")

Reverse a String in Python

A straightforward function to reverse any input string character by character, building the reversed string from end to start.

def reverse_string(s):
    reversed_str = ""  # Start with an empty string
    # Loop through the original string from the end to the start
    for i in range(len(s) - 1, -1, -1):
        reversed_str += s[i]  # Append each character to the result
    return reversed_str

# Test the function
input_string = input("Enter a string: ")
reversed_string = reverse_string(input_string)
print(f"Reversed string: {reversed_string}")

Remove Duplicate Characters from a String

This function processes a string and returns a new string with all duplicate characters removed, preserving the order of the first occurrence.

def remove_duplicates(s):
    # Create an empty string to store the result
    result = ""
    # Loop through each character in the original string
    for char in s:
        # If the character is not already in the result string, add it
        if char not in result:
            result += char
    return result

# Test the function
input_string = input("Enter a string: ")
unique_string = remove_duplicates(input_string)
print(f"String with duplicates removed: {unique_string}")