diff --git a/calculator.js b/calculator.js new file mode 100644 index 00000000..7176e8c4 --- /dev/null +++ b/calculator.js @@ -0,0 +1,32 @@ +class Calculator { + add(a, b) { + return a + b; + } + + subtract(a, b) { + return a - b; + } + + multiply(a, b) { + return a * b; + } + + divide(a, b) { + if (b === 0) { + throw new Error("Division by zero is not allowed."); + } + return a / b; + } +} + + +// Example usage +const calculator = new Calculator(); +console.log("Addition: ", calculator.add(10, 5)); +console.log("Subtraction: ", calculator.subtract(10, 5)); +console.log("Multiplication: ", calculator.multiply(10, 5)); +try { + console.log("Division: ", calculator.divide(10, 0)); +} catch (error) { + console.error(error.message); +} \ No newline at end of file diff --git a/calculator.py b/calculator.py new file mode 100644 index 00000000..f0a928a1 --- /dev/null +++ b/calculator.py @@ -0,0 +1,24 @@ +# This file contains a basic calculator implementation and is unrelated to Git configuration. + +class Calculator: + def add(self, a, b): + return a + b + + def subtract(self, a, b): + return a - b + + def multiply(self, a, b): + return a * b + + def divide(self, a, b): + if b == 0: + raise ValueError("Cannot divide by zero") + return a / b + +# Example usage: +if __name__ == "__main__": + calc = Calculator() + print("Addition:", calc.add(5, 3)) + print("Subtraction:", calc.subtract(5, 3)) + print("Multiplication:", calc.multiply(5, 3)) + print("Division:", calc.divide(5, 3)) diff --git a/card_draw.py b/card_draw.py index 4f4bf631..79754924 100644 --- a/card_draw.py +++ b/card_draw.py @@ -4,12 +4,12 @@ import itertools, random # make a deck of cards -deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']) +deck = list(itertools.product(range(1, 14), ['Spade', 'Heart', 'Diamond', 'Club'])) # shuffle the cards random.shuffle(deck) # draw five cards print("You got:") -for i in range(5) - print(deck[i][0], "of", deck[i][1] +for i in range(5): + print(deck[i][0], "of", deck[i][1]) diff --git a/hello.py b/hello.py new file mode 100644 index 00000000..4648e701 --- /dev/null +++ b/hello.py @@ -0,0 +1 @@ +print("Hello, World!") \ No newline at end of file diff --git a/sum_elements.py b/sum_elements.py index 2731a254..cca0a5fe 100644 --- a/sum_elements.py +++ b/sum_elements.py @@ -1,37 +1,45 @@ -#A poorly written example of a program in Python. It prompts the user for the number of elements to sum, takes those integers as input, and handles some basic error cases - -MAX = 100 - -def calculate_sum(arr): - result = 0 - for num in arr: - result += num - return result +# Programa para calcular la suma de una lista de números enteros ingresados por el usuario. +# Refactorizado para seguir buenas prácticas de programación. + +MAX_ELEMENTS = 100 + +def calculate_sum(numbers): + """Calcula la suma de una lista de números.""" + return sum(numbers) + +def get_integer_input(prompt): + """Solicita al usuario un número entero y valida la entrada.""" + while True: + try: + return int(input(prompt)) + except ValueError: + print("Entrada inválida. Por favor, ingrese un número entero.") + +def get_numbers_from_user(count): + """Solicita al usuario una cantidad específica de números enteros.""" + numbers = [] + print(f"Ingrese {count} números enteros:") + for i in range(count): + number = get_integer_input(f" Número {i + 1}: ") + numbers.append(number) + return numbers def main(): - try: - n = int(input("Enter the number of elements (1-100): ")) - if not 1 <= n <= MAX: - print("Invalid input. Please provide a digit ranging from 1 to 100.") - exit(1) - - arr = [] - - print(f"Enter {n} integers:") - for _ in range(n): - try: - arr.append(int(input())) - except ValueError: - print("Invalid input. Please enter valid integers.") - exit(1) - - total = calculate_sum(arr) - - print("Sum of the numbers:", total) - - except KeyboardInterrupt: - print("\nProgram terminated by user.") - exit(1) + """Función principal del programa.""" + print("Programa para calcular la suma de números enteros.") + while True: + try: + n = get_integer_input(f"Ingrese la cantidad de números a sumar (1-{MAX_ELEMENTS}): ") + if 1 <= n <= MAX_ELEMENTS: + break + print(f"Por favor, ingrese un número entre 1 y {MAX_ELEMENTS}.") + except KeyboardInterrupt: + print("\nPrograma terminado por el usuario.") + return + + numbers = get_numbers_from_user(n) + total = calculate_sum(numbers) + print(f"La suma de los números ingresados es: {total}") if __name__ == "__main__": main() diff --git a/weather_script.js b/weather_script.js new file mode 100644 index 00000000..ff9eb783 --- /dev/null +++ b/weather_script.js @@ -0,0 +1,23 @@ +// Reemplaza 'YOUR_API_KEY' con tu clave de API de OpenWeatherMap +const API_KEY = 'b3c00c360b119aa09fd055754dddb14b'; +const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'; + +// Función para obtener datos del clima por ciudad +async function getWeatherByCity(city) { + try { + const response = await fetch(`${BASE_URL}?q=${city}&appid=${API_KEY}&units=metric`); + if (!response.ok) { + throw new Error(`Error: ${response.status} - ${response.statusText}`); + } + const data = await response.json(); + console.log(`Clima en ${city}:`); + console.log(`Temperatura: ${data.main.temp}°C`); + console.log(`Descripción: ${data.weather[0].description}`); + console.log(`Humedad: ${data.main.humidity}%`); + } catch (error) { + console.error('Error al obtener los datos del clima:', error.message); + } +} + +// Ejemplo de uso +getWeatherByCity('Madrid'); \ No newline at end of file diff --git a/weather_script.py b/weather_script.py new file mode 100644 index 00000000..aa5cdf80 --- /dev/null +++ b/weather_script.py @@ -0,0 +1,31 @@ +import requests + +class WeatherFetcher: + def __init__(self, api_key): + self.api_key = api_key + self.base_url = "https://api.openweathermap.org/data/2.5/weather" + + def get_weather(self, city): + params = { + "q": city, + "appid": self.api_key, + "units": "metric" # Use metric units for temperature in Celsius + } + response = requests.get(self.base_url, params=params) + if response.status_code == 200: + return response.json() + else: + response.raise_for_status() + +# Example usage: +if __name__ == "__main__": + api_key = "d9660777d8703f83462782ab4f0f72d1" + weather_fetcher = WeatherFetcher(api_key) + city = input("Enter the city name: ") + try: + weather_data = weather_fetcher.get_weather(city) + print(f"Weather in {city}:") + print(f"Temperature: {weather_data['main']['temp']}°C") + print(f"Description: {weather_data['weather'][0]['description']}") + except requests.exceptions.RequestException as e: + print(f"Error fetching weather data: {e}")