Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@


def sumar(a, b):
return a + b

def restar(a, b):
return a - b

def multiplicar(a, b):
return a * b

def dividir(a, b):
if b != 0:
return a / b
else:
return "Error: División por cero"

def calculadora():
print("Seleccione una operación:")
print("1. Sumar")
print("2. Restar")
print("3. Multiplicar")
print("4. Dividir")

opcion = input("Ingrese el número de la operación: ")

try:
num1 = float(input("Ingrese el primer número: "))
num2 = float(input("Ingrese el segundo número: "))

if opcion == '1':
print("Resultado:", sumar(num1, num2))
elif opcion == '2':
print("Resultado:", restar(num1, num2))
elif opcion == '3':
print("Resultado:", multiplicar(num1, num2))
elif opcion == '4':
print("Resultado:", dividir(num1, num2))
else:
print("Opción no válida")
except ValueError:
print("Error: Entrada no válida")

if __name__ == "__main__":
calculadora()
6 changes: 3 additions & 3 deletions card_draw.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'])) # Fixed missing parenthesis

# 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): # Fixed missing colon
print(deck[i][0], "of", deck[i][1]) # Fixed missing parenthesis
1 change: 1 addition & 0 deletions hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("Hola Mundo")
62 changes: 32 additions & 30 deletions sum_elements.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,39 @@
#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
return sum(arr) # Usar la función integrada sum()

def get_valid_input(prompt, validation_fn):
while True:
try:
value = int(input(prompt))
if validation_fn(value):
return value
print("Invalid input. Please try again.")
except ValueError:
print("Invalid input. Please enter a valid integer.")

def get_number_of_elements():
return get_valid_input(
"Enter the number of elements (1-100): ",
lambda x: 1 <= x <= MAX
)

def get_elements(n):
arr = []
print(f"Enter {n} integers:")
for _ in range(n):
arr.append(get_valid_input("Enter an integer: ", lambda x: True))
return arr

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)
try:
n = get_number_of_elements()
arr = get_elements(n)
print("Sum of the numbers:", calculate_sum(arr)) # Llamar directamente a calculate_sum()
except KeyboardInterrupt:
print("\nProgram terminated by user.")
exit(1)

if __name__ == "__main__":
main()
main()
30 changes: 30 additions & 0 deletions weather_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import requests

class WeatherAPI:
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_name, units="metric"):
params = {
"q": city_name,
"appid": self.api_key,
"units": units
}
try:
response = requests.get(self.base_url, params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching weather data: {e}")
return None

# Example usage:
# Replace 'your_api_key_here' with your OpenWeatherMap API key
if __name__ == "__main__":
api_key = "your_api_key_here"
weather_api = WeatherAPI(api_key)
city = "London"
weather_data = weather_api.get_weather(city)
if weather_data:
print(weather_data)