-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathpart3_user_input.py
More file actions
122 lines (94 loc) · 3.48 KB
/
Copy pathpart3_user_input.py
File metadata and controls
122 lines (94 loc) · 3.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""
Part 3: Dynamic Queries with User Input
=======================================
Difficulty: Intermediate
Learn:
- Using input() to make dynamic API requests
- Building URLs with f-strings
- Query parameters in URLs
"""
import requests
def get_user_info():
"""Fetch user info based on user input."""
print("=== User Information Lookup ===\n")
user_id = input("Enter user ID (1-10): ")
url = f"https://jsonplaceholder.typicode.com/users/{user_id}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(f"\n--- User #{user_id} Info ---")
print(f"Name: {data['name']}")
print(f"Email: {data['email']}")
print(f"Phone: {data['phone']}")
print(f"Website: {data['website']}")
else:
print(f"\nUser with ID {user_id} not found!")
def search_posts():
"""Search posts by user ID."""
print("\n=== Post Search ===\n")
user_id = input("Enter user ID to see their posts (1-10): ")
# Using query parameters
url = "https://jsonplaceholder.typicode.com/posts"
params = {"userId": user_id}
response = requests.get(url, params=params)
posts = response.json()
if posts:
print(f"\n--- Posts by User #{user_id} ---")
for i, post in enumerate(posts, 1):
print(f"{i}. {post['title']}")
else:
print("No posts found for this user.")
def get_crypto_price():
"""Fetch cryptocurrency price based on user input."""
print("\n=== Cryptocurrency Price Checker ===\n")
print("Available coins: btc-bitcoin, eth-ethereum, doge-dogecoin")
coin_id = input("Enter coin ID (e.g., btc-bitcoin): ").lower().strip()
url = f"https://api.coinpaprika.com/v1/tickers/{coin_id}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price_usd = data['quotes']['USD']['price']
change_24h = data['quotes']['USD']['percent_change_24h']
print(f"\n--- {data['name']} ({data['symbol']}) ---")
print(f"Price: ${price_usd:,.2f}")
print(f"24h Change: {change_24h:+.2f}%")
else:
print(f"\nCoin '{coin_id}' not found!")
print("Try: btc-bitcoin, eth-ethereum, doge-dogecoin")
def main():
"""Main menu for the program."""
print("=" * 40)
print(" Dynamic API Query Demo")
print("=" * 40)
while True:
print("\nChoose an option:")
print("1. Look up user info")
print("2. Search posts by user")
print("3. Check crypto price")
print("4. Exit")
choice = input("\nEnter choice (1-4): ")
if choice == "1":
get_user_info()
elif choice == "2":
search_posts()
elif choice == "3":
get_crypto_price()
elif choice == "4":
print("\nGoodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
# --- EXERCISES ---
#
# Exercise 1: Add a function to fetch weather for a city
# Use Open-Meteo API (no key required):
# https://api.open-meteo.com/v1/forecast?latitude=28.61&longitude=77.23¤t_weather=true
# Challenge: Let user input city name (you'll need to find lat/long)
#
# Exercise 2: Add a function to search todos by completion status
# URL: https://jsonplaceholder.typicode.com/todos
# Params: completed=true or completed=false
#
# Exercise 3: Add input validation (check if user_id is a number)