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
56 changes: 56 additions & 0 deletions calculator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a - b;
}

function multiply(a, b) {
return a * b;
}

function divide(a, b) {
if (b === 0) {
return "Error: Division by zero is not allowed.";
}
return a / b;
}

function calculator() {
console.log("Basic Calculator");
console.log("Select operation:");
console.log("1. Add");
console.log("2. Subtract");
console.log("3. Multiply");
console.log("4. Divide");

const choice = prompt("Enter choice (1/2/3/4):");

if (["1", "2", "3", "4"].includes(choice)) {
const num1 = parseFloat(prompt("Enter first number:"));
const num2 = parseFloat(prompt("Enter second number:"));

let result;
switch (choice) {
case "1":
result = add(num1, num2);
break;
case "2":
result = subtract(num1, num2);
break;
case "3":
result = multiply(num1, num2);
break;
case "4":
result = divide(num1, num2);
break;
}
console.log(`The result is: ${result}`);
} else {
console.log("Invalid input. Please select a valid operation.");
}
}

// Run the calculator
calculator();
41 changes: 41 additions & 0 deletions calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
def add(a, b):
return a + b

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

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

def divide(a, b):
if b == 0:
return "Error: Division by zero is not allowed."
return a / b

def calculator():
print("Basic Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"The result is: {add(num1, num2)}")
elif choice == '2':
print(f"The result is: {subtract(num1, num2)}")
elif choice == '3':
print(f"The result is: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid input. Please select a valid operation.")

if __name__ == "__main__":
calculator()
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']))

# 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])
5 changes: 5 additions & 0 deletions hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def main():
print("Hello, World!")

if __name__ == "__main__":
main()
23 changes: 22 additions & 1 deletion sum_elements.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
#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

def get_number_of_elements(max_value):
while True:
try:
n = int(input(f"Enter the number of elements (1-{max_value}): "))
if 1 <= n <= max_value:
return n
else:
print(f"Invalid input. Please provide a number between 1 and {max_value}.")
except ValueError:
print("Invalid input. Please enter a valid integer.")

def get_elements(n):
elements = []
print(f"Enter {n} integers:")
for _ in range(n):
while True:
try:
elements.append(int(input()))
break
except ValueError:
print("Invalid input. Please enter a valid integer.")
return elements
MAX = 100

def calculate_sum(arr):
Expand Down
33 changes: 33 additions & 0 deletions weather_script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const fetch = require('node-fetch'); // Ensure you have node-fetch installed (npm install node-fetch)

async function fetchWeather(cityName, apiKey) {
const baseUrl = "http://api.openweathermap.org/data/2.5/weather";
const url = `${baseUrl}?q=${cityName}&appid=${apiKey}&units=metric`; // Use "imperial" for Fahrenheit

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const weatherData = await response.json();
return weatherData;
} catch (error) {
return { error: error.message };
}
}

(async () => {
const API_KEY = "your_api_key_here"; // Replace with your OpenWeatherMap API key
const city = "London"; // Replace with the desired city name

const weatherData = await fetchWeather(city, API_KEY);

if (weatherData.error) {
console.log(`Error: ${weatherData.error}`);
} else {
console.log(`Weather in ${weatherData.name}:`);
console.log(`Temperature: ${weatherData.main.temp}°C`);
console.log(`Weather: ${weatherData.weather[0].description.charAt(0).toUpperCase() + weatherData.weather[0].description.slice(1)}`);
console.log(`Humidity: ${weatherData.main.humidity}%`);
}
})();
41 changes: 41 additions & 0 deletions weather_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import requests

def fetch_weather(city_name, api_key):
"""
Fetch weather data for a given city from OpenWeatherMap API.

Args:
city_name (str): Name of the city to fetch weather for.
api_key (str): Your OpenWeatherMap API key.

Returns:
dict: Weather data if successful, or an error message.
"""
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city_name,
"appid": api_key,
"units": "metric" # Use "imperial" for Fahrenheit
}

try:
response = requests.get(base_url, params=params)
response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx)
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}

if __name__ == "__main__":
# Replace with your OpenWeatherMap API key
API_KEY = "your_api_key_here"
city = input("Enter the city name: ")

weather_data = fetch_weather(city, API_KEY)

if "error" in weather_data:
print(f"Error: {weather_data['error']}")
else:
print(f"Weather in {weather_data['name']}:")
print(f"Temperature: {weather_data['main']['temp']}°C")
print(f"Weather: {weather_data['weather'][0]['description'].capitalize()}")
print(f"Humidity: {weather_data['main']['humidity']}%")