pr3-python-sose2026/assignments/test.py

55 lines
1.7 KiB
Python

import requests
def get_advice_by_id(advice_id):
# Prepare the API endpoint with the given ID
url = f"https://api.adviceslip.com/advice/{advice_id}"
try:
# Send HTTP GET Request
response = requests.get(url)
# Check if the request was successful (HTTP Status 200)
if response.status_code == 200:
data = response.json()
# Extract the advice if it exists in the JSON payload
if 'slip' in data:
advice_text = data['slip']['advice']
print(f"\n[Advice #{advice_id}]:")
print(f"\"{advice_text}\"\n")
else:
print(
f"\n[Warning]: Could not find advice with ID {advice_id}.\n")
else:
print(
f"\n[Error]: Server connection failed. Status Code: {response.status_code}\n")
# Handle network connection exceptions
except requests.exceptions.RequestException as e:
print(f"\n[Error]: Network problem occurred: {e}\n")
# Main execution block
if __name__ == "__main__":
print("--- Advice Fetcher ---")
print("Type 'exit' to quit the application.\n")
while True:
user_input = input("-> Enter advice ID (e.g., 10): ")
# Exit condition
if user_input.lower() == 'exit':
print("Goodbye!")
break
# Validate if the input is a number
if user_input.isdigit():
get_advice_by_id(user_input)
else:
print("[Warning]: Please enter a valid number only!\n")
print("[Warning]: Please enter a valid number only!\n")
print("[Warning]: Please enter a valid number only!\n")
print("dafa")