Skip to content

Commit

Permalink
Sample code for the article on variables
Browse files Browse the repository at this point in the history
  • Loading branch information
lpozo committed Oct 2, 2024
1 parent a6c7824 commit d716ae6
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 0 deletions.
3 changes: 3 additions & 0 deletions python-variables/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Variables in Python: Usage and Best Practices

This folder provides the code examples for the Real Python tutorial [Variables in Python: Usage and Best Practices](https://realpython.com/python-variables/).
18 changes: 18 additions & 0 deletions python-variables/colors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
colors: dict[str, str] = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF",
"yellow": "#FFFF00",
"black": "#000000",
"white": "#FFFFFF",
}


# colors: dict[str, tuple[int, int, int]] = {
# "Red": (255, 0, 0),
# "Green": (0, 255, 0),
# "Blue": (0, 0, 255),
# "Yellow": (255, 255, 0),
# "Black": (0, 0, 0),
# "White": (255, 255, 255),
# }
22 changes: 22 additions & 0 deletions python-variables/employees.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Employee:
count = 0

def __init__(self, name, position, salary):
self.name = name
self.position = position
self.salary = salary
type(self).count += 1

def display_profile(self):
print(f"Name: {self.name}")
print(f"Position: {self.position}")
print(f"Salary: ${self.salary}")


jane = Employee("Jane Doe", "Software Engineer", 90000)
jane.display_profile()

john = Employee("John Doe", "Product Manager", 120000)
john.display_profile()

print(f"Total employees: {Employee.count}")
9 changes: 9 additions & 0 deletions python-variables/matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
matrix = [
[9, 3, 8],
[4, 5, 2],
[6, 4, 3],
]

for i in matrix:
for j in i:
print(j)
24 changes: 24 additions & 0 deletions python-variables/scopes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def function():
value = 42
return value


# Global scope
global_variable = "global"


def outer_func():
# Nonlocal scope
nonlocal_variable = "nonlocal"

def inner_func():
# Local scope
local_variable = "local"
print(f"Hi from the '{local_variable}' scope!")

print(f"Hi from the '{global_variable}' scope!")
print(f"Hi from the '{nonlocal_variable}' scope!")
inner_func()


outer_func()
10 changes: 10 additions & 0 deletions python-variables/timeout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
_timeout = 30 # in seconds


def get_timeout():
return _timeout


def set_timeout(seconds):
global _timeout
_timeout = seconds

0 comments on commit d716ae6

Please sign in to comment.