Skip to content

Commit 02a2f1a

Browse files
lpozoKateFinegan
andauthored
Sample code for the article on global variables in functions (#380)
* Sample code for the article on global variables in functions * TR updates, first round * TR updates, second round * LE README.md * TR update --------- Co-authored-by: KateFinegan <[email protected]>
1 parent c6243f2 commit 02a2f1a

File tree

8 files changed

+165
-0
lines changed

8 files changed

+165
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Using and Defining Global Variables in Your Python Functions
2+
3+
This folder provides the code examples for the Real Python tutorial [Using and Defining Global Variables in Your Python Functions](https://realpython.com/python-use-global-variable-in-function/).
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Account:
2+
def __init__(self, balance=0):
3+
self.balance = balance
4+
5+
def deposit(self, amount):
6+
self.balance += amount
7+
print(f"Successful deposit: +${amount:,.2f}")
8+
9+
def withdraw(self, amount):
10+
if self.balance - amount > 0:
11+
self.balance -= amount
12+
print(f"Successful withdrawal: -${amount:,.2f}")
13+
else:
14+
print("Not enough funds for this transaction")
15+
16+
17+
def main():
18+
account = Account()
19+
while True:
20+
operation = input(
21+
"What would you like to do?\n"
22+
" d) deposit "
23+
" w) withdraw "
24+
" b) balance "
25+
" q) quit\n"
26+
"> "
27+
)
28+
if operation in "dD":
29+
amount = float(input("Enter the deposit amount: "))
30+
account.deposit(amount)
31+
elif operation in "wW":
32+
amount = float(input("Enter the withdrawal amount: "))
33+
account.withdraw(amount)
34+
elif operation in "bB":
35+
print(f"Current balance: ${account.balance:,.2f}")
36+
elif operation in "qQ":
37+
print("Goodbye!")
38+
break
39+
else:
40+
print("Invalid operation. Please try again.")
41+
42+
43+
main()
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
balance = 0
2+
3+
4+
def deposit(amount):
5+
global balance
6+
balance += amount
7+
print(f"Successful deposit: +${amount:,.2f}")
8+
9+
10+
def withdraw(amount):
11+
global balance
12+
if balance - amount > 0:
13+
balance -= amount
14+
print(f"Successful withdrawal: -${amount:,.2f}")
15+
else:
16+
print("Not enough funds for this transaction")
17+
18+
19+
def get_balance():
20+
return balance
21+
22+
23+
def main():
24+
while True:
25+
operation = input(
26+
"What would you like to do?\n"
27+
" d) deposit "
28+
" w) withdraw "
29+
" b) balance "
30+
" q) quit\n"
31+
"> "
32+
)
33+
if operation in "dD":
34+
amount = float(input("Enter the deposit amount: "))
35+
deposit(amount)
36+
elif operation in "wW":
37+
amount = float(input("Enter the withdrawal amount: "))
38+
withdraw(amount)
39+
elif operation in "bB":
40+
print(f"Current balance: ${get_balance():,.2f}")
41+
elif operation in "qQ":
42+
print("Goodbye!")
43+
break
44+
else:
45+
print("Invalid operation. Please try again.")
46+
47+
48+
main()
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
config = {
2+
"base_url": "http://127.0.0.1:5000/api",
3+
"timeout": 30,
4+
}
5+
6+
7+
def update_config(**kwargs):
8+
for key, value in kwargs.items():
9+
if key in {"api_key", "base_url", "timeout"}:
10+
config[key] = value
11+
else:
12+
raise KeyError(key)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"database": {
3+
"host": "localhost",
4+
"port": 5432,
5+
"name": "database.db",
6+
"user": "username",
7+
"password": "secret"
8+
},
9+
"api_key": "111222333",
10+
"base_url": "https://example.com/api",
11+
"timeout": 60
12+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def increment(value=0):
2+
return value + 1
3+
4+
5+
counter = increment()
6+
counter = increment(counter)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import webbrowser
2+
3+
import requests
4+
5+
API_KEY = "DEMO_KEY"
6+
BASE_URL = "https://api.nasa.gov/planetary"
7+
TIMEOUT = 3
8+
9+
10+
def load_earth_image(date):
11+
endpoint = f"{BASE_URL}/apod"
12+
try:
13+
response = requests.get(
14+
endpoint,
15+
params={
16+
"api_key": API_KEY,
17+
"date": date,
18+
},
19+
timeout=TIMEOUT,
20+
)
21+
except requests.exceptions.RequestException as e:
22+
print(f"Error connecting to API: {e}")
23+
return
24+
25+
try:
26+
url = response.json()["url"]
27+
except KeyError:
28+
print(f"No image available on {date}")
29+
return
30+
31+
webbrowser.open(url)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import json
2+
3+
4+
def set_config_key(key, value):
5+
globals()[key] = value
6+
7+
8+
with open("config.json") as json_config:
9+
for key, value in json.load(json_config).items():
10+
set_config_key(key, value)

0 commit comments

Comments
 (0)