My Python Snippet Library

Function for user input that valitates data input.

def check_user_input_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print(f"Please input an integer.")

input_variable1 = check_user_input_int(f"Please enter your first variable: ")

print(input_variable1)

Factorial Calculation Using a While Loop.

def calculate_factorial():
    number = int(input("Enter a positive integer: "))
    factorial = 1
    i = 1
    while i <= number:
        factorial *= i
        i += 1
    print(f"{number}! = {factorial}")

Counting Vowels in a String.

def count_vowels():
    user_string = input("Enter a string: ")
    vowel_count = 0
    vowels = 'aeiouAEIOU'
    for char in user_string:
        if char in vowels:
            vowel_count += 1
    print(f"Number of vowels: {vowel_count}")

Simple Calculator (Addition, Subtraction, Multiplication, Division).

def simple_calculator():
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    operation = input("Enter operation (addition, subtraction, multiplication, division): ").lower()
    if operation == "addition":
        print(f"The result is {num1 + num2}")
    elif operation == "subtraction":
        print(f"The result is {num1 - num2}")
    elif operation == "multiplication":
        print(f"The result is {num1 * num2}")
    elif operation == "division":
        if num2 != 0:
            print(f"The result is {num1 / num2}")
        else:
            print("Error: Cannot divide by zero.")
    else:
        print("Invalid operation")

Finding the Second Largest Number in a List.

def find_second_largest(numbers):
    unique_numbers = list(set(numbers))
    if len(unique_numbers) < 2:
        return "Not enough unique numbers to determine the second largest."
    unique_numbers.sort()
    return unique_numbers[-2]

Character Count in a String.

def count_characters():
    user_string = input("Enter a string: ")
    char_count = {}
    for char in user_string:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1
    print(char_count)

Reversing a List of Words.

def reverse_word_list():
    num_words = int(input("How many words would you like to enter? "))
    words = []
    for i in range(num_words):
        word = input(f"Enter word {i + 1}: ")
        words.append(word)
    print("\nWords in reverse order:")
    for word in reversed(words):
        print(word)

Return the number of odd and even numbers from a user input.

user_input = int(input("Please enter a number: "))

if user_input % 2:
    print(f"This number is odd.")
else:
    print(f"This number is even.")

Cybergroup.no

You should care for good internet hygiene!