Skip to content

Commit 409d240

Browse files
authored
Merge pull request larymak#128 from CoderJoshDK/dictFunction
Dict function
2 parents 90d5782 + 21926d2 commit 409d240

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed

Dictionary_Functions/README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Dictionaries used to call functions
2+
3+
## Dictionaries can have intresting keys and values.
4+
5+
In python, a function is also an object. You can assign variables to functions and then call a variable.
6+
```py
7+
def foo():
8+
"""Example code"""
9+
x = foo
10+
x()
11+
```
12+
Actually, on the topic of what you can do with a function. It can be used as a variable in a function too
13+
```py
14+
def bar(func):
15+
func()
16+
bar(foo)
17+
```
18+
19+
Python dictionaries can also have anything that is hashable as a key. So not just strings but many objects too. In this demo, we use strings as our keys. But here is an example of a nontraditional key
20+
```py
21+
import datetime
22+
example = {}
23+
timeNow = datetime.datetime.now()
24+
example[timeNow] = "This is valid"
25+
print(example)
26+
```
27+
28+
Python dictionaries can have any object as a value. And since functions are objects, we can assign them into dictionaries. We can then get a value at a given hash and call it.
29+
```py
30+
example['1'] = foo
31+
example['1']()
32+
```
33+
34+
Finally, we want to call these dicts without checking if it a valid key. A common practice in python is to use try and except blocks. Get used to using these blocks. Unlike other languages, it is common place to have these in your code. One major mistake many new programmers make is to `except` on everything. Instead, you should only catch known exceptions. There are many reasons for this but one of the biggest is because you don't want to catch exceptions such as user interupts. If I wanted to kill a program, I would use ctrl+c. But if I catch all exceptions, it wouldn't end the program.
35+
```py
36+
try:
37+
example['9']()
38+
except (KeyError, TypeError) as e:
39+
# Key error is when the dict does not have that key in its list.
40+
# Type error would be called if the dict has values that are not functions but we try to call it.
41+
print("Invalid key or type")
42+
```
43+
44+
---
45+
## Why is this useful?
46+
Imagine if you wanted to do basically the same thing but the only difference was the function being called. Based on some variable, you excecute some other code. Putting it into a dict can make your code more compact and easiear to expand and work with.
47+
```py
48+
if x == 1:
49+
one()
50+
elif x == 2:
51+
two()
52+
...
53+
# Can be converted to
54+
funcs[x]()
55+
```
56+
57+
---
58+
## Running this demo
59+
60+
To run the sample code, first clone the repo.
61+
> `cd Dictionary_Functions` to get into this folder.
62+
> `python dictionaryFunctions.py` to run the demo
63+
64+
---
65+
I hope you learned something. If you want to see what I am up to, check me out at [CoderJoshDK](https://github.com/CoderJoshDK)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def func1():
2+
print("I am func1")
3+
def func2():
4+
print("I am func2")
5+
def func3():
6+
print("I am func3")
7+
def func4():
8+
print("I am func4")
9+
def func5():
10+
print("I am func5")
11+
12+
def end():
13+
print("I hope you learned something about dictionaries in python :)")
14+
return True
15+
16+
17+
def main():
18+
dictOfFunctions = {
19+
'1' : func1,
20+
'2' : func2,
21+
'3' : func3,
22+
'4' : func4,
23+
'5' : func5,
24+
'q' : end
25+
}
26+
27+
print("Welcome to this simple demo! To exit, enter 'q'")
28+
29+
while True:
30+
user = input("Please let me know what function to run (enter a number 1-5)\n> ").lower()
31+
try:
32+
output = dictOfFunctions[user]()
33+
if output:
34+
break
35+
except (KeyError, TypeError) as e:
36+
print("That was an invalid input. Please input either 1-5 or 'q'")
37+
38+
if __name__ == '__main__':
39+
main()

0 commit comments

Comments
 (0)