├── .gitignore ├── pills ├── day-001 │ ├── src │ │ ├── requirements.txt │ │ ├── app.py │ │ ├── app2.py │ │ └── README.md │ ├── daily-python-tip-001.png │ └── README.md ├── day-002 │ ├── daily-python-tip-002.png │ └── README.md ├── day-003 │ ├── daily-python-tip-003.png │ └── README.md ├── day-004 │ ├── daily-python-tip-004.png │ └── README.md ├── day-005 │ ├── daily-python-tip-005.png │ └── README.md ├── day-006 │ ├── daily-python-tip-006.png │ └── README.md ├── day-007 │ ├── daily-python-tip-007.png │ └── README.md ├── day-008 │ ├── daily-python-tip-008.png │ └── README.md ├── day-009 │ ├── daily-python-tip-009.png │ └── README.md ├── contrib │ └── CONTRIB-TEMPLATE.md ├── day-039 │ └── README.md ├── day-046 │ └── README.md ├── day-049 │ └── README.md ├── day-019 │ └── README.md ├── day-048 │ └── README.md ├── day-025 │ └── README.md ├── day-018 │ └── README.md ├── day-040 │ └── README.md ├── day-033 │ └── README.md ├── day-043 │ └── README.md ├── day-042 │ └── README.md ├── day-029 │ └── README.md ├── day-044 │ └── README.md ├── day-035 │ └── README.md ├── day-047 │ └── README.md ├── day-030 │ └── README.md ├── day-020 │ └── README.md ├── day-045 │ └── README.md ├── day-031 │ └── README.md ├── day-036 │ └── README.md ├── day-041 │ └── README.md ├── day-026 │ └── README.md ├── day-024 │ └── README.md ├── day-021 │ └── README.md ├── day-037 │ └── README.md ├── day-028 │ └── README.md ├── day-011 │ └── README.md ├── day-038 │ └── README.md ├── day-027 │ └── README.md ├── day-034 │ └── README.md ├── day-016 │ └── README.md ├── day-010 │ └── README.md ├── day-023 │ └── README.md ├── day-017 │ └── README.md ├── day-022 │ └── README.md ├── day-014 │ └── README.md ├── day-032 │ └── README.md ├── day-012 │ └── README.md ├── day-013 │ └── README.md └── day-015 │ └── README.md ├── LICENSE ├── CONTRIBUTING.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | __pycache__ 3 | 4 | .DS_Store 5 | 6 | .vscode -------------------------------------------------------------------------------- /pills/day-001/src/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==1.1.1 2 | werkzeug==0.16.1 -------------------------------------------------------------------------------- /pills/day-001/daily-python-tip-001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-001/daily-python-tip-001.png -------------------------------------------------------------------------------- /pills/day-002/daily-python-tip-002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-002/daily-python-tip-002.png -------------------------------------------------------------------------------- /pills/day-003/daily-python-tip-003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-003/daily-python-tip-003.png -------------------------------------------------------------------------------- /pills/day-004/daily-python-tip-004.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-004/daily-python-tip-004.png -------------------------------------------------------------------------------- /pills/day-005/daily-python-tip-005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-005/daily-python-tip-005.png -------------------------------------------------------------------------------- /pills/day-006/daily-python-tip-006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-006/daily-python-tip-006.png -------------------------------------------------------------------------------- /pills/day-007/daily-python-tip-007.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-007/daily-python-tip-007.png -------------------------------------------------------------------------------- /pills/day-008/daily-python-tip-008.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-008/daily-python-tip-008.png -------------------------------------------------------------------------------- /pills/day-009/daily-python-tip-009.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jefo2k/python-daily-pills/HEAD/pills/day-009/daily-python-tip-009.png -------------------------------------------------------------------------------- /pills/day-001/src/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import logging 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def hello(): 8 | app.logger.info('Main request successfull') 9 | return "Hello World!" 10 | 11 | if __name__ == "__main__": 12 | logging.basicConfig(filename='app.log',level=logging.DEBUG) 13 | app.run(host='0.0.0.0', debug=True) -------------------------------------------------------------------------------- /pills/day-001/src/app2.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import logging 3 | 4 | app = Flask(__name__) 5 | logging.basicConfig(filename='app.log',level=logging.DEBUG) 6 | 7 | @app.route("/") 8 | def hello(): 9 | app.logger.info('Main request successfull') 10 | return "Hello World!" 11 | 12 | if __name__ == "__main__": 13 | app.run(host='0.0.0.0', debug=True) -------------------------------------------------------------------------------- /pills/contrib/CONTRIB-TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] The title of your pill 2 | 3 | A brief introduction of the topic you are writing 4 | 5 | > If you want to make a note, use this 6 | 7 | ## For subsections use this format 8 | 9 | You can describe briefly the subtopic here, before the code. 10 | 11 | ```python 12 | >>> # here you will put your python code... dont forget the >>> 13 | ``` 14 | 15 | > Tip: You can always check other pill files to understand how something was done! 16 | 17 | ## References 18 | 19 | Always put a reference link like that: [text of the link](https://link-to-the-reference). 20 | -------------------------------------------------------------------------------- /pills/day-039/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 039 - Python's built-in HTTP server 2 | 3 | Python has a HTTP server built into the standard library. This is super handy for previewing websites. 4 | 5 | ```python 6 | # Python 3.x 7 | $ python3 -m http.server 8 | 9 | # Python 2.x 10 | $ python -m SimpleHTTPServer 8000 11 | ``` 12 | 13 | > Note: By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL [localhost:8000](localhost:8000) in your web browser. 14 | 15 | ## References 16 | 17 | - The [official python docs](https://docs.python.org/3/library/http.server.html). 18 | - A great [mozilla article](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server) about testing local files vs. remote files. 19 | -------------------------------------------------------------------------------- /pills/day-046/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 046 - Functions as First Class Objects 2 | 3 | What does “Functions as First Class Objects” mean? 4 | 5 | They can be passed as arguments to other functions, returned as values from other functions, and 6 | assigned to variables and stored in data structures. 7 | 8 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 9 | 10 | Example: 11 | 12 | ```python 13 | >>> def myfunc(a, b): 14 | ... return a + b 15 | ... 16 | >>> funcs = [myfunc] 17 | >>> funcs[0] 18 | 19 | >>> funcs[0](2, 3) 20 | 5 21 | ``` 22 | 23 | ## References 24 | 25 | A great [realpython article](https://realpython.com/lessons/functions-first-class-objects-python/). 26 | -------------------------------------------------------------------------------- /pills/day-049/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 049 - Count Objects with Counter 2 | 3 | The `Counter()` function is available in Python’s Collections module. We can use this function to count the frequency of each unique item in an iterable list. This function holds the frequency of each unique item in iterable as a key, value pair. 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | Example: 8 | 9 | ```python 10 | >>> from collections import Counter 11 | >>> list1 = [1,1,1,1,2,2,3,3,3,4,5,5,5,6,6,6,6] 12 | >>> Counter(list1) 13 | Counter({1: 4, 6: 4, 3: 3, 5: 3, 2: 2, 4: 1}) 14 | ``` 15 | 16 | ## References 17 | 18 | A great [gitconnected article](https://levelup.gitconnected.com/10-python-tricks-to-code-like-a-pro-programmer-a5faaf596542). 19 | -------------------------------------------------------------------------------- /pills/day-019/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 019 - Swap two variables in Python 2 | 3 | Two ways to swap the values of two variables: 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | ## Using a temporary variable 8 | 9 | ```python 10 | >>> a = 11 11 | >>> b = 7 12 | 13 | >>> temp = a 14 | >>> a = b 15 | >>> b = temp 16 | 17 | >>> a 18 | 7 19 | >>> b 20 | 11 21 | ``` 22 | 23 | ## Without a temporary variable (Tuple swap) 24 | 25 | ```python 26 | >>> a = 11 27 | >>> b = 7 28 | 29 | >>> a, b = b, a 30 | >>> a 31 | 7 32 | >>> b 33 | 11 34 | ``` 35 | 36 | > If you don't know what a Python tuple is please check out [this pill](../day-016). 37 | 38 | ## References 39 | 40 | From [30secondsofcode](https://www.30secondsofcode.org/articles/s/python-swap-variables). 41 | -------------------------------------------------------------------------------- /pills/day-048/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 048 - Use of Enums 2 | 3 | Enum is a class in Python for creating enumerations, which are a set of symbolic names attached to **unique**, **constant** values. 4 | 5 | In order to create an Enum, it is necessary to create a class which is the name of the Enum that you want. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | Example: 10 | 11 | ```python 12 | >>> class Person: 13 | ... John = 0 14 | ... Paul = 1 15 | ... George = 2 16 | ... Ringo = 3 17 | ... 18 | >>> Person.John 19 | 0 20 | 21 | # using the range function 22 | >>> class Person: 23 | ... John, Paul, George, Ringo = range(4) 24 | ... 25 | >>> Person.Paul 26 | 1 27 | ``` 28 | 29 | ## References 30 | 31 | A nice [towardsdatascience article](https://towardsdatascience.com/12-python-tips-and-tricks-for-writing-better-code-b57e7eea580b). 32 | -------------------------------------------------------------------------------- /pills/day-025/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 025 - Short-circuit evaluation 2 | 3 | One more about conditionals! Now it's time to understand what short-circuit evaluation is all about. 4 | 5 | Its simple! If you call a function or method on the right side of `and` and `or`, they may not be executed depending on the result on the left side. 6 | 7 | Examples: 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | ```python 12 | >>> def test(): 13 | print('function is called') 14 | return True 15 | 16 | >>> True and test() 17 | function is called 18 | True 19 | 20 | >>> False and test() 21 | False 22 | 23 | >>> True or test() 24 | True 25 | 26 | >>> False or test() 27 | function is called 28 | True 29 | ``` 30 | 31 | ## References 32 | 33 | Another great [nkmk blog post](https://note.nkmk.me/en/python-boolean-operation/#:~:text=y-,Short,--circuit%20evaluation). 34 | -------------------------------------------------------------------------------- /pills/day-018/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 018 - Merging two dictionaries with a single expression 2 | 3 | In this little pill we'll show how to merge two dictionaries with a single expression. 4 | 5 | If you don't know what a Python dictionary is please check [this pill](../day-014). 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | ## In Python 3.5+ 10 | 11 | ```python 12 | >>> x = {'a': 1, 'b': 2} 13 | >>> y = {'b': 3, 'c': 4} 14 | >>> z = {**x, **y} 15 | >>> z 16 | {'a': 1, 'b': 3, 'c': 4} 17 | ``` 18 | 19 | ## In Python 2.x 20 | 21 | ```python 22 | >>> x = {'a': 1, 'b': 2} 23 | >>> y = {'b': 3, 'c': 4} 24 | >>> z = dict(x, **y) 25 | >>> x 26 | {'a': 1, 'b': 2} 27 | ``` 28 | 29 | > In both examples Python merges dictionary keys in the order listed in the expression, overwriting duplicates from left to right. 30 | 31 | ## References 32 | 33 | Video from [realpython.com](https://www.youtube.com/watch?v=Duexw08KaC8). 34 | -------------------------------------------------------------------------------- /pills/day-040/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 040 - Comparing Python Objects the Right Way: `is` vs `==` 2 | 3 | There’s a subtle difference between the Python identity operator `is` and the equality operator `==`. 4 | 5 | The `==` operator compares the value or equality of two objects, whereas the Python `is` operator checks whether two variables point to the same object in memory. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | ```python 10 | >>> a = [1, 2, 3] 11 | >>> b = a 12 | 13 | >>> a is b 14 | True 15 | >>> a == b 16 | True 17 | 18 | >>> c = list(a) 19 | 20 | >>> a == c 21 | True 22 | >>> a is c 23 | False 24 | ``` 25 | 26 | > Note: In the vast majority of cases you should use the equality operators == and !=, except when you’re comparing to None. 27 | 28 | ## References 29 | 30 | - A great [geeksforgeeks tutorial](https://www.geeksforgeeks.org/difference-operator-python/). 31 | - A [Realpython](https://realpython.com/courses/python-is-identity-vs-equality/) course. 32 | -------------------------------------------------------------------------------- /pills/day-033/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 033 - Sum an arbitrary number of arguments 2 | 3 | As mentioned in [last pill](../day-032), functions are building blocks in Python. They take zero or more arguments and return a value. Python is pretty flexible in terms of how arguments are passed to a function. 4 | 5 | Let's see an example of a function that sums up an arbitrary number of arguments using `*args`. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | ```python 10 | >>> def addition(*args): 11 | result = 0 12 | for i in args: 13 | result += i 14 | return result 15 | 16 | >>> print(addition()) 17 | 0 18 | >>> addition(1,4) 19 | 5 20 | >>> addition(1,7,3) 21 | 11 22 | ``` 23 | 24 | > Note: The parameters passed to the addition function are stored in a tuple. Thus, we can iterate over the args variable. 25 | 26 | ## References 27 | 28 | A great [towardsdatascience article](https://towardsdatascience.com/10-examples-to-master-args-and-kwargs-in-python-6f1e8cc30749). 29 | -------------------------------------------------------------------------------- /pills/day-043/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 043 - List comprehension tricks you might not know 2 | 3 | Creating lists using list comprehension is more pythonic and easier to read. But did you know that you can create other types of objects with the same technique? 4 | 5 | We’ll show you 2 tricks that you might not be using yet. They’ll help make your code easier to read, and easier to write. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | ## Dictionary comprehension 10 | 11 | ```python 12 | >>> words = ["hello", "old", "friend"] 13 | >>> data = {word: len(word) for word in words} 14 | >>> data 15 | {'hello': 5, 'old': 3, 'friend': 6} 16 | ``` 17 | 18 | ## Filtering 19 | 20 | ```python 21 | >>> words = ['deified', 'radar', 'guns'] 22 | >>> palindromes = [word for word in words if word == word[::-1]] 23 | >>> palindromes 24 | ['deified', 'radar'] 25 | ``` 26 | 27 | ## References 28 | 29 | A [gitconnected article](https://levelup.gitconnected.com/3-python-list-comprehension-tricks-you-might-not-know-yet-5891d904ee76). 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Jeferson Vaz dos Santos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /pills/day-042/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 042 - List Comprehensions 2 | 3 | Python is famous for allowing you to write code that’s elegant, easy to write, and almost as easy to read as plain English. One of the language’s most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code. 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | ```python 8 | # Iterating through a string 9 | >>> h_letters = [ letter for letter in 'human' ] 10 | >>> h_letters 11 | ['h', 'u', 'm', 'a', 'n'] 12 | 13 | # if with List Comprehension 14 | >>> even_list = [ x for x in range(20) if x % 2 == 0 ] 15 | >>> even_list 16 | [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 17 | 18 | # if...else With List Comprehension 19 | >>> obj = ["Even" if i % 2 == 0 else "Odd" for i in range(10)] 20 | >>> obj 21 | ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd'] 22 | ``` 23 | 24 | ## References 25 | 26 | A [programiz tutorial](https://www.programiz.com/python-programming/list-comprehension). 27 | -------------------------------------------------------------------------------- /pills/day-007/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 007 - Python Comments 2 | 3 | Comments can be used to explain Python code. 4 | 5 | Comments can be used to make the code more readable. 6 | 7 | Comments can be used to prevent execution when testing code. 8 | 9 | > Note: Always prefer a clean and more concise code than comments. Check the links in the end of this post about the best use for comments. 10 | 11 | Examples: 12 | 13 | ```python 14 | #This is a comment 15 | print("Hello, World!") 16 | 17 | print("Hello, World!") #This is a comment 18 | 19 | #This is a comment 20 | #written in 21 | #more than just one line 22 | print("Hello, World!") 23 | 24 | """ 25 | This is a comment 26 | written in 27 | more than just one line 28 | """ 29 | print("Hello, World!") 30 | ``` 31 | 32 | ## References 33 | 34 | - A nice [realpyton](https://realpython.com/python-comments-guide/) article about comments. 35 | - In his blog, [Uncle Bob](https://blog.cleancoder.com/uncle-bob/2017/02/23/NecessaryComments.html) discusses the use of comments. 36 | - A [freecodecamp](https://www.freecodecamp.org/news/code-comments-the-good-the-bad-and-the-ugly-be9cc65fbf83/) good article about comments good practices. 37 | -------------------------------------------------------------------------------- /pills/day-029/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 029 - Iterate over two lists or more 2 | 3 | The Pythonic style for iterating through a pair of lists, or more, is to use the function `zip`. 4 | 5 | ## Iterate over two lists of same size 6 | 7 | ```python 8 | >>> l1 = ['a','b','c'] 9 | >>> l2 = [1,2,3] 10 | >>> for x,y in zip(l1,l2): 11 | print(x,y) 12 | 13 | a 1 14 | b 2 15 | c 3 16 | ``` 17 | 18 | ## Iterate over three lists of same size 19 | 20 | ```python 21 | >>> l1 = ['a','b','c'] 22 | >>> l2 = [1,2,3] 23 | >>> l3 = ['hello','hi','bye'] 24 | >>> for x,y,z in zip(l1,l2,l3): 25 | print(x,y,z) 26 | 27 | a 1 hello 28 | b 2 hi 29 | c 3 bye 30 | ``` 31 | 32 | ## Iterate over lists of different sizes 33 | 34 | ```python 35 | >>> l1 = ['a','b','c','d','e','f'] 36 | >>> l2 = [1,2,3] 37 | >>> for x,y in zip(l1,l2): 38 | print(x,y) 39 | 40 | a 1 41 | b 2 42 | c 3 43 | ``` 44 | 45 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 46 | 47 | ## References 48 | 49 | A great [moonbooks article](https://moonbooks.org/Articles/How-to-iterate-over-two-lists-or-more-in-python-/). 50 | -------------------------------------------------------------------------------- /pills/day-044/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 044 - Classes and Objects in Python 2 | 3 | Python is an object oriented programming language. 4 | 5 | Almost everything in Python is an object, with its properties and methods. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | Example: 10 | 11 | ```python 12 | # Create a Class 13 | >>> class Person: 14 | ... def __init__(self, name, age): 15 | ... self.name = name 16 | ... self.age = age 17 | ... def myfunc(self): 18 | ... print("Hello my name is " + self.name) 19 | 20 | # Create Object 21 | >>> p1 = Person("Thor", 1500) 22 | 23 | >>> p1.myfunc() 24 | Hello my name is Thor 25 | ``` 26 | > Note 1: The `__init__()` function is called automatically every time the class is being used to create a new object, also known as constructor in other OO languages. 27 | 28 | > Note 2: The `self` parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. 29 | 30 | ## References 31 | 32 | A great [w3schools article](https://www.w3schools.com/python/python_classes.asp). 33 | -------------------------------------------------------------------------------- /pills/day-006/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 006 - Python Indentation 2 | 3 | Indentation refers to the spaces at the beginning of a code line. 4 | 5 | Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. 6 | 7 | Python uses indentation to indicate a block of code. 8 | 9 | ```python 10 | if 5 > 2: 11 | print("Five is greater than two!") 12 | ``` 13 | 14 | Python will give you an error if you skip the indentation 15 | 16 | ```python 17 | if 5 > 2: 18 | print("Five is greater than two!") # Syntax Error 19 | ``` 20 | 21 | The number of spaces is up to you, but it has to be at least one. 22 | 23 | ```python 24 | if 5 > 2: 25 | print("Five is greater than two!") 26 | if 5 > 2: 27 | print("Five is greater than two!") 28 | ``` 29 | 30 | You have to use the same number of spaces in the same block of code, otherwise Python will give you an error: 31 | 32 | ```python 33 | if 5 > 2: 34 | print("Five is greater than two!") 35 | print("Five is greater than two!") # Syntax Error 36 | ``` 37 | 38 | ## References 39 | 40 | More information about identation [check this link out](https://pythonexamples.org/python-indentation). 41 | -------------------------------------------------------------------------------- /pills/day-035/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 035 - Anonymous functions 2 | 3 | Sometimes, naming a function is not worth the trouble. An example is when you’re sure the function will only be used once. For such cases, Python offers us anonymous functions, also called lambda functions. 4 | 5 | A lambda function can be assigned to a variable, creating a concise way of defining a function: 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | ```python 10 | >>> add_one = lambda x: x + 1 11 | >>> add_one(3) 12 | 4 13 | ``` 14 | 15 | It gets more interesting when you need to use a function as an argument. In such cases, the function is often used only once. As you may know, map applies a function to all elements of an iterable object. We can use a lambda when calling map: 16 | 17 | ```python 18 | >>> numbers = [1, 2, 3, 4] 19 | >>> times_two = map(lambda x: x * 2, numbers) 20 | >>> list(times_two) 21 | [2, 4, 6, 8] 22 | ``` 23 | 24 | > Note: When you need to apply a relatively simple operation on each element of an iterable object, using map() in combination with a lambda function is concise and efficient. 25 | 26 | ## References 27 | 28 | A great [python.land article](https://python.land/deep-dives/functions). 29 | -------------------------------------------------------------------------------- /pills/day-047/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 047 - Create an Iterator 2 | 3 | An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. 4 | 5 | To create an object/class as an iterator you have to implement the methods `__iter__()` and `__next__()` to your object. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | Example: 10 | 11 | ```python 12 | >>> class MySequenceGenerator: 13 | ... def __iter__(self): 14 | ... self.a = 1 15 | ... return self 16 | ... def __next__(self): 17 | ... x = self.a 18 | ... self.a += 1 19 | ... return x 20 | ... 21 | >>> my_generator = MySequenceGenerator() 22 | >>> my_iter = iter(my_generator) 23 | >>> 24 | >>> next(my_iter) 25 | 1 26 | >>> next(my_iter) 27 | 2 28 | >>> next(my_iter) 29 | 3 30 | ``` 31 | 32 | > Note: The `__iter__()` method acts similar to `__init__()` where you can do operations (initializing etc.), but must always return the iterator object itself. 33 | 34 | > Note: The `__next__()` method also allows you to do operations, and must return the next item in the sequence. 35 | 36 | ## References 37 | 38 | A awesome [w3schools article](https://www.w3schools.com/python/python_iterators.asp). 39 | -------------------------------------------------------------------------------- /pills/day-030/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 030 - Nested For Loops 2 | 3 | Loops can be nested in Python, as they can with other programming languages. 4 | 5 | ## Syntax 6 | 7 | ```python 8 | for [first iterating variable] in [outer loop]: # Outer loop 9 | [do something] # Optional 10 | for [second iterating variable] in [nested loop]: # Nested loop 11 | [do something] 12 | ``` 13 | 14 | ## Example 1 15 | 16 | ```python 17 | >>> num_list = [1, 2, 3] 18 | >>> alpha_list = ['a', 'b', 'c'] 19 | >>> for number in num_list: 20 | print(number) 21 | for letter in alpha_list: 22 | print(letter) 23 | 24 | 1 25 | a 26 | b 27 | c 28 | 2 29 | a 30 | b 31 | c 32 | 3 33 | a 34 | b 35 | c 36 | ``` 37 | 38 | ## Example 2 39 | 40 | ```python 41 | >>> list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]] 42 | >>> for list in list_of_lists: 43 | for item in list: 44 | print(item) 45 | ... 46 | hammerhead 47 | great white 48 | dogfish 49 | 0 50 | 1 51 | 2 52 | 9.9 53 | 8.8 54 | 7.7 55 | ``` 56 | 57 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 58 | 59 | ## References 60 | 61 | A nice [digitalocean article](https://www.digitalocean.com/community/tutorials/how-to-construct-for-loops-in-python-3). 62 | -------------------------------------------------------------------------------- /pills/day-020/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 020 - Sort a Dictionary by Value 2 | 3 | To sort a dictionary by value in Python you can use the `sorted()` function. 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | ## Sort in Ascending Order 8 | 9 | ```python 10 | >>> orders = { 11 | 'cappuccino': 54, 12 | 'latte': 56, 13 | 'espresso': 72, 14 | 'americano': 48, 15 | 'cortado': 41 16 | } 17 | >>> sort_orders = sorted(orders.items(), key=lambda x: x[1]) 18 | >>> sort_orders 19 | [('cortado', 41), ('americano', 48), ('cappuccino', 54), ('latte', 56), ('espresso', 72)] 20 | ``` 21 | 22 | ## Sort in Descending Order 23 | 24 | ```python 25 | >>> orders = { 26 | 'cappuccino': 54, 27 | 'latte': 56, 28 | 'espresso': 72, 29 | 'americano': 48, 30 | 'cortado': 41 31 | } 32 | >>> sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True) 33 | >>> sort_orders 34 | [('espresso', 72), ('latte', 56), ('cappuccino', 54), ('americano', 48), ('cortado', 41)] 35 | ``` 36 | 37 | > If you don't know what a Python dictionary is please check out [this pill](../day-014). 38 | 39 | ## References 40 | 41 | From [careerkarma](https://careerkarma.com/blog/python-sort-a-dictionary-by-value/). 42 | -------------------------------------------------------------------------------- /pills/day-008/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 008 - Variables in Python 2 | 3 | Variables are containers for storing data values. 4 | 5 | Examples: 6 | 7 | ```python 8 | # Python has no command for declaring a variable. 9 | # A variable is created the moment you first assign a value to it. 10 | >>> x = 5 11 | >>> y = "John" 12 | >>> print(x) 13 | 5 14 | >>> print(y) 15 | John 16 | 17 | # Variables do not need to be declared with any particular type, 18 | # and can even change type after they have been set. 19 | >>> x = 4 # x is of type int 20 | >>> x = "Sally" # x is now of type str 21 | >>> print(x) 22 | Sally 23 | 24 | # If you want to specify the data type of a variable, this can be done with casting. 25 | >>> x = str(3) # x will be '3' 26 | >>> y = int(3) # y will be 3 27 | >>> z = float(3) # z will be 3.0 28 | 29 | # You can get the data type of a variable with the type() function. 30 | >>> x = 5 31 | >>> y = "John" 32 | >>> print(type(x)) 33 | 34 | >>> print(type(y)) 35 | 36 | 37 | # String variables can be declared either by using single or double quotes: 38 | >>> x = "John" 39 | # is the same as 40 | >>> x = 'John' 41 | 42 | # Variable names are case-sensitive. 43 | >>> a = 4 44 | >>> A = "Sally" 45 | #A will not overwrite a 46 | ``` 47 | 48 | ## References 49 | 50 | More information about variables in Python in [this link](https://realpython.com/python-variables/). 51 | -------------------------------------------------------------------------------- /pills/day-045/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 045 - Inheritance 2 | 3 | Inheritance allows us to define a class that inherits all the methods and properties from another class. 4 | 5 | **Parent class** is the class being inherited from, also called base class. 6 | 7 | **Child class** is the class that inherits from another class, also called derived class. 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | Example: 12 | 13 | ```python 14 | >>> class Person: 15 | ... def __init__(self, fname, lname): 16 | ... self.firstname = fname 17 | ... self.lastname = lname 18 | ... def printname(self): 19 | ... print(self.firstname, self.lastname) 20 | ... 21 | >>> class Student(Person): 22 | ... def __init__(self, fname, lname, year): 23 | ... super().__init__(fname, lname) 24 | ... self.graduationyear = year 25 | ... def welcome(self): 26 | ... print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear) 27 | ... 28 | >>> student = Student("Mike", "Olsen", 2019) 29 | >>> student.welcome() 30 | Welcome Mike Olsen to the class of 2019 31 | ``` 32 | 33 | > Note: The `super()` function allow the child class inherit all the methods and properties from its parent. 34 | 35 | ## References 36 | 37 | Another great [w3schools article](https://www.w3schools.com/python/python_inheritance.asp). 38 | -------------------------------------------------------------------------------- /pills/day-031/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 031 - Intro to Python Functions 2 | 3 | A function is a block of code which only runs when it is called. 4 | 5 | You can pass data, known as parameters, into a function. 6 | 7 | A function can return data as a result. 8 | 9 | ## Creating a Function 10 | 11 | In Python a function is defined using the def keyword: 12 | 13 | ```python 14 | >>> def my_function(fname): ## function definition 15 | print("Hello " + fname) 16 | ``` 17 | 18 | ## Calling a Function 19 | 20 | To call a function, use the function name followed by parenthesis: 21 | 22 | ```python 23 | >>> def my_function(fname): 24 | print("Hello " + fname) 25 | 26 | >>> my_function("World!") ## function call 27 | Hello World! 28 | ``` 29 | 30 | ## Arguments 31 | 32 | Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma: 33 | 34 | ```python 35 | >>> def my_function(fname): ## function argument: fname 36 | print("Hello " + fname) 37 | 38 | >>> my_function("Jefo") 39 | Hello Jefo 40 | >>> my_function("Ana") 41 | Hello Ana 42 | >>> my_function("World!") 43 | Hello World! 44 | ``` 45 | 46 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 47 | 48 | ## References 49 | 50 | A awesome [w3schools article](https://www.w3schools.com/python/python_functions.asp). 51 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | First off, thank you for considering contributing to Python daily pills. It's people like you that keep the world safe from bad Python code. 4 | 5 | ## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), So All Project Changes Happen Through Pull Requests 6 | 7 | Pull requests are the best way to propose changes to the codebase (we use [Github Flow](https://guides.github.com/introduction/flow/index.html)). We actively welcome your pull requests: 8 | 9 | 1. First [check](./README.md) if the content you want to contribute already exists. 10 | 1. If doesn't, fork the repo and create your branch from `main`. 11 | 1. Make a copy of the file `pill/contrib/CONTRIB-TEMPLATE.md` in the same folder. Name it like `your_pill_title.md` 12 | 1. Write your pill. 13 | 1. Issue that pull request! 14 | 15 | ## Any contributions you make will be under the MIT Software License 16 | 17 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact us if that's a concern. 18 | 19 | ## Report bugs or typos using Github's [issues](https://github.com/jefo2k/python-daily-pills/issues) 20 | 21 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/jefo2k/python-daily-pills/issues); it's that easy! 22 | 23 | ## License 24 | 25 | By contributing, you agree that your contributions will be licensed under its MIT License. 26 | -------------------------------------------------------------------------------- /pills/day-036/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 036 - Emulate switch/case statements with dicts and lambdas 2 | 3 | Python doesn’t have `switch/case` statements so it’s often necessary to write long `if/elif/else` chains as a workaround. Here’s a little trick you can use to emulate `switch/case` statements in Python using dictionaries and first-class functions. 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | Chained `if/elif/else`, `switch/case` style: 8 | 9 | ```python 10 | >>> def dispatch_if(operator, x, y): 11 | if operator == 'add': 12 | return x + y 13 | elif operator == 'sub': 14 | return x - y 15 | elif operator == 'mul': 16 | return x * y 17 | elif operator == 'div': 18 | return x / y 19 | else: 20 | return None 21 | 22 | >>> dispatch_if('add', 2, 8) 23 | 10 24 | >>> dispatch_if('mul', 2, 8) 25 | 16 26 | >>> dispatch_if('unknown', 2, 8) 27 | >>> 28 | ``` 29 | 30 | Pythonic style: 31 | 32 | ```python 33 | >>> def dispatch_dict(operator, x, y): 34 | return { 35 | 'add': lambda: x + y, 36 | 'sub': lambda: x - y, 37 | 'mul': lambda: x * y, 38 | 'div': lambda: x / y, 39 | }.get(operator, lambda: None)() 40 | 41 | >>> dispatch_dict('add', 2, 8) 42 | 10 43 | >>> dispatch_dict('mul', 2, 8) 44 | 16 45 | >>> dispatch_dict('unknown', 2, 8) 46 | >>> 47 | ``` 48 | 49 | ## References 50 | 51 | A cool [realpython lesson](https://realpython.com/courses/emulating-switch-case-python/). 52 | -------------------------------------------------------------------------------- /pills/day-041/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 041 - The Walrus Operator `:=` 2 | 3 | The biggest change in Python 3.8: the introduction of assignment expressions `:=`. This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. 4 | 5 | Assignment expressions allow you to assign and return a value in the same expression. 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | ```python 10 | >>> sample_data = [ 11 | ... {"id": 1, "name": "Amol", "project": False}, 12 | ... {"id": 2, "name": "Kiku", "project": False}, 13 | ... {"id": 3, "name": None, "project": False}, 14 | ... {"id": 4, "name": "Lini", "project": True}, 15 | ... {"id": 4, "name": None, "project": True}, 16 | ... ] 17 | 18 | # With Python 3.8 Walrus Operator 19 | >>> for entry in sample_data: 20 | ... if name := entry.get("name"): 21 | ... print("Found Person:", name) 22 | 23 | Found Person: Amol 24 | Found Person: Kiku 25 | Found Person: Lini 26 | 27 | # Without Walrus Operator 28 | >>> for entry in sample_data: 29 | ... name = entry.get("name") 30 | ... if name: 31 | ... print('Found Person:', name) 32 | 33 | Found Person: Amol 34 | Found Person: Kiku 35 | Found Person: Lini 36 | ``` 37 | 38 | ## References 39 | 40 | - A awesome [realpython tutorial](https://realpython.com/lessons/assignment-expressions/). 41 | - The [Python 3.8 documentation](https://docs.python.org/3/whatsnew/3.8.html). 42 | - [pythonexamples](https://pythonexamples.org/python-walrus-operator/). 43 | -------------------------------------------------------------------------------- /pills/day-026/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 026 - While loops 2 | 3 | Python has two primitive loop commands: 4 | 5 | - `while` loops 6 | - [`for`](../day-027) loops 7 | 8 | This pill will be about while loops, a structure that allows executing a set of instructions as long as a condition is true. Let's dive in some examples: 9 | 10 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 11 | 12 | Print `i` as long as `i` is less than 6: 13 | 14 | ```python 15 | >>> i = 1 16 | >>> while i < 6: 17 | print(i) 18 | i += 1 19 | 20 | 1 21 | 2 22 | 3 23 | 4 24 | 5 25 | ``` 26 | 27 | With the `break` statement we can stop the loop even if the while condition is true: 28 | 29 | ```python 30 | >>> i = 1 31 | >>> while i < 6: 32 | print(i) 33 | if i == 3: 34 | break 35 | i += 1 36 | 37 | 1 38 | 2 39 | 3 40 | ``` 41 | 42 | With the `continue` statement we can stop the current iteration, and continue with the next: 43 | 44 | ```python 45 | >>> i = 0 46 | >>> while i < 6: 47 | i += 1 48 | if i == 3: 49 | continue 50 | print(i) 51 | 52 | 1 53 | 2 54 | 4 55 | 5 56 | 6 57 | ``` 58 | 59 | With the `else` statement we can run a block of code once when the condition no longer is true: 60 | 61 | ```python 62 | >>> i = 1 63 | >>> while i < 6: 64 | print(i) 65 | i += 1 66 | else: 67 | print("i is no longer less than 6") 68 | 69 | 1 70 | 2 71 | 3 72 | 4 73 | 5 74 | i is no longer less than 6 75 | ``` 76 | 77 | ## References 78 | 79 | - A [w3schools tutorial](https://www.w3schools.com/python/python_while_loops.asp). 80 | - A [realpython tutorial](https://realpython.com/python-while-loop/). 81 | -------------------------------------------------------------------------------- /pills/day-024/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 024 - Chain of multiple comparisons 2 | 3 | Continuing in the conditionals topic, an interesting Python's feature is that comparisons can be chained. 4 | 5 | You can write `a < x and x < b` as `a < x < b` like in mathematics. 6 | 7 | Formally, if `a,b, c, ..., y, z` are expressions and `op1, op2, ..., opN` are comparison operator (such as `<` or `>`), the following two are equivalent: 8 | 9 | ```python 10 | a op1 b op2 c ... y opN z 11 | a op1 b and b op2 c and ... y opN z 12 | ``` 13 | 14 | Examples: 15 | 16 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 17 | 18 | ```python 19 | >>> x = 15 20 | >>> 10 < x and x < 20 21 | True 22 | >>> 10 < x < 20 # equivalent to: 10 < x and x < 20 23 | True 24 | 25 | >>> y = 25 26 | >>> 0 < x and x < 20 and 20 < y and y < 30 27 | True 28 | >>> 10 < x < 20 < y < 30 # equivalent to: 0 < x and x < 20 and 20 < y and y < 30 29 | True 30 | ``` 31 | 32 | ## Most common uses 33 | 34 | When a range of numbers is used as a condition, chained comparisons is useful: 35 | 36 | ```python 37 | >>> x = 15 38 | >>> if 10 < x < 20: 39 | print('result: 10 < x < 20') 40 | else: 41 | print('result: x <= 10 or 20 <= x') 42 | 43 | result: 10 < x < 20 44 | 45 | ``` 46 | 47 | Check if multiple values are all equal is another case where chaining comes in handy: 48 | 49 | ```python 50 | >>> a = 10 51 | >>> b = 10 52 | >>> c = 10 53 | >>> if a == b == c: 54 | print('all equal') 55 | else: 56 | print('not all equal') 57 | 58 | all equal 59 | ``` 60 | 61 | ## References 62 | 63 | A great [nkmk blog post](https://note.nkmk.me/en/python-chain-comparisons/). 64 | -------------------------------------------------------------------------------- /pills/day-004/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 004 - Find element in a list 2 | 3 | Now it's time to learn how to find if an element is inside a list. 4 | 5 | ## Symptoms 6 | 7 | You are using a for loop and testing each element to check if it is in the list. 8 | 9 | ## Remedy 10 | 11 | Python offers at least 2 (two) more concise ways to check whether an element is part of a list: 12 | 13 | ```python 14 | >>> avengers = ['Spider-Man', 'Ant-Man', 'Thor', 'Hulk', 'Captain America', 'Black Panther', 'Iron Man'] 15 | 16 | # using index function to find the location of an item 17 | >>> idx = avengers.index('Hulk') 18 | >>> idx 19 | 3 # 0 based index 20 | >>> idx = avengers.index('Superman') 21 | Traceback (most recent call last): 22 | ValueError: 'Superman' is not in list # Error! Superman isn't in the list 23 | 24 | # using in operator to check if something is inside a list 25 | >>> if 'Thor' in avengers: 26 | print('Thor is an Avenger!') 27 | else: 28 | print('Not an Avenger...') 29 | ... 30 | Thor is an Avenger! 31 | ``` 32 | 33 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 34 | 35 | ## Explanation 36 | 37 | The `index` function returns a position of an element on a list if it exists. Return a `ValueError` if the element isn't in the list. 38 | 39 | The `in` operator check if the element is inside a list. 40 | 41 | ## References 42 | 43 | For more details about find a element on a list, check this links: 44 | 45 | - Index function in [datacamp](https://www.datacamp.com/community/tutorials/python-list-index) 46 | - In operator in [w3schools](https://www.w3schools.com/python/python_operators.asp#:~:text=Python-,Membership,-Operators) 47 | -------------------------------------------------------------------------------- /pills/day-021/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 021 - Python slice notation 101 2 | 3 | Python supports slice notation for any sequential data type like [lists](../day-013), strings, [tuples](../day-016), bytes, bytearrays, and ranges. 4 | 5 | Slice notation it's pretty simple: 6 | 7 | ```shell 8 | a[start:stop] # items start through stop-1 9 | a[start:] # items start through the rest of the list 10 | a[:stop] # items from the beginning through stop-1 11 | a[:] # a copy of the whole list 12 | ``` 13 | 14 | There is also the `step` value, which can be used with any of the above: 15 | 16 | ```shell 17 | a[start:stop:step] # start through not past stop, by step 18 | ``` 19 | 20 | `start` or `stop` may be a negative number, which means it counts from the end of the list instead of the beginning. So: 21 | 22 | ```shell 23 | a[-1] # last item in the list 24 | a[-2:] # last two items in the list 25 | a[:-2] # everything except the last two items 26 | ``` 27 | 28 | Similarly, step may be a negative number: 29 | 30 | ```shell 31 | a[::-1] # all items in the list, reversed 32 | a[1::-1] # the first two items, reversed 33 | a[:-3:-1] # the last two items, reversed 34 | a[-3::-1] # everything except the last two items, reversed 35 | ``` 36 | 37 | > Note: Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for `a[:-2]` and `a` only contains one element, you get an `empty list` instead of an `error`. Sometimes you would prefer the `error`, so you have to be aware that this may happen. 38 | 39 | In the next [pill](../day-022) we are going to show some examples. 40 | 41 | ## References 42 | 43 | From this nice [stackoverflow thread](https://stackoverflow.com/questions/509211/understanding-slice-notation?page=1&tab=votes#tab-top). 44 | -------------------------------------------------------------------------------- /pills/day-001/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 001 - What does `if __name__ == "__main__":` do? 2 | 3 | For this pill, we'll use a simple [flask app](./src). 4 | 5 | ## Symptoms 6 | 7 | Take a look in the `app.py` code: 8 | 9 | ```python 10 | from flask import Flask 11 | import logging 12 | 13 | app = Flask(__name__) 14 | 15 | @app.route("/") 16 | def hello(): 17 | app.logger.info('Main request successfull') # logger been used 18 | return "Hello World!" 19 | 20 | if __name__ == "__main__": 21 | logging.basicConfig(filename='app.log',level=logging.DEBUG) # logger been initialized 22 | app.run(host='0.0.0.0', debug=True) 23 | ``` 24 | 25 | If you use `flask run` to start your app the app.log file will not be created. 26 | 27 | Instead, usign `python app.py` to start the app, the log file will be created. 28 | 29 | ## Remedy 30 | 31 | To solve this issue in both app start strategies, one option is move `logging.basicConfig` out of the `if` statement as such: 32 | 33 | ```python 34 | from flask import Flask 35 | import logging 36 | 37 | app = Flask(__name__) 38 | logging.basicConfig(filename='app.log',level=logging.DEBUG) # <-- logger been initialized moved 39 | 40 | @app.route("/") 41 | def hello(): 42 | app.logger.info('Main request successfull') # logger been used 43 | return "Hello World!" 44 | 45 | if __name__ == "__main__": 46 | app.run(host='0.0.0.0', debug=True) 47 | ``` 48 | 49 | ## Explanation 50 | 51 | When using `flask run` the app.py is loaded as module, and the if statement is evaluated as false. 52 | 53 | ## References 54 | 55 | If you want more info about how main function works in python: 56 | 57 | - A [realpython](https://realpython.com/python-main-function/) article 58 | - A [stackoverflow](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) thread 59 | -------------------------------------------------------------------------------- /pills/day-001/src/README.md: -------------------------------------------------------------------------------- 1 | # Simple Flask app 2 | 3 | Follow this instructions to run the simple flash app. 4 | 5 | ## Prerequisites 6 | 7 | You must have [Python 3+](https://www.python.org/downloads/) installed. 8 | 9 | ## Install dependencies 10 | 11 | Just install the dependencies from `requirements.txt` file. 12 | 13 | ```bash 14 | > pip install -r requirements.txt 15 | ``` 16 | 17 | > Optional: You could use virtualenv instead of install dependencies globally. Take a look here for [more](https://docs.python-guide.org/dev/virtualenvs/#:~:text=virtualenv%20is%20a%20tool%20to,standalone%2C%20in%20place%20of%20Pipenv.) info. 18 | 19 | ## Run using `flask run` - The preferred way to start the development server 20 | 21 | Use the FLASK_APP environment variable to point the command at your app. Set FLASK_ENV=development to run with the debugger and reloader. 22 | 23 | for MacOs and Linux users: 24 | 25 | ```bash 26 | > export FLASK_APP=app 27 | > export FLASK_ENV=development 28 | > flask run 29 | ``` 30 | 31 | On Windows CMD, use set instead of export. 32 | 33 | ```bash 34 | > set FLASK_APP=app 35 | > set FLASK_ENV=development 36 | > flask run 37 | ``` 38 | 39 | For PowerShell, use $env: 40 | 41 | ```bash 42 | > $env:FLASK_APP = "app" 43 | > $env:FLASK_APP = "development" 44 | > flask run 45 | ``` 46 | 47 | ## Run `python app.py` 48 | 49 | ```bash 50 | > python app.py 51 | ``` 52 | 53 | The `python app.py` command runs a Python file and sets __name__ == "__main__". The main block calls app.run(), and it will run the development server. 54 | 55 | ```python 56 | if __name__ == "__main__": 57 | app.run(host='0.0.0.0', debug=True) 58 | ``` 59 | 60 | > Never use this command to deploy publicly, use a production WSGI server such as Gunicorn, uWSGI, Waitress, or mod_wsgi. 61 | 62 | > To run the app2.py just change the name from `app` to `app2`. -------------------------------------------------------------------------------- /pills/day-005/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 005 - The Python Command Line (REPL) 2 | 3 | To test a short amount of code in python sometimes it is quickest and easiest not to write the code in a file. This is made possible because Python can be used as a command line in an environment called REPL. 4 | 5 | REPL stands for Read, Evaluate, Print, Loop. The REPL is how you interact with the Python Interpreter. 6 | 7 | With Python installed, type the following on the Windows, Mac or Linux command line: 8 | 9 | ```python 10 | > python 11 | ``` 12 | 13 | Or, if the "python" command did not work, you can try "py": 14 | 15 | ```python 16 | > py 17 | ``` 18 | 19 | The result must be something like that: 20 | 21 | ```python 22 | Python 3.7.2 (default, Apr 6 2020, 14:21:53) 23 | [Clang 11.0.3 (clang-1103.0.32.29)] on darwin 24 | Type "help", "copyright", "credits" or "license" for more information. 25 | >>> 26 | ``` 27 | 28 | > Note, in the REPL three arrows >>> indicate a line of input given at the prompt. If you see these arrows in example code, don’t copy them into your own REPL. Later, when we run out Python code from files, you will no longer see the triple arrows. 29 | 30 | From there you can try some Python commands: 31 | 32 | ```python 33 | # My REPL. Don't copy the >>> symbols, that means the code was entered 34 | # into the prompt. 35 | # 36 | # If the line does not start with >>>, that means it is output, 37 | # not input 38 | >>> message = "Hello!" 39 | >>> message 40 | 'Hello!' 41 | >>> x = 5 42 | >>> y = 3 43 | >>> x + y 44 | 8 45 | >>> x - y 46 | 2 47 | >>> x * y 48 | 15 49 | >>> x / y 50 | 1.6666666666666667 51 | >>> 52 | ``` 53 | 54 | To quit REPL: 55 | 56 | ```python 57 | >>> quit() 58 | ``` 59 | 60 | ## References 61 | 62 | For more info about Python interpreter (REPL) [click here](https://www.tutorialsteacher.com/python/python-interective-shell). 63 | -------------------------------------------------------------------------------- /pills/day-002/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 002 - The dir function 2 | 3 | In this pill we will cover a powerful inbuilt function in Python3, the `dir` funcition. 4 | 5 | ## Symptoms 6 | 7 | You are not sure about the attributes and methods of an object. 8 | 9 | ## Remedy 10 | 11 | Use the `dir` function: 12 | 13 | ```python 14 | >>> s = 'a simple string' 15 | >>> print(dir(s)) 16 | 17 | ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 18 | ``` 19 | 20 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 21 | 22 | ## Explanation 23 | 24 | The dir function returns a list of valid attributes for the object in its argument, which means we can use it to return an object’s methods. 25 | 26 | > Note: dir only provides an interesting set of names more than a full list. 27 | 28 | ## References 29 | 30 | For more details about the dir function, [check this out](https://docs.python.org/3/library/functions.html#dir). 31 | -------------------------------------------------------------------------------- /pills/day-003/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 003 - Sorting lists 2 | 3 | This time we will show how easy sort a list in Python is. 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | > Note: A more in-depth pill about Python Lists can be found [here](../day-013). 8 | 9 | ## Symptoms 10 | 11 | You need to put the elements of a list in order and don't know how. 12 | 13 | ## Remedy 14 | 15 | Use `sort` function: 16 | 17 | ```python 18 | # sorting a number list 19 | >>> lst = [334, 5, 2, -4, 0, 23, 64, 85, 9, 4] 20 | >>> lst_sorted = sorted(lst) 21 | >>> lst_sorted 22 | [-4, 0, 2, 4, 5, 9, 23, 64, 85, 334] 23 | # descending order 24 | >>> lst_sorted_reverse = sorted(lst, reverse=True) 25 | >>> lst_sorted_reverse 26 | [334, 85, 64, 23, 9, 5, 4, 2, 0, -4] 27 | 28 | # sorting a string list 29 | >>> avengers = ['Spider-Man', 'Ant-Man', 'Thor', 'Hulk', 'Captain America', 'Black Panther', 'Iron Man'] 30 | >>> avengers_sorted = sorted(avengers) 31 | >>> avengers_sorted 32 | ['Ant-Man', 'Black Panther', 'Captain America', 'Hulk', 'Iron Man', 'Spider-Man', 'Thor'] 33 | # descending order 34 | >>> avengers_sorted_reverse = sorted(avengers, reverse=True) 35 | >>> avengers_sorted_reverse 36 | ['Thor', 'Spider-Man', 'Iron Man', 'Hulk', 'Captain America', 'Black Panther', 'Ant-Man'] 37 | ``` 38 | 39 | ## Explanation 40 | 41 | The `sorted` function sorts the elements of a given iterable in a specific order (either ascending or descending) and returns the sorted iterable as a list. 42 | 43 | The syntax of the `sorted` function is: 44 | 45 | ```python 46 | sorted(iterable, key=None, reverse=False) 47 | ``` 48 | 49 | ## References 50 | 51 | For more details about sorting lists check this links: 52 | 53 | - [docs.python.org](https://docs.python.org/3/library/stdtypes.html?highlight=sort#list.sort) 54 | - [programiz](https://www.programiz.com/python-programming/methods/built-in/sorted) 55 | -------------------------------------------------------------------------------- /pills/day-037/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 037 - Shrink your code with lambdas 2 | 3 | For programmers who are skilled at reducing their codes into simple logical statements, [Lambda](../day-035) functions help shrink the number of lines dramatically. 4 | 5 | Lets see some examples: 6 | 7 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 8 | 9 | Take a look of this function: 10 | 11 | ```python 12 | >>> def mult_int(original, multiplier): 13 | return original * multiplier 14 | 15 | >>> mult_int(5, 11) 16 | 55 17 | ``` 18 | 19 | The condensed version, with a `lambda` function, will be like that: 20 | 21 | ```python 22 | >>> mult_int = lambda i, j : i * j 23 | >>> mult_int(5, 11) 24 | 55 25 | ``` 26 | 27 | A more complicated one: 28 | 29 | ```python 30 | >>> def complicated_function(a, b, c, d, e): 31 | return ((a+b) / (c+d)) * e 32 | 33 | >>> complicated_function(1, 2, 3, 4, 5) 34 | 2.142857142857143 35 | ``` 36 | 37 | Again we can condense this entire function into a `lambda` function: 38 | 39 | ```python 40 | >>> complicated_function = lambda i,j,k,l,m : ((i + j) / (k + l)) * m 41 | >>> complicated_function(1, 2, 3, 4, 5) 42 | 2.142857142857143 43 | ``` 44 | 45 | Lets dig in a example using `If-Else` statements to create much more interesting function: 46 | 47 | ```python 48 | >>> def odd_even(figure): 49 | if figure % 2 == 0: 50 | return 'Number is Even' 51 | else: 52 | return 'Number is Odd' 53 | 54 | >>> odd_even(2) 55 | 'Number is Even' 56 | ``` 57 | 58 | This too can be collapsed into a one-line `lambda` function: 59 | 60 | ```python 61 | >>> odd_even_lambda = lambda i: 'Number is Even' if i % 2 ==0 else 'Number is Odd' 62 | >>> odd_even_lambda(3) 63 | 'Number is Odd' 64 | ``` 65 | 66 | ## References 67 | 68 | A great [towardsdatascience article](https://towardsdatascience.com/pythonic-tips-tricks-working-with-lambda-987444d80517). 69 | -------------------------------------------------------------------------------- /pills/day-028/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 028 - The `range()` function 2 | 3 | The `range()` function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. 4 | 5 | It is a built-in function that returns a `range` object which we can iterate using a [`for`](../day-027) loop. 6 | 7 | ## Syntax 8 | 9 | ```python 10 | range(start, stop[, step]) 11 | ``` 12 | 13 | ## `range(stop)` 14 | 15 | When you pass only one argument to the range(), it will generate a sequence of integers starting from 0 to stop -1. 16 | 17 | ```python 18 | # stop = 6 19 | >>> for i in range(6): 20 | print(i) 21 | 22 | 0 23 | 1 24 | 2 25 | 3 26 | 4 27 | 5 28 | ``` 29 | 30 | > Note: As you can see in the output, We got six integers starting from 0 to 5. If you notice, `range()` didn’t include 6 in its result because it generates numbers up to the stop number but never includes the stop number in its result. 31 | 32 | ## `range(start, stop)` 33 | 34 | When you pass two arguments to the range(), it will generate integers starting from the start number to stop -1. 35 | 36 | ```python 37 | # start = 10 38 | # stop = 16 39 | >>> for i in range(10, 16): 40 | print(i) 41 | 42 | 10 43 | 11 44 | 12 45 | 13 46 | 14 47 | 15 48 | ``` 49 | 50 | ## `range(start, stop, step)` 51 | 52 | When you pass all three arguments to the range(), it will return a sequence of numbers, starting from the start number, increments by step number, and stops before a stop number. 53 | 54 | ```python 55 | # start = 10 56 | # stop = 50 57 | # step = 5 58 | >>> for i in range(10, 40, 5): 59 | print(i) 60 | 61 | 10 62 | 15 63 | 20 64 | 25 65 | 30 66 | 35 67 | ``` 68 | 69 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 70 | 71 | ## References 72 | 73 | - A [pynative tutorial](https://pynative.com/python-range-function/). 74 | - A [w3schools tutorial](https://www.w3schools.com/python/ref_func_range.asp). 75 | -------------------------------------------------------------------------------- /pills/day-011/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 011 - Python Operators (Part 1) 2 | 3 | Python divides the operators in the following groups: 4 | 5 | - Arithmetic operators 6 | - Assignment operators 7 | - Comparison operators 8 | - Logical operators 9 | - Identity operators 10 | - Membership operators 11 | - Bitwise operators 12 | 13 | This is the last of a serie of two pills about Python operators. In this one we are going to cover Identity, Membership and Bitwise operators. For the first pill in this serie, [click here](../day-010). 14 | 15 | ## Python Identity Operators 16 | 17 | Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: 18 | 19 | Operator | Description | Example 20 | --- | --- | --- 21 | `is` | Returns True if both variables are the same object | `x is y` 22 | `is not` | Returns True if both variables are not the same object | `x is not y` 23 | 24 | ## Python Membership Operators 25 | 26 | Membership operators are used to test if a sequence is presented in an object: 27 | 28 | Operator | Description | Example 29 | --- | --- | --- 30 | `in` | Returns True if a sequence with the specified value is present in the object | `x in y` 31 | `not in` | Returns True if a sequence with the specified value is not present in the object | `x not in y` 32 | 33 | ## Python Bitwise Operators 34 | 35 | Bitwise operators are used to compare (binary) numbers: 36 | 37 | Operator | Name | Description 38 | --- | --- | --- 39 | & | AND | Sets each bit to 1 if both bits are 1 40 | \| | OR | Sets each bit to 1 if one of two bits is 1 41 | ^ | XOR | Sets each bit to 1 if only one of two bits is 1 42 | ~ | NOT | Inverts all the bits 43 | << | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off 44 | \>\> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off 45 | 46 | ## References 47 | 48 | More information about all Python operators in [this link](https://www.w3schools.com/python/python_operators.asp). 49 | -------------------------------------------------------------------------------- /pills/day-038/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 038 - 6 ways to reverse a string in Python 2 | 3 | Python String doesn’t have a built-in `reverse()` function. However, there are various ways to reverse a string in Python. 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | ## Using `for` Loop 8 | 9 | ```python 10 | >>> string = "Hello World!" 11 | >>> reversed_string = "" 12 | >>> for c in string: 13 | reversed_string = c + reversed_string 14 | 15 | >>> reversed_string 16 | '!dlroW olleH' 17 | ``` 18 | 19 | ## Using `while` Loop 20 | 21 | ```python 22 | >>> string = "Hello World!" 23 | >>> reversed_string = "" 24 | >>> length = len(string) - 1 25 | >>> while length >= 0: 26 | reversed_string = reversed_string + string[length] 27 | length = length - 1 28 | 29 | >>> reversed_string 30 | '!dlroW olleH' 31 | ``` 32 | 33 | ## Using [`join()`](https://docs.python.org/3/library/stdtypes.html#str.join) and [`reversed()`](https://docs.python.org/3/library/functions.html#reversed) 34 | 35 | ```python 36 | >>> string = "Hello World!" 37 | >>> ''.join(reversed(string)) 38 | '!dlroW olleH' 39 | ``` 40 | 41 | ## Using recursion 42 | 43 | ```python 44 | >>> def reverse_recursion(s): 45 | if len(s) == 0: 46 | return s 47 | else: 48 | return reverse_recursion(s[1:]) + s[0] 49 | 50 | >>> reverse_recursion("Hello World!") 51 | '!dlroW olleH' 52 | ``` 53 | 54 | ## Using List `reverse()` 55 | 56 | ```python 57 | >>> string = "Hello World!" 58 | >>> temp_list = list(string) 59 | >>> temp_list.reverse() 60 | >>> ''.join(temp_list) 61 | '!dlroW olleH' 62 | ``` 63 | 64 | ## Using slicing 65 | 66 | ```python 67 | >>> string = "Hello World!" 68 | >>> string[::-1] 69 | '!dlroW olleH' 70 | ``` 71 | 72 | > Note: The fastest (and easiest?) way is to use a slice that steps backwards, -1. 73 | 74 | ## References 75 | 76 | - A nice [journaldev article](https://www.journaldev.com/23647/python-reverse-string). 77 | - Another great [w3schools tutorial](https://www.w3schools.com/python/python_howto_reverse_string.asp). 78 | -------------------------------------------------------------------------------- /pills/day-027/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 027 - For Loops 2 | 3 | As the `while` loop we covered in the [last pill](../day-026), a `for` loop is used for iterating over a sequence that is either a list, a tuple, a dictionary, a set, or a string. 4 | 5 | This structure is less like the `for` keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. 6 | 7 | Lets see some examples: 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | Print each fruit in a fruit list: 12 | 13 | ```python 14 | >>> fruits = ["apple", "banana", "cherry"] 15 | >>> for x in fruits: 16 | print(x) 17 | 18 | apple 19 | banana 20 | cherry 21 | ``` 22 | 23 | Even strings are iterable objects, they contain a sequence of characters: 24 | 25 | ```python 26 | >>> for x in "banana": 27 | print(x) 28 | 29 | b 30 | a 31 | n 32 | a 33 | n 34 | a 35 | ``` 36 | 37 | With the `break` statement we can stop the loop before it has looped through all the items: 38 | 39 | ```python 40 | >>> fruits = ["apple", "banana", "cherry"] 41 | >>> for x in fruits: 42 | if x == "banana": 43 | break 44 | print(x) 45 | 46 | apple 47 | ``` 48 | 49 | With the `continue` statement we can stop the current iteration of the loop, and continue with the next: 50 | 51 | ```python 52 | >>> fruits = ["apple", "banana", "cherry"] 53 | >>> for x in fruits: 54 | if x == "banana": 55 | continue 56 | print(x) 57 | 58 | apple 59 | cherry 60 | ``` 61 | 62 | The `else` keyword in a `for` loop specifies a block of code to be executed when the loop is finished: 63 | 64 | ```python 65 | >>> fruits = ["apple", "banana", "cherry"] 66 | >>> for x in fruits: 67 | if x == "banana": 68 | continue 69 | print(x) 70 | else: 71 | print("Finally finished!") 72 | 73 | apple 74 | cherry 75 | Finally finished! 76 | ``` 77 | 78 | > Note: The `else` block will NOT be executed if the loop is stopped by a `break` statement. 79 | 80 | ## References 81 | 82 | A [w3schools tutorial](https://www.w3schools.com/python/python_for_loops.asp). 83 | -------------------------------------------------------------------------------- /pills/day-034/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 034 - Unpacking Argument Lists 2 | 3 | When the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. Who you wanna call? 4 | 5 | For instance, the [`range()`](../day-028) function expects separate start and stop arguments. If they are not available separately you can call the function with the `*`-operator to unpack the arguments out of a list or tuple: 6 | 7 | > Compatibility note: The unpacking generalizations was introduced in Python 3.5. `*[r]` is equivalent to `list(r)` in later versions, <= 3.4. 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | ```python 12 | >>> r1 = range(2, 7) # normal call with separate arguments 13 | >>> list(r1) 14 | [2, 3, 4, 5, 6] 15 | 16 | >>> args = [2, 7] 17 | >>> r2 = range(*args) # call with arguments unpacked from a list 18 | >>> list(r2) 19 | [2, 3, 4, 5, 6] 20 | ``` 21 | 22 | > Note: The parameters passed to the addition function are stored in a tuple. Thus, we can iterate over the args variable. 23 | 24 | In the same fashion, dictionaries can deliver keyword arguments with the `**`-operator: 25 | 26 | ```python 27 | >>> def parrot(voltage, state="a stiff", action="voom"): 28 | print("-- This parrot wouldn't", action) 29 | print("if you put", voltage, "volts through it.") 30 | print("E's", state, "!") 31 | ... 32 | >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} 33 | >>> parrot(**d) 34 | -- This parrot wouldn't VOOM 35 | if you put four million volts through it. 36 | E's bleedin' demised ! 37 | ``` 38 | 39 | Use operator `*` (for tuples) and `**` (for dictionaries): 40 | 41 | ```python 42 | >>> print(*[1], *[2], 3, *[4, 5]) 43 | 1 2 3 4 5 44 | 45 | >>> def fn(a, b, c, d): 46 | print(a, b, c, d) 47 | 48 | >>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4}) 49 | 1 2 3 4 50 | ``` 51 | 52 | ## References 53 | 54 | - Official Python [documentation](https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists). 55 | - What’s New In Python 3.5: [PEP 448 - Additional Unpacking Generalizations](https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-448). 56 | -------------------------------------------------------------------------------- /pills/day-016/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 016 - Built-in Data Structures (Part 3): Tuples 2 | 3 | Tuples are one of 4 built-in data types in Python used to store collections of data, the other 3 are [Sets](../day-017), [Lists](../day-013) and [Dictionaries](../day-014), all with different qualities and usage. 4 | 5 | Tuples are used to store multiple items in a single variable. 6 | 7 | Tuples are the same as lists are with the exception that the data once entered into the tuple cannot be changed no matter what. 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | Creating a Tuple: 12 | 13 | ```python 14 | >>> my_tuple = (1, 2, 3) #create tuple 15 | >>> my_tuple 16 | (1, 2, 3) 17 | 18 | >>> my_other_tuple = tuple([4, 5, 6]) #create tuple from a list 19 | >>> my_other_tuple 20 | (4, 5, 6) 21 | ``` 22 | 23 | > Note: You create a tuple using parenthesis or using the `tuple()` function. 24 | 25 | Accessing Elements: 26 | 27 | ```python 28 | >>> my_tuple2 = (1, 2, 3, 'edureka') #access elements 29 | >>> for x in my_tuple2: 30 | x 31 | ... 32 | 1 33 | 2 34 | 3 35 | 'edureka' 36 | >>> my_tuple2 37 | (1, 2, 3, 'edureka') 38 | >>> my_tuple2[0] 39 | 1 40 | 41 | >>> print(my_tuple2[:]) 42 | (1, 2, 3, 'edureka') 43 | >>> print(my_tuple2[3][4]) #access 4th character of element 3, 0 based index 44 | e 45 | ``` 46 | 47 | Appending Elements: 48 | 49 | ```python 50 | >>> my_tuple = (1, 2, 3) 51 | >>> my_tuple = my_tuple + (4, 5, 6) #add elements 52 | >>> my_tuple 53 | (1, 2, 3, 4, 5, 6) 54 | ``` 55 | 56 | > Note: In the last code snippet, the `+` operator will take another tuple to appended to the original one. The result will be a new tuple assigned to `my_tuple` variable. 57 | 58 | Other Functions: 59 | 60 | ```python 61 | >>> my_tuple = (1, 2, 3, ['hindi', 'python']) 62 | >>> my_tuple[3][0] = 'english' # the list inside a tuple can be modified 63 | >>> my_tuple 64 | (1, 2, 3, ['english', 'python']) 65 | 66 | >>> my_tuple[0] = 0 # will throw an error: Tuples are immutables 67 | TypeError: 'tuple' object does not support item assignment 68 | 69 | >>> my_tuple.count(2) 70 | 1 71 | >>> my_tuple.index(['english', 'python']) 72 | 3 73 | ``` 74 | 75 | ## References 76 | 77 | Check out this [link](https://www.w3schools.com/python/python_tuples.asp) for more details in Python Tuples. 78 | -------------------------------------------------------------------------------- /pills/day-010/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 010 - Python Operators (Part 1) 2 | 3 | Python divides the operators in the following groups: 4 | 5 | - Arithmetic operators 6 | - Assignment operators 7 | - Comparison operators 8 | - Logical operators 9 | - Identity operators 10 | - Membership operators 11 | - Bitwise operators 12 | 13 | This is the first of a serie of two pills about Python operators. In this one we are going to cover Arithmetic, Assignment, Comparison and Logical operators. For the last pill in this serie, [click here](../day-011). 14 | 15 | ## Python Arithmetic Operators 16 | 17 | Arithmetic operators are used with numeric values to perform common mathematical operations: 18 | 19 | Operator | Name | Example 20 | --- | --- | --- 21 | `+` | Addition | `x + y` 22 | `-` | Subtraction | `x - y` 23 | `*` | Multiplication | `x * y` 24 | `/` | Division | `x / y` 25 | `%` | Modulus | `x % y` 26 | `**` | Exponentiation | `x ** y` 27 | `//` | Floor division | `x // y` 28 | 29 | ## Python Assignment Operators 30 | 31 | Assignment operators are used to assign values to variables: 32 | 33 | Operator | Example | Same As 34 | --- | --- | --- 35 | `=` | `x = 5` | `x = 5` 36 | `+=` | `x += 3` | `x = x + 3` 37 | `-=` | `x -= 3` | `x = x - 3` 38 | `*=` | `x *= 3` | `x = x * 3` 39 | `/=` | `x /= 3` | `x = x / 3` 40 | `%=` | `x %= 3` | `x = x % 3` 41 | `//=` | `x //= 3` | `x = x // 3` 42 | `**=` | `x **= 3` | `x = x ** 3` 43 | `&=` | `x &= 3` | `x = x & 3` 44 | `\|=` | `x \|= 3` | `x = x \| 3` 45 | `^=` | `x ^= 3` | `x = x ^ 3` 46 | `>>=` | `x >>= 3` | `x = x >> 3` 47 | `<<=` | `x <<= 3` | `x = x << 3` 48 | 49 | ## Python Comparison Operators 50 | 51 | Comparison operators are used to compare two values: 52 | 53 | Operator | Name | Example 54 | --- | --- | --- 55 | `==` | Equal | `x == y` 56 | `!=` | Not equal | `x != y` 57 | `>` | Greater than | `x > y` 58 | `<` | Less than | `x < y` 59 | `>=` | Greater than or equal to | `x >= y` 60 | `<=` | Less than or equal to | `x <= y` 61 | 62 | ## Python Logical Operators 63 | 64 | Logical operators are used to combine conditional statements: 65 | 66 | Operator | Description | Example 67 | --- | --- | --- 68 | `and` | Returns True if both statements are true | `x < 5 and x < 10` 69 | `or` | Returns True if one of the statements is true | `x < 5 or x < 4` 70 | `not` | Reverse the result, returns False if the result is true | `not(x < 5 and x < 10)` 71 | 72 | ## References 73 | 74 | More information about all Python operators in [this link](https://www.w3schools.com/python/python_operators.asp). 75 | -------------------------------------------------------------------------------- /pills/day-023/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 023 - Conditions and `if..elif..else` statements 2 | 3 | Python supports the usual logical conditions from mathematics: 4 | 5 | - Equals: `a == b` 6 | - Not Equals: `a != b` 7 | - Less than: `a < b` 8 | - Less than or equal to: `a <= b` 9 | - Greater than: `a > b` 10 | - Greater than or equal to: `a >= b` 11 | 12 | Conditions can be combined with the logical operators `and` and `or`: 13 | 14 | - `a < b and b > 0`: The two conditions must be `True` 15 | - `a < b or b > 0`: At least one condition must be `True` 16 | 17 | Conditions can be used in several ways, most commonly in `if` statements and loops. Let's jump to some examples: 18 | 19 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 20 | 21 | ## The `if` statement 22 | 23 | The `if` statement will execute a subsequent code, or code block, when the condition is `True`. 24 | 25 | ```python 26 | >>> a = 33 27 | >>> b = 200 28 | >>> if b > a: 29 | print("b is greater than a") 30 | 31 | b is greater than a 32 | ``` 33 | 34 | > Note: Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. 35 | 36 | ## `elif` statement 37 | 38 | If the previous conditions were not true, the `elif` condition will be evaluated. The subsequent code will be executed if these condition is `True`. 39 | 40 | ```python 41 | >>> a = 33 42 | >>> b = 33 43 | >>> if b > a: 44 | print("b is greater than a") 45 | elif a == b: 46 | print("a and b are equal") 47 | 48 | a and b are equal 49 | ``` 50 | 51 | ## `else` statement 52 | 53 | `else` catches anything which isn't caught by the preceding conditions. 54 | 55 | ```python 56 | >>> a = 200 57 | >>> b = 33 58 | >>> if b > a: 59 | print("b is greater than a") 60 | elif a == b: 61 | print("a and b are equal") 62 | else: 63 | print("a is greater than b") 64 | ... 65 | a is greater than b 66 | ``` 67 | 68 | ## Short Hands 69 | 70 | If you have only one statement to execute, you can put it on the same line as the `if` and `else` statements. 71 | 72 | ```python 73 | >>> a = 2 74 | >>> b = 330 75 | >>> if a < b: print("a is greater than b") 76 | a is greater than b 77 | 78 | >>> print("A") if a > b else print("B") 79 | B 80 | ``` 81 | 82 | > Note: The last short hand example shows a technique known as Ternary Operators, or Conditional Expressions. 83 | 84 | ## References 85 | 86 | [w3schools](https://www.w3schools.com/python/python_conditions.asp). 87 | -------------------------------------------------------------------------------- /pills/day-009/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 009 - Python Data Types 2 | 3 | Variables can store data of different types, and different types can do different things. 4 | 5 | Python has the following data types built-in by default, in these categories: 6 | 7 | Type | Python data type constructor | Example 8 | --- | --- | --- 9 | Text | `str` | `"Hello World"` 10 | Numeric | `int, float, complex` | `2013`, `20.5`, `1j` 11 | Sequence | `list, tuple, range` | `["apple", "banana", "cherry"]`, `("apple", "banana", "cherry")`, `range(6)` 12 | Mapping | `dict` | `{"name" : "John", "age" : 36}` 13 | Set | `set, frozenset` | `{"apple", "banana", "cherry"}`, `frozenset({"apple", "banana", "cherry"})` 14 | Boolean | `bool` | `True` 15 | Binary | `bytes, bytearray, memoryview` | `b"Hello"`, `bytearray(5)`, `memoryview(bytes(5))` 16 | 17 | Examples: 18 | 19 | ```python 20 | # Data type is set when you assign a value to a variable 21 | >>> x = "Hello World" # str 22 | >>> x = 2013 # int 23 | >>> x = 20.5 # float 24 | >>> x = 1j # complex 25 | >>> x = ["apple", "banana", "cherry"] # list 26 | >>> x = ("apple", "banana", "cherry") # tuple 27 | >>> x = range(6) # range 28 | >>> x = {"name" : "John", "age" : 36} # dict 29 | >>> x = {"apple", "banana", "cherry"} # set 30 | >>> x = frozenset({"apple", "banana", "cherry"}) # frozenset 31 | >>> x = True # bool 32 | >>> x = b"Hello" # bytes 33 | >>> x = bytearray(5) # bytearray 34 | >>> x = memoryview(bytes(5)) # memoryview 35 | 36 | # To specify the data type, you can use constructor functions 37 | >>> x = str("Hello World") # str 38 | >>> x = int(20) # int 39 | >>> x = float(20.5) # float 40 | >>> x = complex(1j) # complex 41 | >>> x = list(("apple", "banana", "cherry")) # list 42 | >>> x = tuple(("apple", "banana", "cherry")) # tuple 43 | >>> x = range(6) # range 44 | >>> x = dict(name="John", age=36) # dict 45 | >>> x = set(("apple", "banana", "cherry")) # set 46 | >>> x = frozenset(("apple", "banana", "cherry")) # frozenset 47 | >>> x = bool(5) # bool 48 | >>> x = bytes(5) # bytes 49 | >>> x = bytearray(5) # bytearray 50 | >>> x = memoryview(bytes(5)) # memoryview 51 | 52 | # To get the datatype use the type function 53 | >>> x = 5 54 | print(type(x)) 55 | 56 | ``` 57 | 58 | ## References 59 | 60 | More information about Python data types [in this link](https://www.w3schools.com/python/python_datatypes.asp). -------------------------------------------------------------------------------- /pills/day-017/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 017 - Built-in Data Structures (Part 4): Sets 2 | 3 | Sets are one of 4 built-in data types in Python used to store collections of data, the other 3 are [Tuples](../day-016), [Dictionaries](../day-014), and [Lists](../day-013), all with different qualities and usage. 4 | 5 | Sets are defined within curly brackets 6 | 7 | Sets are collections that are both unordered and unindexed 8 | 9 | > As a result of this, we can't access the elements of a set the way we would a list or a tuple 10 | 11 | Sets don't hold duplicate values 12 | 13 | > Elaborated below 14 | 15 | Creating Sets: 16 | 17 | ```python 18 | >>> my_set = {5,3,9,7} 19 | >>> my_set # observe below how the elements are in a different order than initialized 20 | {9, 3, 5, 7} 21 | >>> my_set = set((1,4,6,8)) # other ways to create a set 22 | >>> my_set 23 | {8, 1, 4, 6} 24 | >>> my_set = set([5,3,9,8]) # lists, tuples and dictionaries can also be created this way 25 | >>> my_set 26 | {8, 9, 3, 5} 27 | ``` 28 | 29 | Set Functions: 30 | 31 | ```python 32 | >>> dir(set) # lists all the set functions (It isn't as scary as it looks, trust me :D) 33 | ['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 34 | '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', 35 | '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', 36 | '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 37 | 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 38 | 'symmetric_difference_update', 'union', 'update'] 39 | 40 | ``` 41 | 42 | Example functions: 43 | 44 | ```python 45 | >>> my_set.add('another element') # adds an element to the set 46 | >>> my_set 47 | {1, 4, 6, 'another element', 8} 48 | >>> my_set.remove('another element') # removes the specified element 49 | >>> my_set 50 | {1, 4, 6, 8} 51 | >>> my_set.pop() # removes a random element 52 | 1 53 | >>> my_set 54 | {4, 6, 8} 55 | ``` 56 | 57 | Duplicate elements: 58 | 59 | ```python 60 | >>> my_set = {1,1,2,3,4,5,6,6,7,7,7,8} 61 | >>> my_set # observe that only a single occurrence of an element is stored 62 | {1, 2, 3, 4, 5, 6, 7, 8} 63 | ``` 64 | 65 | > If you want to remove duplicate elements in a list or a tuple, a neat trick is to convert them into a set first and then back to either a list or tuple :D 66 | 67 | ## References 68 | 69 | Check out this [link](https://www.w3schools.com/python/python_sets.asp) for more details in Python Sets. 70 | -------------------------------------------------------------------------------- /pills/day-022/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 022 - Python slice notation examples 2 | 3 | In the previous [pill](../day-021) we discussed what slice notation is all about. Now it's time to see some examples. 4 | 5 | Basic usage helper, `a[start:stop:step]`, so: 6 | 7 | > Note: Indexing in most of the programming languages, including Python, starts from 0. 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | ```python 12 | >>> sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone'] 13 | >>> sea_creatures[1:4] # from start (1) through stop-1 (4 - 1 = 3) 14 | ['cuttlefish', 'squid', 'mantis shrimp'] 15 | 16 | >>> sea_creatures[1:] # from start (1) through the rest of the list 17 | ['cuttlefish', 'squid', 'mantis shrimp', 'anemone'] 18 | 19 | >>> sea_creatures[:4] # from the beginning (0) through stop-1 (4 - 1 = 3) 20 | ['shark', 'cuttlefish', 'squid', 'mantis shrimp'] 21 | 22 | >>> sea_creatures[:] # a copy of the whole list, same as sea_creatures[::1] 23 | ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone'] 24 | 25 | >>> sea_creatures[::2] # from the beginning to the end using step 2 26 | ['shark', 'squid', 'anemone'] 27 | ``` 28 | 29 | Using negative numbers in `start` or `stop`, which means it counts from the end of the list instead of the beginning: 30 | 31 | ```python 32 | >>> sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone'] 33 | >>> sea_creatures[-1] # last item in the list 34 | 'anemone' 35 | 36 | >>> sea_creatures[-2:] # last two items in the list 37 | ['mantis shrimp', 'anemone'] 38 | 39 | >>> sea_creatures[:-2] # everything except the last two items 40 | ['shark', 'cuttlefish', 'squid'] 41 | 42 | >>> sea_creatures[::-1] # all items in the list, reversed 43 | ['anemone', 'mantis shrimp', 'squid', 'cuttlefish', 'shark'] 44 | 45 | >>> sea_creatures[1::-1] # the first two items, reversed 46 | ['cuttlefish', 'shark'] 47 | 48 | >>> sea_creatures[:-3:-1] # the last two items, reversed 49 | ['anemone', 'mantis shrimp'] 50 | 51 | >>> sea_creatures[-3::-1] # everything except the last two items, reversed 52 | ['squid', 'cuttlefish', 'shark'] 53 | ``` 54 | 55 | > Reminder: If you ask for `a[:-2]` and `a` only contains one element, you get an `empty list` instead of an `error`. Sometimes you would prefer the `error`, so you have to be aware that this may happen. 56 | 57 | ## References 58 | 59 | - A nice [stackoverflow thread](https://stackoverflow.com/questions/509211/understanding-slice-notation?page=1&tab=votes#tab-top). 60 | - This awesome [railsware blog post](https://railsware.com/blog/python-for-machine-learning-indexing-and-slicing-for-lists-tuples-strings-and-other-sequential-types/). 61 | -------------------------------------------------------------------------------- /pills/day-014/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 014 - Built-in Data Structures (Part 2): Dictionaries 2 | 3 | Dictionaries are one of 4 built-in data types in Python used to store collections of data, the other 3 are [Tuples](../day-016), [Sets](../day-017), and [Lists](../day-013), all with different qualities and usage. 4 | 5 | Dictionaries are used to store data values in key:value pairs. 6 | 7 | A dictionary is a collection which is ordered*, changeable and does not allow duplicates. 8 | 9 | > \* As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. 10 | 11 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 12 | 13 | Create Dictionaries: 14 | 15 | ```python 16 | >>> my_dict = {} #empty dictionary 17 | >>> my_dict 18 | {} 19 | 20 | >>> my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements 21 | >>> my_dict 22 | {1: 'Python', 2: 'Java'} 23 | ``` 24 | 25 | Changing and Adding key, value pairs: 26 | 27 | ```python 28 | >>> my_dict = {'First': 'Python', 'Second': 'Java'} 29 | >>> my_dict 30 | {'First': 'Python', 'Second': 'Java'} 31 | 32 | >>> my_dict['Second'] = 'C++' #changing element 33 | >>> my_dict 34 | {'First': 'Python', 'Second': 'C++'} 35 | 36 | >>> my_dict['Third'] = 'Ruby' #adding key-value pair 37 | >>> my_dict 38 | {'First': 'Python', 'Second': 'C++', 'Third': 'Ruby'} 39 | ``` 40 | 41 | Deleting key, value pairs: 42 | 43 | ```python 44 | >>> my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'} 45 | >>> a = my_dict.pop('Third') #pop element (value) 46 | >>> print('Value:', a) 47 | Value: Ruby 48 | >>> my_dict 49 | {'First': 'Python', 'Second': 'Java'} 50 | 51 | >>> b = my_dict.popitem() #pop the key-value pair 52 | >>> print('Key, value pair:', b) 53 | Key, value pair: ('Second', 'Java') 54 | >>> my_dict 55 | {'First': 'Python'} 56 | 57 | >>> my_dict.clear() #empty dictionary 58 | >>> my_dict 59 | {} 60 | ``` 61 | 62 | Access Elements: 63 | 64 | ```python 65 | >>> my_dict = {'First': 'Python', 'Second': 'Java'} 66 | >>> my_dict['First'] #access elements using keys option 1 67 | 'Python' 68 | 69 | >>> my_dict.get('Second') #access elements using keys option 2 70 | 'Java' 71 | ``` 72 | 73 | Other Functions: 74 | 75 | ```python 76 | >>> my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'} 77 | >>> my_dict.keys() #get keys 78 | dict_keys(['First', 'Second', 'Third']) 79 | 80 | >>> my_dict.values() #get values 81 | dict_values(['Python', 'Java', 'Ruby']) 82 | 83 | >>> my_dict.items() #get key-value pairs 84 | dict_items([('First', 'Python'), ('Second', 'Java'), ('Third', 'Ruby')]) 85 | ``` 86 | 87 | ## References 88 | 89 | Check out this [link](https://www.w3schools.com/python/python_dictionaries.asp) for more details in Python Dictionaries. 90 | -------------------------------------------------------------------------------- /pills/day-032/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 032 - Function Parameters or Arguments? 2 | 3 | The terms parameter and argument can be used for the same thing: information that are passed into a function. 4 | 5 | From a function's perspective: 6 | 7 | - A parameter is the variable listed inside the parentheses in the function definition 8 | - An argument is the value that is sent to the function when it is called 9 | 10 | Now, lets see some examples. 11 | 12 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 13 | 14 | ## Number of Arguments 15 | 16 | By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. 17 | 18 | ```python 19 | >>> def my_function(fname, lname): 20 | print(fname + " " + lname) 21 | 22 | >>> my_function("Spider", "Man") 23 | Spider Man 24 | ``` 25 | 26 | > Note: If you try to call the function with 1 or 3 arguments, you will get an error. 27 | 28 | ## Arbitrary Arguments, `*args` 29 | 30 | If you do not know how many arguments that will be passed into your function, add a `*` before the parameter name in the function definition. 31 | 32 | ```python 33 | >>> def my_function(*avengers): 34 | print("The youngest avenger is " + avengers[0]) 35 | 36 | >>> my_function('Spider-Man', 'Thor', 'Hulk', 'Captain America', 'Black Panther', 'Iron Man') 37 | The youngest avenger is Spider-Man 38 | ``` 39 | 40 | > Note: Arbitrary Arguments are often shortened to `*args` in Python documentations. 41 | 42 | ## Keyword Arguments 43 | 44 | You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. 45 | 46 | ```python 47 | >>> def my_function(avenger3, avenger2, avenger1): 48 | print("The greenish avenger is " + avenger3) 49 | ... 50 | >>> my_function(avenger1 = 'Spider-Man', avenger2 = 'Thor', avenger3 = 'Hulk') 51 | The greenish avenger is Hulk 52 | ``` 53 | 54 | > Note: Keyword Arguments are often shortened to `kwargs` in Python documentations. 55 | 56 | ## Arbitrary Keyword Arguments, `**kwargs` 57 | 58 | If you do not know how many keyword arguments that will be passed into your function, add two asterisk: `**` before the parameter name in the function definition. 59 | 60 | ```python 61 | >>> def my_function(**avenger): 62 | print("The blondiest of the blondies is " + avenger["blondiest"]) 63 | ... 64 | >>> my_function(greenish = "Hulk", blondiest = "Thor") 65 | The blondiest of the blondies is Thor 66 | ``` 67 | 68 | > Note: Arbitrary Kword Arguments are often shortened to `**kwargs` in Python documentations. 69 | 70 | ## References 71 | 72 | A awesome [w3schools article](https://www.w3schools.com/python/python_functions.asp). 73 | -------------------------------------------------------------------------------- /pills/day-012/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 012 - Python primitive data types in-depth: string, int, float and boolean 2 | 3 | Primitive data structures are the simplest forms of representing data. 4 | 5 | Python has four primitive data types: 6 | 7 | - Integer 8 | - Float 9 | - String 10 | - Boolean 11 | 12 | Lets deep dive into each one of them: 13 | 14 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 15 | 16 | ## Integer 17 | 18 | An integer is a whole number that could hold a zero, positive or negative value. 19 | 20 | ```python 21 | # positive number 22 | >>> number = 25 23 | 24 | # negative number 25 | >>> negative_number = -23 26 | 27 | >>> zero = 0 28 | ``` 29 | 30 | In Python 3 there are no different integer types as in Python 2.7, which has `int` and `long int`. In Python 3 there is only one integer type, which can store very large numbers: 31 | 32 | ```python 33 | >>> number = 100000000000000000000000 34 | >>> print(type(number)) 35 | # output 36 | ``` 37 | 38 | ## Float 39 | 40 | Float represents real numbers, a data type that is used to define floating decimal points. 41 | 42 | ```python 43 | >>> decimal_number = 25.33 44 | >>> decimal_number_two = 45.2424 45 | ``` 46 | 47 | To convert an `int` or a `string` to a `float` use the `float()` function: 48 | 49 | ```python 50 | >>> number = 5 51 | >>> print(float(number)) 52 | 5.0 53 | 54 | >>> address_number = "33" 55 | >>> print(float(address_number)) 56 | 33.0 57 | ``` 58 | 59 | ## String 60 | 61 | String represents a sequence of characters (text) inside double or single quotes. In Python, strings are immutable so once it's declared the value can't be changed, instead a new object is created: 62 | 63 | ```python 64 | >>> first_string = "Hello" 65 | >>> second_string = first_string 66 | >>> print(first_string) 67 | Hello 68 | >>> print(second_string) 69 | Hello 70 | 71 | # let's change first_string 72 | >>> first_string = "I have changed" 73 | >>> print(first_string) 74 | Hello 75 | ``` 76 | 77 | The string class has a lot of useful methods for string manipulation: 78 | 79 | ```python 80 | >>> first_name = 'ana' 81 | >>> print(first_name.capitalize()) 82 | Ana # First character capitalized 83 | 84 | >>> print(first_name.upper()) 85 | ANA # All string capitalized 86 | 87 | >>> age = 28 88 | >>> "My name is {0} and I'm {1} years old.".format(first_name.capitalize(), age) 89 | 'My name is Ana and I'm 28 years old.' 90 | ``` 91 | 92 | > There are plenty of useful methods to check different things like: if the string `startswith()` or `endswith()` some word, or check if a string `isdigit()` or `isnumeric()` . You can refer to the [Python 3 documentation for a full list of string methods](https://docs.python.org/3/library/stdtypes.html#string-methods) or use the `dir` function, as explained in [this pill](../day-002). 93 | 94 | ## Boolean 95 | 96 | Booleans are used to represent truth values with two constant objects True and False. 97 | 98 | ```python 99 | >>> num = 1 100 | >>> print(bool(num)) 101 | True # since Boolean in numeric can be present as 0 or 1 102 | 103 | ``` 104 | 105 | ## References 106 | 107 | Check out the [official Python 3 docs](https://docs.python.org/3/library/stdtypes.html#built-in-typ) for more details. 108 | -------------------------------------------------------------------------------- /pills/day-013/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 013 - Built-in Data Structures (Part 1): Lists 2 | 3 | Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are [Tuples](../day-016), [Sets](../day-017), and [Dictionaries](../day-014), all with different qualities and usage. 4 | 5 | Lists in Python are used to store collection of heterogeneous items. These are mutable, which means that you can change their content without changing their identity. 6 | 7 | You can recognize lists by their square brackets `[` and `]` that hold elements, separated by a comma `,`. 8 | 9 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 10 | 11 | Create Lists: 12 | 13 | ```python 14 | # string list 15 | >>> fruits = ["apple", "banana", "cherry"] 16 | >>> fruits 17 | ['apple', 'banana', 'cherry'] 18 | 19 | # int list 20 | >>> calories = [52, 89, 50] # calories for each 100 grams 21 | >>> calories 22 | [52, 89, 50] 23 | 24 | # list with strings, integers and boolean values 25 | >>> list = ["abc", 34, True, 40, "male"] 26 | >>> list 27 | ['abc', 34, True, 40, 'male'] 28 | ``` 29 | 30 | Add Elements: 31 | 32 | ```python 33 | >>> fruits = ["apple", "banana", "cherry"] 34 | >>> fruits 35 | ['apple', 'banana', 'cherry'] 36 | 37 | # add as a single element 38 | >>> fruits.append("watermelon") 39 | >>> fruits 40 | ['apple', 'banana', 'cherry', 'watermelon'] 41 | 42 | # add another list as elements 43 | >>> fruits.extend(["lemon", "orange"]) 44 | >>> fruits 45 | ['apple', 'banana', 'cherry', 'watermelon', 'lemon', 'orange'] 46 | 47 | >>> fruits.insert(0, 'pineapple') #add element at i-th position, 0 based index 48 | >>> fruits 49 | ['pineapple', 'apple', 'banana', 'cherry', 'watermelon', 'lemon', 'orange'] 50 | ``` 51 | 52 | Delete Elements: 53 | 54 | ```python 55 | >>> my_list = [1, 2, 3, 'example', 3.132, 10, 30] 56 | >>> del my_list[5] #delete element at index 5 57 | >>> my_list 58 | [1, 2, 3, 'example', 3.132, 30] 59 | 60 | >>> my_list.remove('example') #remove element with value 61 | >>> my_list 62 | [1, 2, 3, 3.132, 30] 63 | 64 | >>> a = my_list.pop(1) #pop element from list at i-th position, 0 based index 65 | 'Popped Element: ', a, ' List remaining: ', my_list 66 | ('Popped Element: ', 2, ' List remaining: ', [1, 3, 3.132, 30]) 67 | 68 | >>> my_list.clear() #empty the list 69 | >>> my_list 70 | [] 71 | ``` 72 | 73 | Access Elements: 74 | 75 | ```python 76 | >>> my_list = [1, 2, 3, 'example', 3.132, 10, 30] 77 | >>> for element in my_list: #access elements one by one 78 | print(element) 79 | ... 80 | 1 81 | 2 82 | 3 83 | example 84 | 3.132 85 | 10 86 | 30 87 | >>> print(my_list) #access all elements 88 | [1, 2, 3, 'example', 3.132, 10, 30] 89 | >>> print(my_list[3]) #access index 3 element 90 | example 91 | >>> print(my_list[0:2]) #access elements from 0 to 1 and exclude 2 92 | [1, 2] 93 | >>> print(my_list[::-1]) #access elements in reverse 94 | [30, 10, 3.132, 'example', 3, 2, 1] 95 | ``` 96 | 97 | Other Functions: 98 | 99 | ```python 100 | >>> my_list = [1, 2, 3, 10, 30, 10] 101 | >>> len(my_list) #find length of list 102 | 6 103 | 104 | >>> my_list.index(10) #find index of element that occurs first 105 | 3 106 | 107 | >>> my_list.count(10) #find count of the element 108 | 2 109 | 110 | >>> sorted(my_list) #print sorted list but not change original 111 | [1, 2, 3, 10, 10, 30] 112 | 113 | >>> my_list.sort(reverse=True) #sort original list 114 | >>> my_list 115 | [30, 10, 10, 3, 2, 1] 116 | ``` 117 | 118 | ## References 119 | 120 | Check out this [link](https://www.w3schools.com/python/python_lists.asp) for more details in Python Lists. 121 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python daily pills 2 | 3 | Daily knowledge pills to get better Python code. 4 | 5 | ## Why 6 | 7 | Does your Python code suffers of any of this symptoms? 8 | 9 | - Incorrect Indentation 10 | - IndexError: list index out of range 11 | - Circular module dependencies 12 | - UnboundLocalError: local variable referenced before assignment 13 | 14 | If yes, we have good news for you! 15 | 16 | ## Remedy 17 | 18 | Take this daily knowledge pills to get better in Python. 19 | 20 | You can take as many as you want, there are no known contraindications. 21 | 22 | - [Day 001 - What does `if __name__ == "__main__":` do?](./pills/day-001) 23 | - [Day 002 - The dir function](./pills/day-002) 24 | - [Day 003 - Sorting lists](./pills/day-003) 25 | - [Day 004 - Find element in a list](./pills/day-004) 26 | - [Day 005 - The Python Command Line (REPL)](./pills/day-005) 27 | - [Day 006 - Python Indentation](./pills/day-006) 28 | - [Day 007 - Python Comments](./pills/day-007) 29 | - [Day 008 - Variables in Python](./pills/day-008) 30 | - [Day 009 - Python Data Types](./pills/day-009) 31 | - [Day 010 - Python Operators (Part 1)](./pills/day-010) 32 | - [Day 011 - Python Operators (Part 2)](./pills/day-011) 33 | - [Day 012 - Python primitive data types in-depth: string, int, float and boolean](./pills/day-012) 34 | - [Day 013 - Built-in Data Structures (Part 1): Lists](./pills/day-013) 35 | - [Day 014 - Built-in Data Structures (Part 2): Dictionaries](./pills/day-014) 36 | - [Day 015 - Pretty Print a Dictionary in Python](./pills/day-015) 37 | - [Day 016 - Built-in Data Structures (Part 3): Tuples](./pills/day-016) 38 | - [Day 017 - Built-in Data Structures (Part 4): Sets](./pills/day-017) 39 | - [Day 018 - Merging two dictionaries with a single expression](./pills/day-018) 40 | - [Day 019 - Swap two variables in Python](./pills/day-019) 41 | - [Day 020 - Sort a Dictionary by Value](./pills/day-020) 42 | - [Day 021 - Python slice notation 101](./pills/day-021) 43 | - [Day 022 - Python slice notation examples](./pills/day-022) 44 | - [Day 023 - Conditions and `if..elif..else` statements](./pills/day-023) 45 | - [Day 024 - Chain of multiple comparisons](./pills/day-024) 46 | - [Day 025 - Short-circuit evaluation](./pills/day-025) 47 | - [Day 026 - While loops](./pills/day-026) 48 | - [Day 027 - For Loops](./pills/day-027) 49 | - [Day 028 - The `range()` function](./pills/day-028) 50 | - [Day 029 - Iterate over two lists or more](./pills/day-029) 51 | - [Day 030 - Nested For Loops](./pills/day-030) 52 | - [Day 031 - Intro to Python Functions](./pills/day-031) 53 | - [Day 032 - Function Parameters or Arguments?](./pills/day-032) 54 | - [Day 033 - Sum an arbitrary number of arguments](./pills/day-033) 55 | - [Day 034 - Unpacking Argument Lists](./pills/day-034) 56 | - [Day 035 - Anonymous functions](./pills/day-035) 57 | - [Day 036 - Emulate switch/case statements with dicts and lambdas](./pills/day-036) 58 | - [Day 037 - Shrink your code with lambdas](./pills/day-037) 59 | - [Day 038 - 5 ways to reverse a string in Python](./pills/day-038) 60 | - [Day 039 - Python's built-in HTTP server](./pills/day-039) 61 | - [Day 040 - Comparing Python Objects the Right Way: `is` vs `==`](./pills/day-040) 62 | - [Day 041 - The Walrus Operator](./pills/day-041) 63 | - [Day 042 - List Comprehensions](./pills/day-042) 64 | - [Day 043 - List comprehension tricks you might not know](./pills/day-043) 65 | - [Day 044 - Classes and Objects in Python](./pills/day-044) 66 | - [Day 045 - Inheritance](./pills/day-045) 67 | - [Day 046 - Functions as First Class Objects](./pills/day-046) 68 | - [Day 047 - Create an Iterator](./pills/day-047) 69 | - [Day 048 - Use of Enums](./pills/day-048) 70 | - [Day 049 - Count Objects with Counter](./pills/day-049) 71 | 72 | ## Contributing 73 | 74 | If you are interested in contributing for this project, please check for the instructions [here](./CONTRIBUTING.md). 75 | 76 | ## References 77 | 78 | - [realpython](https://realpython.com) 79 | - [programiz](https://www.programiz.com/python-programming) 80 | - [w3schools](https://www.w3schools.com/python) 81 | - [pythonexamples](https://pythonexamples.org) 82 | - [Scaler Topics](https://www.scaler.com/topics/python/) 83 | -------------------------------------------------------------------------------- /pills/day-015/README.md: -------------------------------------------------------------------------------- 1 | # [Python daily pills] Day 015 - Pretty Print a Dictionary in Python 2 | 3 | As we just introduce dictionaries in the [last pill](../day-014), this one will cover ways to present them in a more readable style: 4 | 5 | > Note: We have used the Python interpreter, also known as `REPL`, to run the examples. If you don't know what `REPL` is, please [take this pill](../day-005). 6 | 7 | ## Using pprint() 8 | 9 | [`pprint`](https://docs.python.org/3/library/pprint.html) is a Python module that provides the capability to pretty print Python data types to be more readable. This module also supports pretty-printing dictionary. 10 | 11 | ```python 12 | >>> import pprint 13 | >>> dct_arr = [ 14 | {'Name': 'John', 'Age': '23', 'Country': 'USA'}, 15 | {'Name': 'Jose', 'Age': '44', 'Country': 'Spain'}, 16 | {'Name': 'Anne', 'Age': '29', 'Country': 'UK'}, 17 | {'Name': 'Lee', 'Age': '35', 'Country': 'Japan'} 18 | ] 19 | >>> pprint.pprint(dct_arr) 20 | [{'Age': '23', 'Country': 'USA', 'Name': 'John'}, 21 | {'Age': '44', 'Country': 'Spain', 'Name': 'Jose'}, 22 | {'Age': '29', 'Country': 'UK', 'Name': 'Anne'}, 23 | {'Age': '35', 'Country': 'Japan', 'Name': 'Lee'}] 24 | ``` 25 | 26 | To compare, below is the output of a normal `print()` statement: 27 | 28 | ```python 29 | [{'Name': 'John', 'Age': '23', 'Country': 'USA'}, {'Name': 'Jose', 'Age': '44', 'Country': 'Spain'}, {'Name': 'Anne', 'Age': '29', 'Country': 'UK'}, {'Name': 'Lee', 'Age': '35', 'Country': 'Japan'}] 30 | ``` 31 | 32 | > Note: `pprint` will not pretty print nested objects, including nested dictionaries. So if you expect your values to be nested, then this is not the solution for that as well. 33 | 34 | ## Using json.dumps() 35 | 36 | The [`json`](https://docs.python.org/3/library/json.html) module has a function called `dumps()`, which converts a Python object into a JSON string and also formats the dictionary into a pretty JSON format. 37 | 38 | ```python 39 | >>> import json 40 | >>> dct_arr = [ 41 | {'Name': 'John', 'Age': '23', 'Country': 'USA'}, 42 | {'Name': 'Jose', 'Age': '44', 'Country': 'Spain'}, 43 | {'Name': 'Anne', 'Age': '29', 'Country': 'UK'}, 44 | {'Name': 'Lee', 'Age': '35', 'Country': 'Japan'} 45 | ] 46 | >>> print(json.dumps(dct_arr, sort_keys=False, indent=4)) 47 | [ 48 | { 49 | "Name": "John", 50 | "Age": "23", 51 | "Country": "USA" 52 | }, 53 | { 54 | "Name": "Jose", 55 | "Age": "44", 56 | "Country": "Spain" 57 | }, 58 | { 59 | "Name": "Anne", 60 | "Age": "29", 61 | "Country": "UK" 62 | }, 63 | { 64 | "Name": "Lee", 65 | "Age": "35", 66 | "Country": "Japan" 67 | } 68 | ] 69 | ``` 70 | 71 | What if the values given have a nested dictionary within them? Let’s edit the example a bit and take a look at the output. 72 | 73 | ```python 74 | >>> import json 75 | >>> dct_arr = [ 76 | {'Name': 'John', 'Age': '23', 'Residence': {'Country':'USA', 'City': 'New York'}}, 77 | {'Name': 'Jose', 'Age': '44', 'Residence': {'Country':'Spain', 'City': 'Madrid'}}, 78 | {'Name': 'Anne', 'Age': '29', 'Residence': {'Country':'UK', 'City': 'England'}}, 79 | {'Name': 'Lee', 'Age': '35', 'Residence': {'Country':'Japan', 'City': 'Osaka'}} 80 | ] 81 | >>> print(json.dumps(dct_arr, sort_keys=False, indent=4)) 82 | [ 83 | { 84 | "Name": "John", 85 | "Age": "23", 86 | "Residence": { 87 | "Country": "USA", 88 | "City": "New York" 89 | } 90 | }, 91 | { 92 | "Name": "Jose", 93 | "Age": "44", 94 | "Residence": { 95 | "Country": "Spain", 96 | "City": "Madrid" 97 | } 98 | }, 99 | { 100 | "Name": "Anne", 101 | "Age": "29", 102 | "Residence": { 103 | "Country": "UK", 104 | "City": "England" 105 | } 106 | }, 107 | { 108 | "Name": "Lee", 109 | "Age": "35", 110 | "Residence": { 111 | "Country": "Japan", 112 | "City": "Osaka" 113 | } 114 | } 115 | ] 116 | ``` 117 | 118 | > The `dumps()` function accepts 3 parameters used for pretty printing: the object for conversion, a boolean value sort_keys, which determines whether the entries should be sorted by key, and indent, which specifies the number of spaces for indentation. 119 | 120 | ## References 121 | 122 | Check out this [link](https://www.delftstack.com/howto/python/python-pretty-print-dictionary/) for more details about pretty print a dictionary in Python. 123 | --------------------------------------------------------------------------------