Skip to content

Dict function #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Dictionary_Functions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Dictionaries used to call functions

## Dictionaries can have intresting keys and values.

In python, a function is also an object. You can assign variables to functions and then call a variable.
```py
def foo():
"""Example code"""
x = foo
x()
```
Actually, on the topic of what you can do with a function. It can be used as a variable in a function too
```py
def bar(func):
func()
bar(foo)
```

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
```py
import datetime
example = {}
timeNow = datetime.datetime.now()
example[timeNow] = "This is valid"
print(example)
```

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.
```py
example['1'] = foo
example['1']()
```

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.
```py
try:
example['9']()
except (KeyError, TypeError) as e:
# Key error is when the dict does not have that key in its list.
# Type error would be called if the dict has values that are not functions but we try to call it.
print("Invalid key or type")
```

---
## Why is this useful?
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.
```py
if x == 1:
one()
elif x == 2:
two()
...
# Can be converted to
funcs[x]()
```

---
## Running this demo

To run the sample code, first clone the repo.
> `cd Dictionary_Functions` to get into this folder.
> `python dictionaryFunctions.py` to run the demo

---
I hope you learned something. If you want to see what I am up to, check me out at [CoderJoshDK](https://github.com/CoderJoshDK)
39 changes: 39 additions & 0 deletions Dictionary_Functions/dictionaryFunctions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
def func1():
print("I am func1")
def func2():
print("I am func2")
def func3():
print("I am func3")
def func4():
print("I am func4")
def func5():
print("I am func5")

def end():
print("I hope you learned something about dictionaries in python :)")
return True


def main():
dictOfFunctions = {
'1' : func1,
'2' : func2,
'3' : func3,
'4' : func4,
'5' : func5,
'q' : end
}

print("Welcome to this simple demo! To exit, enter 'q'")

while True:
user = input("Please let me know what function to run (enter a number 1-5)\n> ").lower()
try:
output = dictOfFunctions[user]()
if output:
break
except (KeyError, TypeError) as e:
print("That was an invalid input. Please input either 1-5 or 'q'")

if __name__ == '__main__':
main()
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ The contribution guidelines are as per the guide [HERE](https://github.com/larym

| SR No | Project | Author |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| 1 | [Ascii Image Converter](https://github.com/larymak/Python-project-Scripts/tree/master/image-ascii) | [Lary Mak](https://github.com/larymak) |
| 1 | [Ascii Image Converter](https://github.com/larymak/Python-project-Scripts/tree/main/image-ascii) | [Lary Mak](https://github.com/larymak) |
| 2 | [DigitalClock](https://github.com/larymak/Python-project-Scripts/tree/main/DigitalClock) | [Logan Ozdyck](https://github.com/ozdyck3) |
| 3 | [Insta Spam Bot](https://github.com/larymak/Python-project-Scripts/tree/main/InstaSpamBot) | [Lary Mak](https://github.com/larymak) |
| 4 | [Pyjokes](https://github.com/larymak/Python-project-Scripts/tree/master/pyjokes) | [Lary Mak](https://github.com/larymak) |
| 5 | [WhatsApp Spambot](https://github.com/larymak/Python-project-Scripts/tree/master/whatsapp-spam) | [Lary Mak](https://github.com/larymak) |
| 4 | [Pyjokes](https://github.com/larymak/Python-project-Scripts/tree/main/pyjokes) | [Lary Mak](https://github.com/larymak) |
| 5 | [WhatsApp Spambot](https://github.com/larymak/Python-project-Scripts/tree/main/whatsapp-spam) | [Lary Mak](https://github.com/larymak) |
| 6 | [Instagram Bot](https://github.com/larymak/Python-project-Scripts/tree/main/InstagramBot) | [Lary Mak](https://github.com/larymak) |
| 7 | [Photo Editor App](https://github.com/larymak/Python-project-Scripts/tree/master/photo%20editor) | [Lary Mak](https://github.com/larymak) |
| 7 | [Photo Editor App](https://github.com/larymak/Python-project-Scripts/tree/main/photo%20editor) | [Lary Mak](https://github.com/larymak) |
| 8 | [Random Name Generator](https://github.com/larymak/Python-project-Scripts/tree/main/RandomNameGen) | [Lary Mak](https://github.com/larymak) |
| 9 | [Web Scrapping](https://github.com/larymak/Python-project-Scripts/tree/main/WebScraping) | [Lary Mak](https://github.com/larymak) |
| 10 | [Random Password Generator](https://github.com/larymak/Python-project-Scripts/tree/main/RandomPassword) | [Gagan prajapatii](https://github.com/Gagan1111) |
Expand Down Expand Up @@ -90,6 +90,6 @@ The contribution guidelines are as per the guide [HERE](https://github.com/larym
| 47 | [Morse Code Converter](https://github.com/HarshitRV/Python-project-Scripts/tree/main/Morse-Code-Converter) | [HarshitRV](https://github.com/HarshitRV) |)
| 48 | [CLI Photo Watermark](https://github.com/odinmay/Python-project-Scripts/tree/main/CLI-Photo-Watermark) | [Odin May](https://github.com/odinmay)
| 49 | [Pomodoro App](https://github.com/HarshitRV/Python-project-Scripts/tree/main/Pomodoro-App) | [HarshitRV](https://github.com/HarshitRV)
| 49 | [BullsAndCows](https://github.com/HarshitRV/Python-project-Scripts/tree/main/BullsAndCows) | [JerryChen](https://github.com/jerrychen1990)
| 49 | [BullsAndCows](https://github.com/larymak/Python-project-Scripts/tree/main/BullsAndCows) | [JerryChen](https://github.com/jerrychen1990)
| 50 | [Minesweeper AI](https://github.com/nrp114/Minsweeper_AI) | [Nisarg Patel](https://github.com/nrp114)
| 51 | [PDF Downloader](https://github.com/Sdccoding/Python-project-Scripts/tree/main/PDF_Downloader) | [Souhardya Das Chowdhury](https://github.com/Sdccoding)