Summing Two Numeric Inputs
This script accepts user input for two numbers, converts them to floating-point values, calculates the total, and displays the result.
# Add two numbers provided by the user
first_input = input("Enter the first numeric value: ")
second_input = input("Enter the second numeric value: ")
# Perform addition after type casting
result = float(first_input) + float(second_input)
# Output the formatted result
print(f"The sum of {first_input} and {second_input} is: {result}")
Generating Random Integers
The random module is utilized here to generate a pseudo-random integer within a specified range. This example prints a number between 1 and 10.
import random
# Generate a random integer between 1 and 10 (inclusive)
random_value = random.randint(1, 10)
print(f"Generated random number: {random_value}")
Identifying Prime Numbers in a Range
The following logic iterates through a user-defined interval to find and print prime numbers. It checks for factors greater than one to determine primality.
# Get range limits from the user
lower_limit = int(input("Enter the lower bound of the range: "))
upper_limit = int(input("Enter the upper bound of the range: "))
print(f"Prime numbers between {lower_limit} and {upper_limit}:")
for num in range(lower_limit, upper_limit + 1):
# Prime numbers are strictly greater than 1
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if (num % i) == 0:
break
else:
print(num)
Determining Days in a Month
Using the built-in calendar module, this snippet retrieves data for a specific month and year. The output is a tuple containing the weekday of the first day and the total number of days.
import calendar
# Get calendar data for October 2023
# Returns (weekday_of_first_day, number_of_days)
month_info = calendar.monthrange(2023, 10)
print(month_info)
# Output interpretation: (6, 31) implies the first day is Sunday (6) and there are 31 days.
Resetting a List
This example demonstrates how to remove all elements from a list using the .clear() method, resulting in an empty list.
sample_collection = [10, 50, 25, 100]
print("List before clearing:", sample_collection)
# Empty the list
sample_collection.clear()
print("List after clearing:", sample_collection)