diff --git a/Python Tutorial/Dict-comprehension.md b/Python Tutorial/Dict-comprehension.md new file mode 100644 index 0000000..b4695a4 --- /dev/null +++ b/Python Tutorial/Dict-comprehension.md @@ -0,0 +1,208 @@ +# Dict comprehension + +source: `{{ page.path }}` + +`Dictionary comprehension` is a way to build a new dictionary by applying an expression to each item in an iterable. +Dictionaries are data types in Python which allows us to store data in key/value pair. For example: +```python +D = {} +for x in range(5): + D[x] = x**2 + +print(D) # Prints {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} +``` +General syntax for a dictionary comprehension is: + +![](./images/dict2.PNG) +![](./images/dict3.PNG) + +```python +D = {c: c*3 for c in "RED"} +print(D) # {'R': 'RRR', 'E': 'EEE', 'D': 'DDD'} + +L = ['ReD', 'GrEeN', 'BlUe'] +D = {c.lower(): c.upper() for c in L} +print(D) # Prints {'blue': 'BLUE', 'green': 'GREEN', 'red': 'RED'} +``` +#### Extracting a Subset of a Dictionary +Sometimes you want to extract particular keys from a dictionary. This is easily accomplished using a dictionary comprehension. +```python +D = {0:'A', 1:'B', 3:'C', 4:'D', 5:'E'} +keys = [0,3,5] +x = {k: D[k] for k in keys} +print(x) # {0: 'A', 3: 'C', 5: 'E'} +``` +#### Filter Dictionary Contents +Suppose you want to make a new dictionary with selected keys removed. Here’s a simple code that deletes specified keys from a dictionary. +```python +D = {0:'A', 1:'B', 3:'C', 4:'D', 5:'E'} +remove = [0,3,5] +x = {k: D[k] for k in D.keys() - remove} +print(x) # {1: 'B', 4: 'D'} +``` +#### Invert Mapping / Reverse lookup +Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]. This operation is called a lookup. + +But what if you want to retrieve a key k using a value v in a dictionary? You have to do `reverse lookup`. +```python +D = {0: 'red', 1: 'green', 2: 'blue'} +R = {v: k for k,v in D.items()} +print(R) # Prints {'red': 0, 'green': 1, 'blue': 2} +``` + +#### Dictionary Comprehension with Enumerate +Sometimes you want to create a dictionary from the list with list index number as key and list element as value. To achieve this wrap the list in `enumerate()` function and pass it as an iterable to the dict comprehension. +```python +L = ['red', 'green', 'blue'] +D = {k:v for k,v in enumerate(L)} +print(D) # Prints {0: 'red', 1: 'green', 2: 'blue'} + +Such dictionaries with element index are often useful in a variety of scenarios such as reading a file by lines. + +D = {ix: line for ix, line in enumerate(open('myFile.txt'))} +print(D) +# {0: 'First line\n', +# 1: 'Second line\n', +# 2: 'Third line\n'} +``` +#### Initialize Dictionary with Comprehension +Dictionary comprehensions are also useful for initializing dictionaries from keys lists, in much the same way as the `fromkeys()` method. Following example Initializes a dictionary with default value ‘0’ for each key. +```python +keys = ['red', 'green', 'blue'] + +# using dict comprehension +D = {k: 0 for k in keys} +print(D) # Prints {'red': 0, 'green': 0, 'blue': 0} + +# equivalent to using fromkeys() method +D = dict.fromkeys(keys, 0) +print(D) # Prints {'red': 0, 'green': 0, 'blue': 0} +``` +A standard way to dynamically initialize a dictionary is to combine its keys and values with `zip`, and pass the result to the `dict()` function. However, you can achieve the same result with a dictionary comprehension. +```python +keys = ['name', 'age', 'job'] +values = ['Bob', 25, 'Dev'] + +# using dict comprehension +D = {k: v for (k, v) in zip(keys, values)} +print(D) # Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'} + +# equivalent to using dict() on zipped keys/values +D = dict(zip(keys, values)) +print(D) # Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'} +``` +#### Dictionary Comprehension with if Clause +A dictionary comprehension may have an optional associated if clause to filter items out of the result. + +Iterable’s items are skipped for which the if clause is not true. +```tip + { key:value for var in iterable if_clause } +``` +The following example collects squares of even items (i.e. items having no remainder for division by 2) in a range. +```python + +D = {x: x**2 for x in range(6) if x % 2 == 0} + +print(D) # Prints {0: 0, 2: 4, 4: 16} + +This dictionary comprehension is the same as a for loop that contains an if statement: + +D = {} +for x in range(5): + if x % 2 == 0: + D[x] = x**2 + +print(D) # Prints {0: 0, 2: 4, 4: 16} +``` +#### Nested Dictionary Comprehension +The initial value in a dictionary comprehension can be any expression, including another dictionary comprehension. +```tip + { key: {dict comprehension} for var in iterable } +``` +For example, here’s a simple list comprehension that uses a nested for clause. +```python +D = {(k,v): k+v for k in range(2) for v in range(2)} +print(D) # Prints {(0, 1): 1, (1, 0): 1, (0, 0): 0, (1, 1): 2} + +# is equivalent to +D = {} +for k in range(2): + for v in range(2): + D[(k,v)] = k+v +print(D) # Prints {(0, 1): 1, (1, 0): 1, (0, 0): 0, (1, 1): 2} +``` + +#### dictionary comprehension example +```python +square_dict = {num: num*num for num in range(1, 11)} +print(square_dict) + +{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} + +``` +In both programs, we have created a dictionary square_dict with number-square key/value pair. + +However, using dictionary comprehension allowed us to create a dictionary in a single line. + +`Syntax: dictionary = {key: value for vars in iterable}` + +```python +# item price in dollars + +old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5} + +dollar_to_pound = 0.76 +new_price = {item: value*dollar_to_pound for (item, value) in old_price.items()} +print(new_price) + +{'milk': 0.7752, 'coffee': 1.9, 'bread': 1.9} + +``` +#### Conditionals in Dictionary Comprehension +We can further customize dictionary comprehension by adding conditions to it. Let's look at an example. +```python +## If Conditional Dictionary Comprehension +original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33} + +even_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0} +print(even_dict) + +{'jack': 38, 'michael': 48} + +``` +```python +## Multiple if Conditional Dictionary Comprehension +original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33} + +new_dict = {k: v for (k, v) in original_dict.items() if v % 2 != 0 if v < 40} +print(new_dict) + +{'john': 33} +``` +```python +## if-else Conditional Dictionary Comprehension +original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33} + +new_dict_1 = {k: ('old' if v > 40 else 'young') + for (k, v) in original_dict.items()} +print(new_dict_1) + +{'jack': 'young', 'michael': 'old', 'guido': 'old', 'john': 'young'} +``` +#### Nested Dictionary Comprehension +We can add dictionary comprehensions to dictionary comprehensions themselves to create nested dictionaries. Let's look at an example. +```python +## Nested Dictionary with Two Dictionary Comprehensions +dictionary = { + k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 5) +} +print(dictionary) + +{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, +3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}, +4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}} +``` +Advantages of Using Dictionary Comprehension +* As we can see, dictionary comprehension shortens the process of dictionary initialization by a lot. It makes the code more pythonic. + +* Using dictionary comprehension in our code can shorten the lines of code while keeping the logic intact. \ No newline at end of file diff --git a/Python Tutorial/Dictionary.md b/Python Tutorial/Dictionary.md new file mode 100644 index 0000000..b2a2292 --- /dev/null +++ b/Python Tutorial/Dictionary.md @@ -0,0 +1,521 @@ +# Dictionary +source: `{{ page.path }}` + +Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.Dictionaries are optimized to retrieve values when the key is known. + +Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.An item has a key and a corresponding value that is expressed as a pair (key: value). + +While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. + +![](./images/dict1.PNG) + +```tip +1. dict is a collection of "key : value" pairs. +2. dict is represented in {} brackets. +3. dict allows both Homeogenous & Hetrogenous values/elements. +4. dict are mutable. +5. dict doesn't allow duplicate keys but allow values. +6. dict doesn't allow indexing and slicing. +7. dict maintain insertion order +``` +```note +1. Creating a Dictionary +2. Accessing a Dictionary +3. Reassigning a dictionary +4. Deleting a Dictionary +5. In-Built function on a Dictionary +6. In-Built Methods on a Dictionary +7. Operations on a Dictionary +8. iterating on a Dictionary +9. Nested Dictionary +``` +## Creating a Dictionary +You can create a dictionary by placing a comma-separated list of `key:value` pairs in curly braces `{}`. Each key is separated from its associated value by a colon +```python +# empty dictionary +my_dict = {} + +# dictionary with integer keys +my_dict = {1: 'apple', 2: 'ball'} + +# dictionary with mixed keys +my_dict = {'name': 'John', 1: [2, 4, 3]} + +# using dict() +my_dict = dict({1:'apple', 2:'ball'}) + +# from sequence having each item as a pair +my_dict = dict([(1,'apple'), (2,'ball')]) + +# Declaring one key more than once +my_dict={1:2, 1:3, 1:4, 2:4} + +# Python Dictionary Comprehension +my_dict={x*x:x for x in range(8)} + +# Create a dictionary with list of zipped keys/values +keys = ['name', 'age', 'job'] +values = ['Bob', 25, 'Dev'] + +print(dict(zip(keys, values))) +# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'} + +# Initialize dictionary with default value '0' for each key +keys = ['a', 'b', 'c'] +defaultValue = 0 + +print(dict.fromkeys(keys,defaultValue)) +# Prints {'a': 0, 'b': 0, 'c': 0} +``` +## Accessing a Dictionary +The order of key:value pairs is not always the same. + +While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets `[]` or with the `get()` method. + +If we use the square brackets [], `KeyError` is raised in case a key is not found in the dictionary. On the other hand, the `get()` method returns None if the key is not found. + +```python +# get vs [] for retrieving elements +my_dict = {'name': 'Jack', 'age': 26} + +# Output: Jack +print(my_dict['name']) + +# Output: 26 +print(my_dict.get('age')) + +# Trying to access keys which doesn't exist throws error +# Output None +print(my_dict.get('address')) + +# KeyError +print(my_dict['address']) + +# example 2 +D = {'name': 'Bob', + 'age': 25, + 'job': 'Dev'} + +print(D['name']) +# Prints Bob + +print(D['salary']) +# Triggers KeyError: 'salary' +# When key is present + +print(D.get('name')) +# Prints Bob + +# When key is absent +print(D.get('salary')) +# Prints None + +``` +## Reassigning a dictionary + +Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator. + +If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary. +```python +# Changing and adding Dictionary Elements +my_dict = {'name': 'Jack', 'age': 26} + +# update value +my_dict['age'] = 27 + +#Output: {'age': 27, 'name': 'Jack'} +print(my_dict) + +# add item +my_dict['address'] = 'Downtown' + +# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} +print(my_dict) + +# Merging two dictionaries +D1 = {'name': 'Bob', + 'age': 25, + 'job': 'Dev'} + +D2 = {'age': 30, + 'city': 'New York', + 'email': 'bob@web.com'} + +D1.update(D2) +print(D1) +# Prints {'name': 'Bob', 'age': 30, 'job': 'Dev', +# 'city': 'New York', 'email': 'bob@web.com'} +``` +## Deleting a Dictionary +There are several ways to remove items from a dictionary. + +Remove an Item by Key +If you know the key of the item you want, you can use pop() method. It removes the key and returns its value. +```python +# Removing elements from a dictionary + +# create a dictionary +squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} + +# remove a particular item, returns its value +# Output: 16 +print(squares.pop(4)) + +# Output: {1: 1, 2: 4, 3: 9, 5: 25} +print(squares) + +# remove an arbitrary item, return (key,value) +# Output: (5, 25) +print(squares.popitem()) + +# Output: {1: 1, 2: 4, 3: 9} +print(squares) + +# remove all items +squares.clear() + +# Output: {} +print(squares) + +# delete the dictionary itself +del squares + +# Throws Error +print(squares) + +# example 2 +D = {'name': 'Bob', + 'age': 25, + 'job': 'Dev'} + +x = D.pop('age') +print(D) # Prints {'name': 'Bob', 'job': 'Dev'} + +# get removed value +print(x) # Prints 25 + +del D['age'] +print(D) # Prints {'name': 'Bob', 'job': 'Dev'} + +# The popitem() method removes and returns the last inserted item. +x = D.popitem() +print(D) # Prints {'name': 'Bob', 'age': 25} + +# Remove all Items +D.clear() +print(D) # Prints {} + +``` +## In-Built function on a Dictionary + +Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks. + +|Function | Description | +|---------------|-----------------------------------------------------------------------------------------------| +|all() | Return True if all keys of the dictionary are True (or if the dictionary is empty). | +|any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. | +|len() | Return the length (the number of items) in the dictionary. | +|cmp() | Compares items of two dictionaries. (Not available in Python 3) | +|sorted() | Return a new sorted list of keys in the dictionary. | + +```python +# Dictionary Built-in Functions +squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} + +print(all(squares)) # False + +print(any(squares)) # True + +print(len(squares)) # 6 + +print(sorted(squares)) # [0, 1, 3, 5, 7, 9] +``` +## In-Built Methods on a Dictionary + +|Method | Description | +|--------------------------|---------------------------------------------------------------------------------------------------------| +|clear() | Removes all items from the dictionary. | +|copy() | Returns a shallow copy of the dictionary. | +|fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value equal to v (defaults to None). | +|get(key[,d]) | Returns the value of the key. If the key does not exist, returns d (defaults to None). | +|items() | Return a new object of the dictionary's items in (key, value) format. | +|keys() | Returns a new object of the dictionary's keys. | +|pop(key[,d]) | Removes the item with the key and returns its value or d if key is not found. If d is not provided and | +| | the key is not found, it raises KeyError. | +|popitem() | Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. | +|setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value | +| | of d and returns d (defaults to None). | +|update([other]) | Updates the dictionary with the key/value pairs from other, overwriting existing keys. | +|values() | Returns a new object of the dictionary's values | + +```python +data = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} +print((data)) +print(data.keys()) # dict_keys([0, 1, 2, 3, 4, 5]) +print(data.values()) # dict_values([0, 1, 4, 9, 16, 25]) +print(data.items()) # dict_items([(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]) +print(data.get(3,0)) # it will give the value of key 3 = 9 + # if there is no key it return `none` +print(data.clear()) # it clears the dictionary +data1=data.copy() # +print(data1) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} +print(data1.pop(4)) # used to remove and display an item from the dictionary 16 + # this has no default None value for the second parameter it throw keyerror +print(data1.popitem()) # last inserted item in dictionary (5,25) +print(data.fromkeys({1,2,3,4,7},0)) # {1: 0, 2: 0, 3: 0, 4: 0, 7: 0} +print(data.fromkeys({'1','2','3','4','7'})) # {'2': None, '4': None, '3': None, '7': None, '1': None} +dict1={1:1,2:2} +dict2={4:5,5:2} +dict1.update(dict2) # Then it updates the dictionary to hold values from the + # other dictionary that it doesn’t already. +print(dict1) # {1: 1, 2: 2, 4: 5, 5: 2} + +``` +## iterating on a Dictionary + +```python +D = {'name': 'Bob','age': 25,'job': 'Dev'} + +for x in D: + print(x) # Prints name age job +for x in D: + print(D[x]) # Prints Bob 25 Dev + +data={1: 11, 5: 12, 6: 15} +for i in data: + print(data[i]*2) # 22,24,30 +``` + +## Nested Dictionary + +A dictionary can contain another dictionary, which in turn can contain dictionaries themselves, and so on to arbitrary depth. This is known as nested dictionary. + +Nested dictionaries are one of many ways to represent structured information (similar to ‘records’ or ‘structs’ in other languages). + +#### Create a Nested Dictionary +A nested dictionary is created the same way a normal dictionary is created. The only difference is that each value is another dictionary. +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} +``` +#### dict() Constructor + +There are several ways to create a nested dictionary using a type constructor called dict(). +To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. +```python +D = dict(emp1 = {'name': 'Bob', 'job': 'Mgr'}, + emp2 = {'name': 'Kim', 'job': 'Dev'}, + emp3 = {'name': 'Sam', 'job': 'Dev'}) + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}, +# 'emp3': {'name': 'Sam', 'job': 'Dev'}} +``` +we can use `dict()` function along with the `zip()` function, to combine separate lists of keys and values obtained dynamically at runtime. +```python +IDs = ['emp1','emp2','emp3'] + +EmpInfo = [{'name': 'Bob', 'job': 'Mgr'}, + {'name': 'Kim', 'job': 'Dev'}, + {'name': 'Sam', 'job': 'Dev'}] + +D = dict(zip(IDs, EmpInfo)) + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}, +# 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +``` +we often want to create a dictionary with default values for each key. The `fromkeys()` method offers a way to do this. +```python +IDs = ['emp1','emp2','emp3'] +Defaults = {'name': '', 'job': ''} + +D = dict.fromkeys(IDs, Defaults) + +print(D) +# Prints {'emp1': {'name': '', 'job': ''}, +# 'emp2': {'name': '', 'job': ''}, +# 'emp3': {'name': '', 'job': ''}} +``` +#### Access Nested Dictionary Items +You can access individual items in a nested dictionary by specifying key in multiple square brackets. +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +print(D['emp1']['name']) # Prints Bob + +print(D['emp2']['job']) # Prints Dev + +If you refer to a key that is not in the nested dictionary, an exception is raised. + +print(D['emp1']['salary']) # Triggers KeyError: 'salary' +``` +To avoid such exception, you can use the special dictionary `get(`) method. This method returns the value for key if key is in the dictionary, else None, so that this method never raises a KeyError. +```python +# key present +print(D['emp1'].get('name')) # Prints Bob + +# key absent +print(D['emp1'].get('salary')) # PrintsNone +``` + +#### Change Nested Dictionary Items + +To change the value of a specific item in a nested dictionary, refer to its key. +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +D['emp3']['name'] = 'Max' +D['emp3']['job'] = 'Janitor' + +print(D['emp3']) # Prints {'name': 'Max', 'job': 'Janitor'} +``` +#### Add or Update Nested Dictionary Items +Adding or updating nested dictionary items is easy. Just refer to the item by its key and assign a value. If the key is already present in the dictionary, its value is replaced by the new one. +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +D['emp3'] = {'name': 'Max', 'job': 'Janitor'} + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}, +# 'emp3': {'name': 'Max', 'job': 'Janitor'}} +If the key is new, it is added to the dictionary with its value. + +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +D['emp4'] = {'name': 'Max', 'job': 'Janitor'} + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}, +# 'emp3': {'name': 'Sam', 'job': 'Dev'}, +# 'emp4': {'name': 'Max', 'job': 'Janitor'}} +``` +#### Merge Two Nested Dictionaries +Use the built-in update() method to merge the keys and values of one nested dictionary into another. Note that this method blindly overwrites values of the same key if there’s a clash. +```python +D1 = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}} + +D2 = {'emp2': {'name': 'Sam', 'job': 'Dev'}, + 'emp3': {'name': 'Max', 'job': 'Janitor'}} + +D1.update(D2) + +print(D1) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Sam', 'job': 'Dev'}, +# 'emp3': {'name': 'Max', 'job': 'Janitor'}} +Here the ’emp2′ record is updated while ’emp3′ is added to the dictionary. +``` +#### Remove Nested Dictionary Items +There are several ways to remove items from a nested dictionary. + +(I) . Remove an Item by Key +If you know the key of the item you want, you can use `pop()` method. It removes the key and returns its value. + +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +x = D.pop('emp3') + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}} + +# get removed value +print(x) +# Prints {'name': 'Sam', 'job': 'Dev'} +``` + +(II). If you don’t need the removed value, use the del statement. + +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +del D['emp3'] + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}} +``` + +(III). Remove Last Inserted Item +The `popitem()` method removes and returns the last inserted item as a tuple. + +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +x = D.popitem() + +print(D) +# Prints {'emp1': {'name': 'Bob', 'job': 'Mgr'}, +# 'emp2': {'name': 'Kim', 'job': 'Dev'}} + +# get removed pair +print(x) +# Prints ('emp3', {'name': 'Sam', 'job': 'Dev'}) +``` + +In versions before 3.7, `popitem()` would remove a random item. + +Iterate Through a Nested Dictionary +we can iterate over all values in a nested dictionary using nested for loop. + +```python +D = {'emp1': {'name': 'Bob', 'job': 'Mgr'}, + 'emp2': {'name': 'Kim', 'job': 'Dev'}, + 'emp3': {'name': 'Sam', 'job': 'Dev'}} + +for id, info in D.items(): + print("\nEmployee ID:", id) + for key in info: + print(key + ':', info[key]) + +# Prints Employee ID: emp1 +# name: Bob +# job: Mgr + +# Employee ID: emp2 +# name: Kim +# job: Dev + +# Employee ID: emp3 +# name: Sam +# job: Dev + +``` + + + + + + + + + + + + + + diff --git a/Python Tutorial/For Loop.md b/Python Tutorial/For Loop.md new file mode 100644 index 0000000..47a2179 --- /dev/null +++ b/Python Tutorial/For Loop.md @@ -0,0 +1,199 @@ +# For Loop + +source: `{{ page.path }}` + +The for statement in Python is a bit different from what you usually use in other programming languages. + +Rather than iterating over a numeric progression, Python’s for statement iterates over the items of any iterable **(list, tuple, dictionary, set, or string)**. The items are iterated in the order that they appear in the iterable. + +#### For Loop + +![](./images/for.PNG) + + ```python +# Iterate through a list +colors = ['red', 'green', 'blue', 'yellow'] +for x in colors: + print(x) +# Prints red green blue yellow + +# Iterate through a string +S = 'python' +for x in S: + print(x) +# Prints p y t h o n + +``` + +#### Break in for Loop +Python break statement is used to exit the loop immediately. It simply jumps out of the loop altogether, and the program continues after the loop. + +```python +# Break the loop at 'blue' +colors = ['red', 'green', 'blue', 'yellow'] +for x in colors: + if x == 'blue': + break + print(x) +# Prints red green +``` + +#### Continue in for Loop +The continue statement skips the current iteration of a loop and continues with the next iteration. + +```python +# Skip 'blue' and execute other colors in list +colors = ['red', 'green', 'blue', 'yellow'] +for x in colors: + if x == 'blue': + continue + print(x) +# Prints red green yellow +``` + +#### Else in for Loop +Python allows an optional else clause at the end of a for loop. The else clause will be executed if the loop terminates naturally (through exhaustion). + +```python +colors = ['red', 'green', 'blue', 'yellow'] +for x in colors: + print(x) +else: + print('Done!') +# Prints red green blue yellow +# Prints Done! + +## If the loop terminates prematurely with break, the else clause won’t be executed. + +colors = ['red', 'green', 'blue', 'yellow'] +for x in colors: + if x == 'blue': + break + print(x) +else: + print('Done!') +# Prints red green + +``` + +#### range() function in for loop +If you need to execute a group of statements for a specified number of times, use built-in function range(). + +The **range(start,stop,step)** function generates a sequence of numbers from 0 up to (but not including) specified number. + +```python +# Generate a sequence of numbers from 0 6 +for x in range(7): + print(x) +# Prints 0 1 2 3 4 5 6 + +range() provides a simple way to repeat an action a specific number of times. + +# Print 'Hello!' three times +for x in range(3): + print('Hello!') +# Prints Hello! +# Prints Hello! +# Prints Hello! + +The range starts from 0 by default. But, you can start the range at another number by specifying start parameter. + +# Generate a sequence of numbers from 2 to 6 +for x in range(2, 7): + print(x) +# Prints 2 3 4 5 6 + +# Increment the range with 2 +for x in range(2, 7, 2): + print(x) +# Prints 2 4 6 +``` + +#### Nested for Loop + +A loop inside another loop is called a nested loop. +```python +# Flatten a nested list +list = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] +for sublist in list: + for number in sublist: + print(number) +# Prints 1 2 3 4 5 6 7 8 9 +``` + +#### Access Index in for Loop +To iterate over the indices of a sequence, you can combine range() and len() as follows: + +```python +colors = ['red', 'green', 'blue'] +for index in range(len(colors)): + print(index, colors[index]) +# Prints 0 red +# Prints 1 green +# Prints 2 blue + +However, in most such cases it is convenient to use the enumerate() function. + +colors = ['red', 'green', 'blue'] +for index, value in enumerate(colors): + print(index, value) +# Prints 0 red +# Prints 1 green +# Prints 2 blue +``` +#### Unpacking in a for loop +Below for loop does a multiple assignment (unpack the current tuple) each time through the loop. + +```python +# Tuple unpacking +T = [(1, 2), (3, 4), (5, 6)] +for (a, b) in T: + print(a, b) +# Prints 1 2 +# Prints 3 4 +# Prints 5 6 + +Likewise, you can iterate through both keys and values in a dictionary. + +# Dictionary unpacking +D = {'name': 'Bob', 'age': 25} +for x, y in D.items(): + print(x, y) +# Prints age 25 +# Prints name Bob +``` + +#### Modify a List While Iterating +Don’t alter mutable objects while looping on them. It may create an infinite loop. + +```python +# infinite loop +colors = ['red', 'green', 'blue'] +for x in colors: + if x == 'red': + colors.insert(0, 'orange') + print(colors) +``` +It is recommended that you first make a copy. The slicing operator makes this especially convenient. + +```python +colors = ['red', 'green', 'blue'] +for x in colors[:]: + if x == 'red': + colors.insert(0, 'orange') +print(colors) +# Prints ['orange', 'red', 'green', 'blue'] +``` +#### Looping Through Multiple Lists +Using built-in **zip()** function you can loop through multiple lists at once. + +```python +# Loop through two lists at once +name = ['Bob', 'Sam', 'Max'] +age = [25, 35, 30] +for x, y in zip(name, age): + print(x, y) +# Prints Bob 25 +# Prints Sam 35 +# Prints Max 30 +``` \ No newline at end of file diff --git a/Python Tutorial/Functions.md b/Python Tutorial/Functions.md new file mode 100644 index 0000000..d1ec740 --- /dev/null +++ b/Python Tutorial/Functions.md @@ -0,0 +1,299 @@ +# Functions + +source: `{{ page.path }}` + +Functions are the first step to code reuse. They allow you to define a reusable block of code that can be used repeatedly in a program. + +Python provides several built-in functions such as print(), len() or type(), but you can also define your own functions to use within your programs + +![](./images/function.PNG) + +#### Create a Function +To define a Python function, use def keyword. Here’s the simplest possible function that prints ‘Hello, World!’ on the screen. + +```python +def hello(): + print('Hello, World!') +``` +#### Call a Function +The def statement only creates a function but does not call it. After the def has run, you can can call (run) the function by adding parentheses after the function’s name. +```python +def hello(): + print('Hello, World!') + +hello() +# Prints Hello, World! +``` +#### Pass Arguments +You can send information to a function by passing values, known as arguments. Arguments are declared after the function name in parentheses. + +When you call a function with arguments, the values of those arguments are copied to their corresponding parameters inside the function. +```python +# Pass single argument to a function +def hello(name): + print('Hello,', name) + +hello('Bob') +# Prints Hello, Bob +hello('Sam') +# Prints Hello, Sam +``` +You can send as many arguments as you like, separated by commas ,. +```python +# Pass two arguments +def func(name, job): + print(name, 'is a', job) + +func('Bob', 'developer') +# Prints Bob is a developer +``` + +#### Types of Arguments +Python handles function arguments in a very flexible manner, compared to other languages. It supports multiple types of arguments in the function definition. Here’s the list: + +* Positional Arguments +* Keyword Arguments +* Default Arguments +* Variable Length Positional Arguments (*args) +* Variable Length Keyword Arguments (**kwargs) + +#### Positional Arguments +The most common are positional arguments, whose values are copied to their corresponding parameters in order. +```python +def func(name, job): + print(name, 'is a', job) + +func('Bob', 'developer') +# Prints Bob is a developer +``` +The only downside of positional arguments is that you need to pass arguments in the order in which they are defined. +```python +def func(name, job): + print(name, 'is a', job) + +func('developer', 'Bob') +# Prints developer is a Bob +``` + +#### Keyword Arguments +To avoid positional argument confusion, you can pass arguments using the names of their corresponding parameters. + +In this case, the order of the arguments no longer matters because arguments are matched by name, not by position. + +```python +# Keyword arguments can be put in any order +def func(name, job): + print(name, 'is a', job) + +func(name='Bob', job='developer') +# Prints Bob is a developer + +func(job='developer', name='Bob') +# Prints Bob is a developer +``` +It is possible to combine positional and keyword arguments in a single call. If you do so, specify the positional arguments before keyword arguments. + +#### Default Arguments +You can specify default values for arguments when defining a function. The default value is used if the function is called without a corresponding argument. + +In short, defaults allow you to make selected arguments optional. +```python +# Set default value 'developer' to a 'job' parameter +def func(name, job='developer'): + print(name, 'is a', job) + +func('Bob', 'manager') +# Prints Bob is a manager + +func('Bob') +# Prints Bob is a developer +``` + +#### Variable Length Arguments (*args and **kwargs) +Variable length arguments are useful when you want to create functions that take unlimited number of arguments. Unlimited in the sense that you do not know beforehand how many arguments can be passed to your function by the user. + +This feature is often referred to as var-args. + +##### *args +When you prefix a parameter with an asterisk * , it collects all the unmatched positional arguments into a tuple. Because it is a normal tuple object, you can perform any operation that a tuple supports, like indexing, iteration etc. + +Following function prints all the arguments passed to the function as a tuple. +```python +def print_arguments(*args): + print(args) + +print_arguments(1, 54, 60, 8, 98, 12) +# Prints (1, 54, 60, 8, 98, 12) +``` +You don’t need to call this keyword parameter args, but it is standard practice. + +##### **kwargs +The ** syntax is similar, but it only works for keyword arguments. It collects them into a new dictionary, where the argument names are the keys, and their values are the corresponding dictionary values. +```python +def print_arguments(**kwargs): + print(kwargs) + +print_arguments(name='Bob', age=25, job='dev') +# Prints {'name': 'Bob', 'age': 25, 'job': 'dev'} +``` +#### Return Value +To return a value from a function, simply use a return statement. Once a return statement is executed, nothing else in the function body is executed. +```python +# Return sum of two values +def sum(a, b): + return a + b + +x = sum(3, 4) +print(x) +# Prints 7 +``` +Remember! a python function always returns a value. So, if you do not include any return statement, it automatically returns None. + +#### Return Multiple Values +Python has the ability to return multiple values, something missing from many other languages. You can do this by separating return values with a comma. +```python +# Return addition and subtraction in a tuple +def func(a, b): + return a+b, a-b + +result = func(3, 2) + +print(result) +# Prints (5, 1) +``` + +When you return multiple values, Python actually packs them in a single tuple and returns it. You can then use multiple assignment to unpack the parts of the returned tuple. + +```python +# Unpack returned tuple +def func(a, b): + return a+b, a-b + +add, sub = func(3, 2) + +print(add) +# Prints 5 +print(sub) +# Prints 1 +``` + +#### Docstring +You can attach documentation to a function definition by including a string literal just after the function header. Docstrings are usually triple quoted to allow for multi-line descriptions. +```python +def hello(): + """This function prints + message on the screen""" + print('Hello, World!') +``` +To print a function’s docstring, use the Python help() function and pass the function’s name. +```python +# Print docstring in rich format +help(hello) + +# Help on function hello in module __main__: +# hello() +# This function prints +# message on the screen +``` +You can also access the docstring through __doc__ attribute of the function. +```python +# Print docstring in a raw format +print(hello.__doc__) + +# Prints This function prints message on the screen +``` +#### Composition +One of the most useful features of Python is its ability to take small building blocks and compose them. For example, the argument of a function can be any type of expression, including arithmetic operators: +```python +import math +x = math.sin(360*2*math.pi) +print(x) +# Prints -3.133115067780141e-14 +``` +And even function calls: +```python +import math +x = math.exp(math.log(3.14)) +print(x) +# Prints 3.1399999999999997 +``` + +#### Nested Functions +A Nested function is a function defined within other function. They are useful when performing complex task multiple times within another function, to avoid loops or code duplication. + +```python +def outer(a, b): + def inner(c, d): + return c + d + return inner(a, b) + +result = outer(2, 4) + +print(result) +# Prints 6 +``` +A nested function can act as a closure. + +#### Recursion +A recursive function is a function that calls itself and repeats its behavior until some condition is met to return a result. + +In below example, countdown() is a recursive function that calls itself (recurse) to countdown. If num is 0 or negative, it prints the word “Stop”. Otherwise, it prints num and then calls itself, passing num-1 as an argument. +```python +def countdown(num): + if num <= 0: + print('Stop') + else: + print(num) + countdown(num-1) + +countdown(5) +# Prints 5 +# Prints 4 +# Prints 3 +# Prints 2 +# Prints 1 +# Prints Stop +``` +#### Assigning Functions to Variables +When Python runs a def statement, it creates a new function object and assigns it to the function’s name. You can assign a different name to it anytime and call through the new name. + +For example, let’s assign a different name ‘hi’ to our ‘hello’ function and call through its new name. +```python +def hello(): + print('Hello, World!') + +hi = hello +hi() +# Prints Hello, World! +You can use this feature to implement jump table. Jump table is a dictionary of functions to be called on demand. + +def findSquare(x): + return x ** 2 + +def findCube(x): + return x ** 3 + +# Create a dictionary of functions +exponent = {'square': findSquare, 'cube': findCube} + +print(exponent['square'](3)) +# Prints 9 +print(exponent['cube'](3)) +# Prints 27 +``` +#### Python Function Executes at Runtime +Because Python treats def as an executable statement, it can appear anywhere a normal statement can. + +For example you can nest a function inside an if statement to select between alternative definitions. +```python +x = 0 +if x: + def hello(): + print('Hello, World!') +else: + def hello(): + print('Hello, Universe!') + +hello() +# Prints Hello, Universe! +``` \ No newline at end of file diff --git a/Python Tutorial/If Else.md b/Python Tutorial/If Else.md new file mode 100644 index 0000000..1e14b1a --- /dev/null +++ b/Python Tutorial/If Else.md @@ -0,0 +1,178 @@ +# IF ELSE + +source: `{{ page.path }}` + +Python if else elif Statement + +* **if Statement:** use it to execute a block of code, if a specified condition is true +* **else Statement:** use it to execute a block of code, if the same condition is false +* **elif (else if) Statement:** use it to specify a new condition to test, if the first condition is false + +#### The if Statement + +Use if statement to execute a block of Python code, if the condition is true. + +Syntax: + +![](./images/if.PNG) + +```python +x, y = 7, 5 +if x > y: + print('x is greater') +# Prints x is greater + +# mathematical expression +x, y = 7, 5 +if x + y: + print('True') +# Prints True +``` +![](./images/if1.PNG) + +#### The else Statement +Use else statement to execute a block of Python code, if the condition is false. + +Syntax: + +![](./images/else.PNG) + +```python +x, y = 7, 5 +if x < y: + print('y is greater') +else: + print('x is greater') + +# Prints x is greater +``` +#### The elif (else if) Statement +Use elif statement to specify a new condition to test, if the first condition is false. + +![](./images/elif.PNG) + +```python +x, y = 5, 5 +if x > y: + print('x is greater') +elif x < y: + print('y is greater') +else: + print('x and y are equal') + +# Prints x and y are equal + +``` + +#### Python nested if else statement +In nested if else statements, if statement is nested inside an if statements. So, the nested if statements will be executed only if the expression of main if statement returns TRUE. + +Syntax of nested if else in Python. + +```python +if test_expression: + if test_expression: + block of code + else: + block of code +else: + block of code +``` + +This syntax shows an if else statement nested inside an if else statement. + +```python +num = float(input("Enter a number: ")) +if num >= 0: + if num == 0: + print("Zero") + else: + print("Positive number") +else: + print("Negative number") +``` + +#### Substitute for Switch Case +Unlike other programming languages, Python does not have a ‘switch‘ statement. You can use if…elif…elif sequence as a substitute. + +```python +if choice == 1: + print('case 1') +elif choice == 2: + print('case 2') +elif choice == 3: + print('case 3') +elif choice == 4: + print('case 4') +else: + print('default case') +``` +#### Multiple Conditions +To join two or more conditions into a single if statement, use logical operators viz. and, or and not. + +`and expression` is `True`, if all the conditions are true. +`or expression` is `True`, if at least one of the conditions is True. +`not expression` is `True`, if the condition is false + +```python +# and expression is True, if all the conditions are true. +x, y, z = 7, 4, 2 +if x > y and x > z: + print('x is greater') + +# Prints x is greater + +# or expression is True, if at least one of the conditions is True. +x, y, z = 7, 4, 9 +if x > y or x > z: + print('x is greater than y or z') + +# Prints x is greater than y or z + +# not expression is True, if the condition is false +x, y = 7, 5 +if not x < y: + print('x is greater') + +# Prints x is greater +``` +#### Conditional Expressions (ternary operator) +Conditional expression (sometimes referred to as ‘ternary operator’) allows us to select one of two statements depending on the specified condition. + +The syntax of the conditional expression is +![](./images/if2.PNG) +```python +x, y = 7, 5 +print('x is greater') if x > y else print('y is greater') + +# Prints x is greater +You can also use it to select variable assignment. + +x, y = 7, 5 +max = x if x > y else y +print(max) +# Prints 7 +``` + +#### Check If Item Present in a Sequence +The in operator is used to check if a value is present in a sequence `(list, tuple, string etc.).` + +```python +# list +L = ['red', 'green', 'blue'] +if 'red' in L: + print('yes') +# Prints yes + +# tuple +T = ('red', 'green', 'blue') +if 'red' in T: + print('yes') +# Prints yes + +# string +S = 'Hello, World!' +if 'Hello' in S: + print('Yes') +# Prints yes +``` \ No newline at end of file diff --git a/Python Tutorial/Lambda Function.md b/Python Tutorial/Lambda Function.md new file mode 100644 index 0000000..00653d2 --- /dev/null +++ b/Python Tutorial/Lambda Function.md @@ -0,0 +1,368 @@ +# Lambda Function + +source: `{{ page.path }}` + +`Lambda` is one of the most useful, important and interesting features in Python. Unfortunately, they are easy to misunderstand and get wrong. + +What is a Lambda Function? +A lambda is simply a way to define a function in Python. They are sometimes known as lambda operators or lambda functions. + +By now you probably have defined your functions using the def keyword, and it has worked well for you so far. So why is there another way to do the same thing? + +The difference is that lambda functions are anonymous. Meaning, they are functions that do not need to be named. They are used to create small one-line functions in cases where a normal function would be an overkill. + +#### Basic Example +Before looking at a lambda function, let’s look at a super basic function defined the “traditional” way: Here is a simple function that doubles the passed value. +```python +def doubler(x): + return x*2 + +print(doubler(2)) +# Prints 4 + +print(doubler(5)) +# Prints 10 + +## Here’s how it looks as a lambda function: + +doubler = lambda x: x*2 + +print(doubler(2)) +# Prints 4 + +print(doubler(5)) +# Prints 10 +``` +In the above example, the lambda is constructed as: + +```javascript + +lambda parameters: expression + +``` + +#### Important Characteristics +##### Single Expression Only +Unlike a normal function, a lambda function contains only a single expression. + +Although, you can spread the expression over multiple lines using parentheses or a multiline string, but it should only remain as a single expression. +```python +evenOdd = (lambda x: + 'odd' if x%2 else 'even') + +print(evenOdd(2)) +# Prints even + +print(evenOdd(3)) +# Prints odd +``` + +##### Immediately Invoked Function Expression (IIFE) +A lambda function can be immediately invoked. For this reason it is often referred to as an Immediately Invoked Function Expression (IIFE). + +Here’s the same previously seen ‘doubler’ lambda function that is defined and then called immediately with 3 as an argument. + +```python +print((lambda x: x*2)(3)) +# Prints 6 +``` +#### Multiple Arguments + +You can send as many arguments as you like to a lambda function; just separate them with a comma ,. + +Here’s how you’d create a lambda function with multiple arguments: +```python +# A lambda function that multiplies two values +mul = lambda x, y: x*y +print(mul(2, 5)) +# Prints 10 +# A lambda function that adds three values +add = lambda x, y, z: x+y+z +print(add(2, 5, 10)) +# Prints 17 +``` +#### Ways to Pass Arguments +Like a normal function, a lambda function supports all the different ways of passing arguments. This includes: + +* Positional arguments +* Keyword arguments +* Default argument +* Variable list of arguments (*args) +* Variable list of keyword arguments (**args) + +The following examples illustrate various options for passing arguments to the lambda function. +```python +# Positional arguments +add = lambda x, y, z: x+y+z +print(add(2, 3, 4)) +# Prints 9 + +# Keyword arguments +add = lambda x, y, z: x+y+z +print(add(2, z=3, y=4)) +# Prints 9 + +# Default arguments +add = lambda x, y=3, z=4: x+y+z +print(add(2)) +# Prints 9 + +# *args +add = lambda *args: sum(args) +print(add(2, 3, 4)) +# Prints 9 + +# **args +add = lambda **kwargs: sum(kwargs.values()) +print(add(x=2, y=3, z=4)) +# Prints 9 +``` +#### Lambdas With Map, Filter, and Reduce +The Python core library has three methods called map(), filter(), and reduce(). These methods are possibly the best reasons to use lambda functions. + +##### With map() +The map() function expects two arguments: a function and a list. It takes that function and applies it on every item of the list and returns the modified list. + +Here’s a map() function without a lambda: +```python +# Double each item of the list +def doubler(x): + return x*2 + +L = [1, 2, 3, 4, 5, 6] +mod_list = map(doubler, L) +print(list(mod_list)) +# Prints [2, 4, 6, 8, 10, 12] +``` +In above example the doubler function is passed in as an argument, but what if you don’t want to create a new function every time you use the map()? You can use a lambda instead! +```python +# Double each item of the list +L = [1, 2, 3, 4, 5, 6] +doubler = map(lambda x: x*2, L) +print(list(doubler)) +# Prints [2, 4, 6, 8, 10, 12] +``` +As you can see, the entire doubler function is no longer needed. Instead, the lambda function is used to create more concise code. + +##### With filter() +The filter() function is similar to the map(). It takes a function and applies it to each item in the list to create a new list with only those items that cause the function to return True. + +First, without a lambda: +```python +# Filter the values above 18 +def checkAge(age): + if age > 18: + return True + else: + return False + +age = [5, 11, 16, 19, 24, 42] +adults = filter(checkAge, age) +print(list(adults)) +# Prints [19, 24, 42] +Here’s what the above code looks like, with the checkAge function replaced by a lambda: + +# Filter the values above 18 +age = [5, 11, 16, 19, 24, 42] +adults = filter(lambda x: x > 18, age) +print(list(adults)) +# Prints [19, 24, 42] +``` +##### With reduce() +reduce() is another Python function. It applies a rolling calculation to all items in a list. You can use it to calculate the total sum or to multiply all the numbers together. + +Here’s a reduce() function without a lambda: +```python +# sum all items in a list +from functools import reduce + +def summer(a, b): + return a + b + +L = [10, 20, 30, 40] +result = reduce(summer, L) +print(result) +# Prints 100 +There is no need for a new function here either: + +from functools import reduce + +L = [10, 20, 30, 40] +result = reduce(lambda a, b: a + b, L) +print(result) +# Prints 100 +``` +#### Return Multiple Values +To return multiple values pack them in a tuple. Then use multiple assignment to unpack the parts of the returned tuple. +```python +# Return multiple values by packing them in a tuple +findSquareCube = lambda num: (num**2, num**3) +x, y = findSquareCube(2) +print(x) +# Prints 4 +print(y) +# Prints 8 +``` +#### if else in a Lambda +Generally if else statement is used to implement selection logic in a function. But as it is a statement, you cannot use it in a lambda function. You can use the if else ternary expression instead. +```python +# A lambda function that returns the smallest item +findMin = lambda x, y: x if x < y else y + +print(findMin(2, 4)) +# Prints 2 + +print(findMin('a', 'x')) +# Prints a +``` +#### List Comprehension in a Lambda +List comprehension is an expression, not a statement, so you can safely use it in a lambda function. +```python +# Flatten a nested list with lambda +flatten = lambda l: [item for sublist in l for item in sublist] + +L = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] +print(flatten(L)) +# Prints [1, 2, 3, 4, 5, 6, 7, 8, 9] + +L = [['a', 'b', 'c'], ['d', 'e']] +print(flatten(L)) +# Prints ['a', 'b', 'c', 'd', 'e'] +``` +#### Jump Table Using a Lambda +The jump table is a list or dictionary of functions to be called on demand. Here’s how a lambda function is used to implement a jump table. +```python +# dictionary of functions +exponent = {'square':lambda x: x ** 2, + 'cube':lambda x: x ** 3} + +print(exponent['square'](3)) +# Prints 9 + +print(exponent['cube'](3)) +# Prints 27 +# list of functions +exponent = [lambda x: x ** 2, + lambda x: x ** 3] + +print(exponent[0](3)) +# Prints 9 + +print(exponent[1](3)) +# Prints 27 +``` +#### Lambda Key Functions +In Python, key functions are higher-order functions that take another function (which can be a lambda function) as a key argument. This function directly changes the behavior of the key function itself. Here are some key functions: + +List method: sort() +Built-in functions: sorted(), min(), max() +In the Heap queue algorithm module heapq: nlargest() and nsmallest() +In the following example, a lambda is assigned to the key argument so that the list of students is sorted by their age rather than by name. + +```python +# Sort the list of taples by the age of students +L = [('Sam', 35), + ('Max', 25), + ('Bob', 30)] +x = sorted(L, key=lambda student: student[1]) +print(x) +# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)] +``` +#### Decorating a lambda +A decorator can be applied to a lambda. Although it is not possible to decorate a lambda with the @decorator syntax, you can apply the decorator manually, by calling the decorator and passing the lambda as an argument. + +Let’s create a @debug decorator that will do the following, whenever the function is called: + +* Print the function’s name +* Print the values of its arguments +* Run the function with the arguments +* Print the result +* Return the modified function for use +* from functools import wraps +```python +# Defining a decorator +def debug(func): + @wraps(func) + def wrapper(*args, **kwargs): + result = func(*args) + print(f"[DEBUG] Calling {func.__name__} with argument {args} | Result: {result}") + return result + return wrapper + +# Applying decorator to hello() +@debug +def hello(name): + return "Hello " + name + +# Calling the decorated function +print(hello("Bob")) +# Prints [DEBUG] Calling hello with argument ('Bob',) | Result: Hello Bob +# Prints Hello Bob +Let’s apply our @debug decorator to a lambda and see how it actually works. + +print((debug(lambda x: x ** 2))(3)) +# Prints [DEBUG] Calling with argument (3,) | Result: 9 +# Prints 9 +Decorating the lambda function in this way can be useful for debugging purposes, possibly to debug the behavior of the lambda function used in higher-order functions or key functions. Here is an example with map(): + +print(list(map(debug(lambda x: x*2), range(3)))) +# Prints [DEBUG] Calling with argument (0,) | Result: 0 +# Prints [DEBUG] Calling with argument (1,) | Result: 2 +# Prints [DEBUG] Calling with argument (2,) | Result: 4 +# Prints [0, 2, 4] +``` +#### Lambda Closures +As a normal function can be a closure, so can a lambda function. Here’s a closure constructed with a normal Python function: +```python +def multiplier(x): + def inner_func(y): + return x*y + return inner_func + +doubler = multiplier(2) +print(doubler(10)) +# Prints 20 + +tripler = multiplier(3) +print(tripler(10)) +# Prints 30 +``` +Here the multiplier() returns inner_func() which computes the multiplication of two arguments: + +x is passed as an argument to multiplier() +y is an argument passed to inner_func() +Similarly, a lambda can also be a closure. Here’s the same example with a lambda function: +```python +multiplier = (lambda x: (lambda y: x*y)) + +doubler = multiplier(2) +print(doubler(10)) +# Prints 20 + +tripler = multiplier(3) +print(tripler(10)) +# Prints 30 +``` + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Python Tutorial/Python.programs.md b/Python Tutorial/Python.programs.md new file mode 100644 index 0000000..9243f64 --- /dev/null +++ b/Python Tutorial/Python.programs.md @@ -0,0 +1,226 @@ +# Python Programs +source: `{{ page.path }}` +## Basic Programs +#### All Arithmetic operations of 2 no +```python +# Store input numbers: +num1 = input('Enter first number: ') +num2 = input('Enter second number: ') + +# Add two numbers +add = float(num1) + float(num2) +# Subtract two numbers +sub = float(num1) - float(num2) +# Multiply two numbers +mul = float(num1) * float(num2) +#Divide two numbers +div = float(num1) / float(num2) + +# Display the sum +print(f"The sum of {num1} and {num2} is {add}") +# Display the subtraction +print(f"The sub of {num1} and {num2} is {sub}") +# Display the multiplication +print(f"The mul of {num1} and {num2} is {mul}") +# Display the division +print(f"The div of {num1} and {num2} is {div}") +``` +#### python program to swap 2 numbers +```python +# method 1 +x = 1 +y = 0 +temp = x +x = y +y = temp +print(f"values of x={x} and y={y}") +# method 2 +x = 1 +y = 0 +x,y = y,x +print(f"values of x={x} and y={y}") +# method 3 +x = 10 +y = 50 + +# Swapping of two variables +# using arithmetic operations +x = x + y +y = x - y +x = x - y +print(f"values of x={x} and y={y}") +``` +#### python program convert km to miles + +```python +# converting Kilometer in to miles +# 1 kilometer is equal to 0.62137 miles +x = float(input("enter the no of kilometers : ")) +miles = x * 0.62137 +print(f" Total no of {x} kilometers in to miles is {miles}") +``` + +#### python program convert celsius to Fahrenheit + +```python + +## T(℉) = T(℃) x 1.8 + 32 +C = float(input("enter the celsius value : ")) +F = ( C * 1.8 ) + 32 +print(f"The celsius of {C} in Fahrenheit temp is {F}") +``` + +#### Python program to display calender + +```python +import calendar +# Enter the month and year +yy = int(input("Enter year: ")) +mm = int(input("Enter month: ")) + +# display the calendar +print(calendar.month(yy,mm)) +``` + +#### python program of multiplication table + +```python +mul = int(input("Enter the no for multiplication : ")) +for i in range(1,11): + print(mul, "*" ,i, "=" ,mul * i) +``` + +#### Pythom program for Leap Year + +```python +year = int(input("Enter a year: ")) +if (year % 4) == 0: + if (year % 100) == 0: + if (year % 400) == 0: + print(f"{year} is a leap year") + else: + print(f"{year} is not a leap year") + else: + print(f"{year} is a leap year") +else: + print(f"{year} is not a leap year") +``` + +#### Prime number + +```python +for num in range(15): + if num > 1: + for i in range(2,num): + if (num % i) == 0: + break + else: + print(f"{num} is prime number") +``` +#### Factorial number + +```python +num = int(input("Enter a number: ")) +factorial = 1 +if num < 0: + print(" factorial does not exist for negative numbers") +elif num == 0: + print("The factorial of 0 is 1") +else: + for i in range(1,num + 1): + factorial = factorial*i + print("The factorial of",num,"is",factorial) +``` +#### MAX and Min numbers + +```python +# Given list of numbers +list = [ 3,2,19,10] + +# sorting the given list "list" +# sort() function sorts the list in ascending order +list.sort() +# Displaying the first element of the list +# which is the smallest number in the sorted list +print("list of small number : ",list[0]) +print("list of Big number : ",list[-1]) + +## method 2 +list = [ 87,64,78,99,96 ] +print("Maximum number in list : ", max(list)) +print("Minimum number in list : ", min(list)) +``` + +#### sum of cubes +An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 + +```python +## method 1 +def sumofcubes(n): + sum = 0 + for i in range (1,n+1): + sum += i*i*i + return sum +n = int(input("enter the value of n: ")) +print(sumofcubes(n)) + +## method 2 +# Returns the sum of series with mathematical formula is (n ( n + 1 ) / 2) ^ 2 +def sumofcubes(n): + x = (n * (n + 1) / 2) + return (int)(x * x) + +# Driver Function +n = int(input("Enter the value of number: ")) +print(sumofcubes(n)) + +``` +#### Sum of squares of natural numbers + +```python +# Method 1 +# Return the sum of square of first n natural numbers +def squaresum(n) : + # Iterate i from 1 and n finding square of i and add to sum. + sum = 0 + for i in range(1, n+1) : + sum = sum + (i * i) + return sum +n = int(input("enter the value of n : ")) +print(squaresum(n)) + + +# method 2 + +## n * (n + 1) * (2 * n + 1)/6 +def sumofsquares(n): + sum = n * (n + 1) * (2 * n + 1) // 6 + return sum + +n = int(input("enter the value of n : ")) +print(sumofsquares(n)) +``` + +#### Remove punctuation from string +```python +# Removing punctuations in string +# Using regex +import re + +# initializing string +test_str = "python, is best program: to learn !!!;" + +# printing original string +print("The original string is : " + test_str) + +# Removing punctuations in string Using regex +res = re.sub(r'[^\w\s]', '', test_str) + +# printing result +print("The string after punctuation filter : " + res) + +# output : +The original string is : python, is best program: to learn !!!; +The string after punctuation filter : python is best program to learn + +``` diff --git a/Python Tutorial/README.md b/Python Tutorial/README.md new file mode 100644 index 0000000..5dce28e --- /dev/null +++ b/Python Tutorial/README.md @@ -0,0 +1,13 @@ +--- +sort: 1 +--- + +# Python Tutorial + + + +# source: `{{ page.path }}` \ No newline at end of file diff --git a/Python Tutorial/Strings.md b/Python Tutorial/Strings.md new file mode 100644 index 0000000..90363ae --- /dev/null +++ b/Python Tutorial/Strings.md @@ -0,0 +1,616 @@ +# Strings + +source: `{{ page.path }}` + +A string is a sequence of characters. You must have used strings in other languages as well. Python strings play the same role as character arrays in languages like C, but they are somewhat higher-level tools than arrays. + +Unlike languages such as C, in Python, strings come with a powerful set of processing tools. + +#### Create a String +A python string is zero or more characters written inside single quotes ' ' or double quotes " " +```python +S = 'Hello, World!' # single quotes +S = "Hello, World!" # double quotes +``` + +#### Multiline Strings +You can create a multiline string using triple-quotes: """ """ or ''' '''. +```python +S = """String literals can +span multiple lines.""" +print(S) +# String literals can +# span multiple lines. +The str() Constructor +You can convert almost any object in Python to a string using a type constructor called str() + +# an integer to a string +S = str(42) +print(S) +# Prints '42' + +# a complex number to a string +S = str(3+4j) +print(S) +# Prints '(3+4j) + +# a list to a string +S = str([1,1]) +print(S) +# Prints '[1, 1]' +``` + +#### Access Characters by Index +You can access individual characters in a string using an index in square brackets. The string indexing starts from 0. + +You can also access a string by negative indexing. A negative string index counts from the end of the string. + +The indices for the elements in a string are illustrated as below: + +![](./images/string.PNG) +```python +String Indexing +# Indexing +S = 'ABCDEFGHI' +print(S[0]) # Prints A +print(S[4]) # Prints E + +# Negative Indexing +S = 'ABCDEFGHI' +print(S[-1]) # Prints I +print(S[-6]) # Prints D +``` +#### Slicing a String +A segment of a string is called a slice and you can extract one by using a slice operator. A slice of a string is also a string. + +The slice operator [n:m] returns the part of the string from the “n-th” item to the “m-th” item, including the first but excluding the last. +```python +S = 'ABCDEFGHI' +print(S[2:5]) # Prints CDE +print(S[5:-1]) # Prints FGH +print(S[1:6:2]) # Prints BDF +``` +The string slicing capability provided by python is extensive and covered in full detail here. + +#### Modify a String +It is tempting to use the [] operator on the left side of an assignment, in order to convert a character into a string. for example: +```python +S = 'Hello, World!' +S[0] = 'J' +# Triggers TypeError: 'str' object does not support item assignment +The reason for the error is that the strings are unchangeable (immutable) and because of which you cannot change the existing string. The best you can do is create a new string that is a variation of the original: + +S = 'Hello, world!' +new_S = 'J' + S[1:] +print(new_S) +# Prints Jello, world! +``` +#### String Concatenation +You can concatenate strings using the concatenation operator + or the augmented assignment operator += +```python +# concatenation operator +S = 'Hello,' + ' World!' +print(S) +# Hello, World! + +# augmented assignment operator +S = 'Hello,' +S += ' World!' +print(S) +# Prints Hello, World! + +In Python, two or more strings next to each other are automatically concatenated, known as Implicit concatenation. + +S = 'Hello,' " World!" +print(S) +# Prints Hello, World! +Implicit concatenation only works with two literals though, not with variables or expressions. + +You can also put several strings within parentheses to join them together. This feature is useful when you want to break long strings. + +S = ('Put strings within parentheses ' + 'to join them together.') +print(S) +# Put strings within parentheses to join them together. +``` +You can replicate substrings in a string using the replication operator * +``` +# the hard way +S = '--------------------' + +# the easy way +S = '-' * 20 +``` +#### Find String Length +To find the number of characters in a string, use len() built-in function. +```python +S = 'Supercalifragilisticexpialidocious' +print(len(S)) +# Prints 34 +``` +#### Replace Text Within a String +Sometimes you want to replace a text inside a string, then you can use the replace() method. +```python +S = 'Hello, World!' +x = S.replace('World', 'Universe') +print(x) +# Prints Hello, Universe! +``` +#### Split and Join a String +Use split() method to chop up a string into a list of substrings, around a specified delimiter. +```python +# Split the string on comma +S = 'red,green,blue,yellow' +x = S.split(',') +print(x) +# Prints ['red', 'green', 'blue', 'yellow'] +print(x[0]) +# Prints red + +And use join() method to join the list back into a string, with a specified delimiter in between. + +# Join the list of substrings +L = ['red', 'green', 'blue', 'yellow'] +S = ','.join(L) +print(S) +# Prints red,green,blue,yellow +``` +#### String Case Conversion +Python provides five methods to perform case conversion on the target string viz. lower(), upper(), capitalize(), swapcase() and title() +```python +S = 'Hello, World!' +print(S.lower()) +# Prints hello, world! + +S = 'Hello, World!' +print(S.upper()) +# Prints HELLO, WORLD! + +S = 'Hello, World!' +print(S.capitalize()) +# Prints Hello, world! + +S = 'Hello, World!' +print(S.swapcase()) +# Prints hELLO, wORLD! + +S = 'hello, world!' +print(S.title()) +# Prints Hello, World! +``` +#### Check if Substring Contains in a String +To check if a specific text is present in a string, use in operator. The in is a boolean operator, which takes two strings and returns True if the first appears as a substring in the second: + +```python +S = 'Hello, World!' +print('Hello' in S) +# Prints True +``` +To search for a specific text within a string, use find() method. It returns the lowest index in the string where substring is found. + +```python +# Search for 'Foolish' within a string +S = 'Stay Hungry, Stay Foolish' +x = S.find('Foolish') +print(x) +# Prints 18 + +``` +#### Iterate Through a String +To iterate over the characters of a string, use a simple for loop. +```python +# Print each character in a string +S = 'Hello, World!' +for letter in S: + print(letter, end=' ') +# H e l l o , W o r l d ! +``` +#### Python Escape Sequence +You can use quotes inside a string, as long as they don’t match the quotes surrounding the string. +```python +S = "We're open" # Escape single quote +S = "I said 'Wow!'" # Escape single quotes +S = 'I said "Wow!"' # Escape double quotes +``` +This is fine for most of the time but what if you want to declare a string with both single and double quotes like: + +`Bob told me, “Sam said, ‘This won’t work.'”` + +Python will raise a `SyntaxError`, because both quotation marks are special characters. The solution to avoid this problem is to use the backslash escape character \. + +Prefixing a special character with \ turns it into an ordinary character. This is called escaping. +```python +S = "Bob told me, \"Sam said, 'This won't work.'\"" +print(S) +# Prints Bob told me, "Sam said, 'This won't work.'" +Backslash escape character is used in representing certain special characters like: \n is a newline, \t is a tab. These are known as escape sequences. + +S = str('First line.\n\tSecond line.') +print(S) +# First line. +# Second line. +``` +#### String Methods + +|Function |Description | +|---------------|-------------------------------------------------------------------------------------------------------------------------------| +|encode() |Python string encode() function is used to encode the string using the provided encoding. | +|count() |Python String count() function returns the number of occurrences of a substring in the given string. | +|startswith() |Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False. | +|endswith() |Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False. | +|capitalize() |Python String capitalize() function returns the capitalized version of the string. | +|center() |Python string center() function returns a centered string of specified size. | +|casefold() |Python string casefold() function returns a casefolded copy of the string. This function is used to perform case-insensitive | | |string comparison. | +|expandtabs() |Python string expandtabs() function returns a new string with tab characters (\t) replaced with one or more whitespaces. | +|index() |Python String index() function returns the lowest index where the specified substring is found. | +| __contains__()|Python String class has __contains__() function that we can use to check if it contains another string or not. We can also use | | | “in” operator to perform this check. | + + + +##### Conversion Functions + +`capitalize()` – Returns the string with the first character capitalized and rest of the characters in lower case. +```python +var = 'PYTHON' +print (var.capitalize()) +# Python +``` + +`lower()` – Converts all the characters of the String to lowercase + +```python +var = 'FootBall' +print (var.lower()) +# football +``` + +`upper()` – Converts all the characters of the String to uppercase + +```python +var = 'FootBall' +print (var.upper()) +# FOOTBALL +``` + +`swapcase()` – Swaps the case of every character in the String means that lowercase characters got converted to uppercase and vice-versa. + +```python +var = 'FootBall' +print (var.swapcase()) +# fOOTbALL +``` + +`title()` – Returns the ‘titlecased’ version of String, which means that all words start with uppercase and the rest of the characters in words are in lowercase. + +```python +var = 'welcome to Python programming' +print (var.title()) +# Welcome To Python Programming +``` + +`count( str[, beg [, end]])` – Returns the number of times substring ‘str’ occurs in +the range [beg, end] if beg and end index are given else the search continues in full String Search is case-sensitive. + +```python +var='Television' +str='e' +print (var.count(str)) +# 2 +var1='Eagle Eyes' +print (var1.count('e')) +# 2 +var2='Eagle Eyes' +print (var2.count('E',0,5)) +# 1 +``` + +##### Comparison Functions – Part1 + +`islower()` – Returns ‘True’ if all the characters in the String are in lowercase. If any of the char is in uppercase, it will return False. + +```python +var='Python' +print (var.islower()) +# False + +var='python' +print (var.islower()) +# True +``` + +`isupper()` – Returns ‘True’ if all the characters in the String are in uppercase. If any of the char is in lowercase, it will return False. + +```python +var='Python' +print (var.isupper()) +# False + +var='PYTHON' +print (var.isupper()) +# True +``` + +`isdecimal()` – Returns ‘True’ if all the characters in String are decimal. If any character in the String is of other data-type, it will return False.Decimal characters are those from the Unicode category Nd. + +```python +num=u'2016' +print (num.isdecimal()) +# True +``` + +`isdigit()` – Returns ‘True’ for any char for which isdecimal() would return ‘True and some characters in the ‘No’ category. If there are any characters other than these, it will return False’. + +Precisely, digits are the characters for which Unicode property includes: Numeric_Type=Digit or Numeric_Type=Decimal. + +For example, superscripts are digits, but fractions not. + +```python +print ('2'.isdigit()) +# True + +print ('²'.isdigit()) +# True +``` + +##### Comparison Functions – II + +`isnumeric()` – Returns ‘True’ if all the characters of the Unicode String lie in any one of the categories Nd, No, and NI. + +If there are any characters other than these, it will return False. + +Precisely, Numeric characters are those for which Unicode property includes: Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. + +```python +num=u'2016' +print (num.isnumeric()) +# True + +num=u'year2016' +print (num.isnumeric()) +# False +``` + +`isalpha()` – Returns ‘True’ if String contains at least one character (non-empty String), and all the characters are alphabetic, ‘False’ otherwise. + +```python +print ('python'.isalpha()) +# True + +print ('python3'.isalpha()) +# False +``` + +`isalnum()` – Returns ‘True’ if String contains at least one character (non-empty String), and all the characters are either alphabetic or decimal digits, ‘False’ otherwise. + +```python +print ('python'.isalnum()) +# True +print ('python3'.isalnum()) +# True +``` + +##### Padding Functions + +`rjust(width[,fillchar])` – Returns string filled with input char while pushing the original content on the right side. + +By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler character. + +```python +var='Python' +print (var.rjust(10)) +# Python + +print (var.rjust(10,'-')) +# ----Python +``` + +`ljust(width[,fillchar])` – Returns a padded version of String with the original String left-justified to a total of width columns + +By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler character. + +```python +var='Python' +print (var.ljust(10)) +# Python + +print (var.ljust(10,'-')) +# Python---- +``` + +`center(width[,fillchar])` – Returns string filled with the input char while pushing the original content into the center. + +By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler character. + +```python +var='Python' +print (var.center(20)) +# Python + +print (var.center(20,'*')) +# *******Python******* +``` + +`zfill(width)` – Returns string filled with the original content padded on the left with zeros so that the total length of String becomes equal to the input size. + +If there is a leading sign (+/-) present in the String, then with this function, padding starts after the symbol, not before it. + +```python +var='Python' +print (var.zfill(10)) +# 0000Python + +var='+Python' +print (var.zfill(10)) +# +000Python +``` + +##### Search Functions + +`find(str [,i [,j]])` – Searches for ‘str’ in complete String (if i and j not defined) or in a sub-string of String (if i and j are defined).This function returns the index if ‘str’ is found else returns ‘-1’. + +Here, i=search starts from this index, j=search ends at this index. +See more details – Python String Find() + +```python +var="High sky" +str="sky" +print (var.find(str)) +# 5 + +var="High sky" +str="sky" +print (var.find(str,4)) +# 5 + +var="High sky" +str="sky" +print (var.find(str,7)) +# -1 +``` + +`index(str[,i [,j]])` – This is same as ‘find’ method. The only difference is that it raises the ‘ValueError’ exception if ‘str’ doesn’t exist. + +```python +var='High Sky' +str='sky' +print (var.index(str)) +# 5 + +var='High Sky' +str='sky' +print (var.index(str,4)) +# 5 + +var='High Sky' +str='sky' +print (var.index(str,7)) +# ValueError: substring not found +``` + +`rfind(str[,i [,j]])` – This is same as find() just that this function returns the last index where ‘str’ is found. If ‘str’ is not found, it returns ‘-1’. + +```python +var='This is a good example' +str='is' +print (var.rfind(str,0,10)) +# 5 + +print (var.rfind(str,10)) +# -1 +``` + +`count(str[,i [,j]])` – Returns the number of occurrences of substring ‘str’ in the String. Searches for ‘str’ in the complete String (if i and j not defined) or in a sub-string of String (if i and j are defined). + +Where: i=search starts from this index, j=search ends at this index. + +```python +var='This is a good example' +str='is' +print (var.count(str)) +# 2 + +print (var.count(str,4,10)) +# 1 +``` + +##### String Substitution Functions + +`replace(old,new[,count])` – Replaces all the occurrences of substring ‘old’ with ‘new’ in the String. + +If the count is available, then only ‘count’ number of occurrences of ‘old’ will be replaced with the ‘new’ var. + +Where old =substring to replace, new =substring + +```python +var='This is a good example' +str='was' +print (var.replace('is',str)) +# Thwas was a good exampleprint (var.replace('is',str,1)) +# Thwas is a good example +``` + +`split([sep[,maxsplit]])` – Returns a list of substring obtained after splitting the String with ‘sep’ as a delimiter. + +Where, sep= delimiter, the default is space, maxsplit= number of splits to be done + +```python +var = "This is a good example" +print (var.split()) +# ['This', 'is', 'a', 'good', 'example']print (var.split(' ', 3)) +# ['This', 'is', 'a', 'good example'] +``` + +`splitlines(num)` – Splits the String at line breaks and returns the list after removing the line breaks. + +Where num = if this is a positive value. It indicates that line breaks will appear in the returned list. + +```python +var='Print new line\nNextline\n\nMove again to new line' +print (var.splitlines()) +# ['Print new line', 'Nextline', '', 'Move again to new line']print (var.splitlines(1)) +# ['Print new line\n', 'Nextline\n', '\n', 'Move again to new line'] +``` + +`join(seq)` – Returns a String obtained after concatenating the sequence ‘seq’ with a delimiter string. + +Where: the seq= sequence of elements to join + +```python +seq=('ab','bc','cd') +str='=' +print (str.join(seq)) +# ab=bc=cd +``` + +##### Misc String Functions + +`lstrip([chars])` – Returns a string after removing the characters from the beginning of the String. + +Where: Chars=this is the character to be trimmed from the String. + +The default is whitespace character. + +```python +var=' This is a good example ' +print (var.lstrip()) +# This is a good example +var='*****This is a good example*****' +print (var.lstrip('*')) +# This is a good example********** +``` + +`rstrip()` – Returns a string after removing the characters from the End of the String. + +Where: Chars=this is the character to be trimmed from the String. The default is whitespace character. + +```python +var=' This is a good example ' +print (var.rstrip()) +# This is a good example +var='*****This is a good example*****' +print (var.lstrip('*')) +# *****This is a good example +``` + +`rindex(str[,i [,j]])` – Searches for ‘str’ in the complete String (if i and j not defined) or in a sub-string of String (if i and j are defined). This function returns the last index where ‘str’ is available. + +If ‘str’ is not there, then it raises a ValueError exception. + +Where: i=search starts from this index, j=search ends at this index. + +```python +var='This is a good example' +str='is' +print (var.rindex(str,0,10)) +# 5 +print (var.rindex(str,10)) +# ValueError: substring not found +``` + +`len(string)` – Returns the length of given String + +```python +var='This is a good example' +print (len(var)) +# 22 +``` diff --git a/Python Tutorial/Variables.md b/Python Tutorial/Variables.md new file mode 100644 index 0000000..18096d4 --- /dev/null +++ b/Python Tutorial/Variables.md @@ -0,0 +1,556 @@ +# Variables + +source: `{{ page.path }}` + +A variable is a container for a value. It can be assigned a name, you can use it to refer to it later in the program. Based on the value assigned, the interpreter decides its data type. You can always store a different type in a variable. + +1. Python Variables Naming Rules + +There are certain rules to what you can name a variable(called an identifier). +* Python variables can only begin with a letter(A-Z/a-z) or an underscore(_).but it cannot start with a digit. +* The name of the variable should start with either an alphabet letter (lower or upper case) or an underscore (_), +More than one alpha-numeric characters or underscores may follow. +* The variable name can consist of alphabet letter(s), number(s) and underscore(s) only. For example, myVar, MyVar, _myVar, MyVar123 are valid variable names but m*var, my-var, 1myVar are invalid variable names. +* Identifiers in Python are case sensitive. So, NAME, name, nAME, and nAmE are treated as different variable names. + +``` +Reserved words (keywords) cannot be used as identifier names. + +and def False import not True +as del finally in or try +assert elif for is pass while +break else from lambda print with +class except global None raise yield +continue exec if nonlocal return +``` + +2. Assigning and Reassigning Python Variables + +To assign a value to Python variables, you don’t need to declare its type. You name it according to the rules stated in section 2a, and type the value after the equal sign. + +``` +age=7 +print(age) +7 + +age='Dinosaur' +print(age) +Dinosaur +``` + +3. Multiple Assignment +You can assign values to multiple Python variables in one statement. + +``` +age,city=21,'Indore' +print(age,city) +21 Indore + + Or you can assign the same value to multiple Python variables. + +age=fav=7 +print(age,fav) +7 7 +``` + +4. Swapping Variables +Swapping means interchanging values. To swap Python variables, you don’t need to do much. + +``` +a,b='red','blue' +a,b=b,a +print(a,b) +blue red + +``` +5. Deleting Variables +You can also delete Python variables using the keyword ‘del’. +``` +a='red' +del a +a +``` +image: ![](./images/variable1.PNG) + +### Python Data Types +Although we don’t have to declare a type for Python variables, a value does have a type. This information is vital to the interpreter. Python supports the following Python data types. + +#### 1. Python Numbers +There are four numeric Python data types. + +1.1. `int` +int stands for integer. This Python Data Type holds signed integers. We can use the type() function to find which class it belongs to. + +``` +a=-7 +type(a) + + +An integer can be of any length, with the only limitation being the available memory. + +a=9999999999999999999999999999999 +type(a) + + +``` +1.2. `float` +This Python Data Type holds floating-point real values. An int can only store the number 3, but float can store 3.25 if you want. + +``` +a=3.0 +type(a) + +``` +1.3. `long` +This Python Data type holds a long integer of unlimited length. But this construct does not exist in Python 3.x. + +1.4. `complex` +This Python Data type holds a complex number. A complex number looks like this: a+bj Here, a and b are the real parts of the number, and j is imaginary. +``` +a=2+3j +type(a) + + +Use the isinstance() function to tell if Python variables belong to a particular class. It takes two parameters- the variable/value, and the class. + +print(isinstance(a,complex)) +True +``` +It’s time to know the detail insights of Python numbers. + +#### 2. `Strings` +A string is a sequence of characters. Python does not have a char data type, unlike C++ or Java. You can delimit a string using single quotes or double-quotes. + +``` +city='Ahmedabad' +city +‘Ahmedabad’ + +city="Ahmedabad" +city +‘Ahmedabad’ + +``` + +2.1. Spanning a String Across Lines +To span a string across multiple lines, you can use triple quotes. + +``` +var="""If +only""" +var +‘If\n\tonly’ + +print(var) +If +Only + +"""If +only""" +‘If\n\tonly’ + +As you can see, the quotes preserved the formatting (\n is the escape sequence for newline, \t is for tab). + +``` +2.2. `Displaying Part of a String` +You can display a character from a string using its index in the string. Remember, indexing starts with 0. + +``` +lesson='disappointment' +lesson[0] +‘d’ + +You can also display a burst of characters in a string using the slicing operator []. + +lesson[5:10] +‘point’ + +This prints the characters from 5 to 9. +``` + +2.3. `String Formatters` +String formatters allow us to print characters and values at once. You can use the % operator. + +``` +x=10; +printer="Dell" +print("I just printed %s pages to the printer %s" % (x, printer)) + +Or you can use the format method. +print("I just printed {0} pages to the printer {1}".format(x, printer)) +print("I just printed {x} pages to the printer {printer}".format(x=7, printer="Dell")) + +A third option is to use f-strings. + +print(f"I just printed {x} pages to the printer {printer}") + +``` + +2.4. `String Concatenation` +You can concatenate(join) strings. + +``` +a='10' +print(a+a) +1010 + +However, you cannot concatenate values of different types. + +print('10'+10) +TypeError: must be str, not int +``` + +#### 3. `Python Lists` +A list is a collection of values. Remember, it may contain different types of values. To define a list, you must put values separated with commas in square brackets. You don’t need to declare a type for a list either. + +``` +days=['Monday','Tuesday',3,4,5,6,7] +days +[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7] + +``` + +3.1. `Slicing a List` +You can slice a list the way you’d slice a string- with the slicing operator. +``` +days[1:3] +[‘Tuesday’, 3] + +``` +Indexing for a list begins with 0, like for a string. A Python doesn’t have arrays. + +3.2. `Length of a List` +Python supports an inbuilt function to calculate the length of a list. +``` +len(days) +7 +``` +3.3. `Reassigning Elements of a List` +A list is mutable. This means that you can reassign elements later on. +``` +days[2]='Wednesday' +days +[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7] + +``` +3.4. `Iterating on the List` +To iterate over the list we can use the for loop. By iterating, we can access each element one by one which is very helpful when we need to perform some operations on each element of list. + +``` +Code: + +nums = [1,2,5,6,8] +for n in nums: + print(n) +Output: +1 +2 +5 +6 +8 + +``` +3.5. `Multidimensional Lists` +A list may have more than one dimension. Have a detailed look on this in DataFlair’s tutorial on Python Lists. + +``` +a=[[1,2,3],[4,5,6]] +a +[[1, 2, 3], [4, 5, 6]] + +``` + +#### 4. Python Tuples +A tuple is like a list. You declare it using parentheses instead. + +``` +subjects=('Physics','Chemistry','Maths') +subjects +(‘Physics’, ‘Chemistry’, ‘Maths’) +``` +4.1. `Accessing and Slicing a Tuple` +You access a tuple the same way as you’d access a list. The same goes for slicing it. + +``` +subjects[1] +‘Chemistry’ + +subjects[0:2] +(‘Physics’, ‘Chemistry’) + +``` +4.2. `A tuple is Immutable` +However, Python tuple is immutable. Once declared, you can’t change its size or elements. + +``` +subjects[2]='Biology' + +Traceback (most recent call last): +File “”, line 1, in +subjects[2]=’Biology’ +`TypeError: ‘tuple’ object does not support item assignment` + +subjects[3]='Computer Science' +Traceback (most recent call last): +File “”, line 1, in +subjects[3]=’Computer Science’ +`TypeError: ‘tuple’ object does not support item assignment` + +``` +#### 5. `Dictionaries` +A dictionary holds key-value pairs. Declare it in curly braces, with pairs separated by commas. Separate keys and values by a colon(:). + +``` +person={'city':'Ahmedabad','age':7} +person +{‘city’: ‘Ahmedabad’, ‘age’: 7} + +The type() function works with dictionaries too. + +type(person) + + +``` +5.1. `Accessing a Value` +To access a value, you mention the key in square brackets. + +``` +person['city'] +‘Ahmedabad’ + +``` + +5.2. `Reassigning Elements` +You can reassign a value to a key. + +``` +person['age']=21 +person['age'] +21 + +``` + +5.3. `List of Keys` +Use the keys() function to get a list of keys in the dictionary. + +``` +person.keys() +dict_keys([‘city’, ‘age’]) + +``` + +#### 6. bool +A Boolean value can be True or False. + +``` +a=2>1 +type(a) + + +``` +#### 7. Sets +A set can have a list of values. Define it using curly braces. + +``` +a={1,2,3} +a +{1, 2, 3} + +It returns only one instance of any value present more than once. + +a={1,2,2,3} +a +{1, 2, 3} + +However, a set is unordered, so it doesn’t support indexing. + +a[2] +Traceback (most recent call last): +File “”, line 1, in +a[2] +TypeError: ‘set’ object does not support indexing + +``` +Also, it is mutable. You can change its elements or add more. Use the add() and remove() methods to do so. +``` +a={1,2,3,4} +a +{1, 2, 3, 4} + +a.remove(4) +a +{1, 2, 3} + +a.add(4) +a +{1, 2, 3, 4} + +``` + +#### Type Conversion +Since Python is dynamically-typed, you may want to convert a value into another type. Python supports a list of functions for the same. + +``` +1. `int()` +It converts the value into an int. +int(3.7) +3 + +* Notice how it truncated 0.7 instead of rounding the number off to 4. You can also turn a Boolean into an int. + +int(True) +1 + +int(False) +However, you cannot turn a string into an int. It throws an error. + +int("a") +Traceback (most recent call last): +File “”, line 1, in ; +int(“a”) +ValueError: invalid literal for int() with base 10: ‘a’ + +However, if the string has only numbers, then you can. + +int("77") +77 +``` + +2. `float()` +It converts the value into a float. + +``` +float(7) +7.0 + +float(7.7) +7.7 + +float(True) +1.0 + +float("11") +You can also use ‘e’ to denote an exponential number. + +11.0 + +float("2.1e-2") +0.021 + +float(2.1e-2) +0.021 + +However, this number works even without the float() function. + +2.1e-2 +0.021 + +``` + +3. `str()` +It converts the value into a string. + +``` +str(2.1) +‘2.1’ + +str(7) +‘7’ + +str(True) +‘True’ + +You can also convert a list, a tuple, a set, or a dictionary into a string. + +str([1,2,3]) +‘[1, 2, 3]’ + +``` +4. `bool()` +It converts the value into a boolean. + +``` +bool(3) +True + +bool(0) +False + +bool(True) +True + +bool(0.1) +True + +You can convert a list into a Boolean. + +bool([1,2]) +True + +The function returns False for empty constructs. + +bool() +False + +bool([]) +False + +bool({}) +False + +None is a keyword in Python that represents an absence of value. + +bool(None) +False + +``` + +5. `set()` +It converts the value into a set. + +``` +set([1,2,2,3]) +{1, 2, 3} + +set({1,2,2,3}) +{1, 2, 3} + +Explore Pythons sets and booleans with syntax and examples. + +``` +6. `list()` +It converts the value into a list. + +``` +del list +list("123") +[‘1’, ‘2’, ‘3’] + +list({1,2,2,3}) +[1, 2, 3] + +list({"a":1,"b":2}) +[‘a’, ‘b’] + +However, the following raises an error. + +list({a:1,b:2}) +Traceback (most recent call last): +File “”, line 1, in ; +list({a:1,b:2}) +TypeError: unhashable type: ‘set’ + +``` +7. tuple() +It converts the value into a tuple. + +``` +tuple({1,2,2,3}) +(1, 2, 3) + +You can try your own combinations. Also try composite functions. + +tuple(list(set([1,2]))) +(1, 2) + +``` diff --git a/Python Tutorial/While Loop.md b/Python Tutorial/While Loop.md new file mode 100644 index 0000000..c5825d2 --- /dev/null +++ b/Python Tutorial/While Loop.md @@ -0,0 +1,141 @@ +# While Loop + +source: `{{ page.path }}` + +A while loop is used when you want to perform a task indefinitely, until a particular condition is met. It’s a condition-controlled loop + +#### Python While Loop Syntax +![](./images/while.PNG) + +Basic Examples +Any non-zero value or nonempty container is considered TRUE; whereas Zero, None, and empty container is considered FALSE. +```python +# Iterate until x becomes 0 +x = 6 +while x: + print(x) + x -= 1 +# Prints 6 5 4 3 2 1 +# Iterate until list is empty +L = ['red', 'green', 'blue'] +while L: + print(L.pop()) +# Prints blue green red +# Iterate until string is empty +x = 'blue' +while x: + print(x) + x = x[1:] +# Prints blue +# Prints lue +# Prints ue +# Prints e + +If the condition is false at the start, the while loop will never be executed at all. + +# Exit condition is false at the start +x = 0 +while x: + print(x) + x -= 1 +``` +```python +i=1 +number=0 +b=9 +number = int(input("Enter the number:")) +while i<=10: + print("%d X %d = %d \n"%(number,i,number*i)) + i = i+1 +output : +Enter the number:10 +10 X 1 = 10 +10 X 2 = 20 +10 X 3 = 30 +10 X 4 = 40 +10 X 5 = 50 +10 X 6 = 60 +10 X 7 = 70 +10 X 8 = 80 +10 X 9 = 90 +10 X 10 = 100 +``` +#### Break in while Loop +Python break statement is used to exit the loop immediately. It simply jumps out of the loop altogether, and the program continues after the loop. +```python +# Exit when x becomes 3 +x = 6 +while x: + print(x) + x -= 1 + if x == 3: + break +# Prints 6 5 4 +``` +#### Continue in while Loop +The continue statement skips the current iteration of a loop and continues with the next iteration. +```python +# Skip odd numbers +x = 6 +while x: + x -= 1 + if x % 2 != 0: + continue + print(x) +# Prints 4 2 0 +``` +#### Else in While Loop +Python allows an optional else clause at the end of a while loop. The else clause will be executed when the loop terminates normally (the condition becomes false). +```python +## The else clause will be executed when the loop terminates normally +x = 6 +while x: + print(x) + x -= 1 +else: + print('Done!') +# Prints 6 5 4 3 2 1 +# Prints Done! + +## The else clause will still be executed if the condition is false at the start. +x = 0 +while x: + print(x) + x -= 1 +else: + print('Done!') +# Prints Done! + +## If the loop terminates prematurely with break, the else clause won’t be executed. + +x = 6 +while x: + print(x) + x -= 1 + if x == 3: + break +else: + print('Done!') +# Prints 6 5 4 +``` +#### Infinte Loop (while true) +The condition must eventually become false. Otherwise, the loop will execute forever, creating an infinite/endless loop. + +# Infinte loop with while statement +while True: + print('Press Ctrl+C to stop me!') +You can safely implement an infinite loop in your program using a break statement. +```python +# Loop runs until the user enters 'stop' +while True: + name = input('Enter name:') + if name == 'stop': break + print('Hello', name) + +# Output: +# Enter name:Bob +# Hello Bob +# Enter name:Sam +# Hello Sam +# Enter name:stop +``` \ No newline at end of file diff --git a/Python Tutorial/identifiers.md b/Python Tutorial/identifiers.md new file mode 100644 index 0000000..3cee77b --- /dev/null +++ b/Python Tutorial/identifiers.md @@ -0,0 +1,3 @@ +# identifiers + +source: `{{ page.path }}` \ No newline at end of file diff --git a/Python Tutorial/images/assymetricdifference.PNG b/Python Tutorial/images/assymetricdifference.PNG new file mode 100644 index 0000000..1ffc49e Binary files /dev/null and b/Python Tutorial/images/assymetricdifference.PNG differ diff --git a/Python Tutorial/images/dict1.PNG b/Python Tutorial/images/dict1.PNG new file mode 100644 index 0000000..3c35e25 Binary files /dev/null and b/Python Tutorial/images/dict1.PNG differ diff --git a/Python Tutorial/images/dict2.PNG b/Python Tutorial/images/dict2.PNG new file mode 100644 index 0000000..4253752 Binary files /dev/null and b/Python Tutorial/images/dict2.PNG differ diff --git a/Python Tutorial/images/dict3.PNG b/Python Tutorial/images/dict3.PNG new file mode 100644 index 0000000..2922fe5 Binary files /dev/null and b/Python Tutorial/images/dict3.PNG differ diff --git a/Python Tutorial/images/difference.PNG b/Python Tutorial/images/difference.PNG new file mode 100644 index 0000000..634ad54 Binary files /dev/null and b/Python Tutorial/images/difference.PNG differ diff --git a/Python Tutorial/images/elif.PNG b/Python Tutorial/images/elif.PNG new file mode 100644 index 0000000..c2bfea0 Binary files /dev/null and b/Python Tutorial/images/elif.PNG differ diff --git a/Python Tutorial/images/else.PNG b/Python Tutorial/images/else.PNG new file mode 100644 index 0000000..d8e0ac3 Binary files /dev/null and b/Python Tutorial/images/else.PNG differ diff --git a/Python Tutorial/images/for.PNG b/Python Tutorial/images/for.PNG new file mode 100644 index 0000000..bcf7222 Binary files /dev/null and b/Python Tutorial/images/for.PNG differ diff --git a/Python Tutorial/images/function.PNG b/Python Tutorial/images/function.PNG new file mode 100644 index 0000000..800f3e0 Binary files /dev/null and b/Python Tutorial/images/function.PNG differ diff --git a/Python Tutorial/images/if.PNG b/Python Tutorial/images/if.PNG new file mode 100644 index 0000000..09b205d Binary files /dev/null and b/Python Tutorial/images/if.PNG differ diff --git a/Python Tutorial/images/if1.PNG b/Python Tutorial/images/if1.PNG new file mode 100644 index 0000000..b8ef399 Binary files /dev/null and b/Python Tutorial/images/if1.PNG differ diff --git a/Python Tutorial/images/if2.PNG b/Python Tutorial/images/if2.PNG new file mode 100644 index 0000000..3bf23c4 Binary files /dev/null and b/Python Tutorial/images/if2.PNG differ diff --git a/Python Tutorial/images/intersection.PNG b/Python Tutorial/images/intersection.PNG new file mode 100644 index 0000000..0a65875 Binary files /dev/null and b/Python Tutorial/images/intersection.PNG differ diff --git a/Python Tutorial/images/string.PNG b/Python Tutorial/images/string.PNG new file mode 100644 index 0000000..96236d0 Binary files /dev/null and b/Python Tutorial/images/string.PNG differ diff --git a/Python Tutorial/images/union.PNG b/Python Tutorial/images/union.PNG new file mode 100644 index 0000000..a99f850 Binary files /dev/null and b/Python Tutorial/images/union.PNG differ diff --git a/Python Tutorial/images/variable1.PNG b/Python Tutorial/images/variable1.PNG new file mode 100644 index 0000000..fe85200 Binary files /dev/null and b/Python Tutorial/images/variable1.PNG differ diff --git a/Python Tutorial/images/variable2.PNG b/Python Tutorial/images/variable2.PNG new file mode 100644 index 0000000..7d3ed4e Binary files /dev/null and b/Python Tutorial/images/variable2.PNG differ diff --git a/Python Tutorial/images/while.PNG b/Python Tutorial/images/while.PNG new file mode 100644 index 0000000..b0f12eb Binary files /dev/null and b/Python Tutorial/images/while.PNG differ diff --git a/Python Tutorial/lists.md b/Python Tutorial/lists.md new file mode 100644 index 0000000..740174c --- /dev/null +++ b/Python Tutorial/lists.md @@ -0,0 +1,418 @@ + +# lists +source: `{{ page.path }}` + +A list is a sequence of values (similar to an array in other programming languages but more versatile) + +The values in a list are called items or sometimes elements. + +The important properties of Python lists are as follows: + +* Lists are ordered – Lists remember the order of items inserted. +* Accessed by index – Items in a list can be accessed using an index. +* Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists. +* Lists are changeable (mutable) – You can change a list in-place, add new items, and delete or update existing items. + +```tip +# Python Lists + +1. Lists is a collection of values/elements. +2. list is represented in [] brackets. +3. list allows both Homeogenous & Hetrogenous values/elements. +4. Lists are mutable. +5. list allow duplicate values/elements. +6. lists allow indexing and slicing. +7. Implication of iterations is Time-consuming. +8. The list is better for performing operations, such as insertion and deletion. +9. Lists consume more memory. +10. Lists have several built-in methods + +``` +Python List Tutorial. + +```note +## Lists operations + +1. Creating Lists +2. Accessing Lists +3. Slicing Lists +4. Reassigning Lists +5. Deleting Lists +6. Multidimension Lists +7. Concatenation Lists +8. Operation Lists +9. Iterable Lists +10. Lists Comprehension +11. `Built-in Functions :` min,max,sum,len,all,any,list,sorted +12. `Built-in Methods :` append,insert,remove,pop,index,clear,reverse,count,sort + +``` +## Creating a list + +To create a list in Python, simply add any number of comma separated values between square brackets. Like this +``` +colors = ['red','green','blue'] + +planets = [ "Earth", "Mars", "Saturn", "Jupiter" ] + +``` +## Accessing a list + +``` +List indexing +my_list = ['p', 'r', 'o', 'b', 'e'] +print(my_list[0]) + +# Nested List +n_list = ["Happy", [2, 0, 1, 5]] # nested list +print(n_list[0][1]) # nested indexing + +``` +## slicing list +``` +list = [1,2,3,5,4] +print(list[2:4]) # 3,5,4 +print(list[3:]) # 5,4 +print(list[:3]) # 1,2,3 +print (list[3:-1]) # 5 +print (list[3:-2]) # [] +print(list[:-2]) # 123 +print(list[1:-2]) # 23 +print(list[-2:-1]) # 5 +print(list[-3:-5]) # [] + +l1= [10,20,30,40,50] +print(l1[1:-2]) # 20,30 +print(l1[2:-2]) # 30 +print(l1[1:-2]) # 20,30 + +``` + +| synatax | Explanation | +|------------------|-----------------------------------------------------------| +|a[start:stop] | # items start through stop-1 | +|a[start:] | # items start through the rest of the array | +|a[:stop] | # items from the beginning through stop-1 | +|a[:] | # a copy of the whole array | +| | | +| `Slicing` | `Explanation` | +|a[start:stop:step]| # start through not past stop, by step | +|a[-1] | # last item in the array | +|a[-2:] | # last two items in the array | +|a[:-2] | # everything except the last two items | +|a[::-1] | # all items in the array, reversed | +|a[1::-1] | # the first two items, reversed | +|a[:-3:-1] | # the last two items, reversed | +|a[-3::-1] | # everything except the last two items, reversed | + + +``` +Both +ve and -ve index no are move in -> direction +in +ve index start values is greater than stop values of the list then it will be empty +in -ve index start value is greater than stop value of the list then it will be empty ex: [ -5,-6] + +syntax = [start:stop] + +l2= [10,20,30,40,50,60,70] +print(l2[1:-2]) # 20 -50 +print(l2[2:-5]) # [] +print(l2[2:-4]) # 30 +print(l2[3:-3]) # 40 +print(l2[1:-3]) # 20-40 +print(l2[-7:-3]) # 10-40 +print(l2[-6:4]) # 20-40 +print(l2[:-3]) # 10-40 +print(l2[-3:]) # 50-70 + + +[start : stop : steps] + +`Step increment : ` +a = [1, 2, 3, 4, 5, 6, 7, 8] +print(a[1:4]) # [2,3,4] +print(a[1:4:2]) # [2,4] +print(a[::2]) # [1,3,5,7] +print(a[::3]) # [1,4,7] +print(a[::-1]) # [8,7,6,5,4,3,2,1] +print(a[::-2]) # [8,6,4,2] +print(a[1:-2:2]) # [2,4,6] +``` + +## Re-assigning multiple elements +``` +list=["caramel","gold","silver","occur"] + +# reassign full list +print(list) +list=["red","green","blue","orange"] +print(list) + +# reassign few elements +list=["caramel","gold","silver","occur","bauxite"] +list[2:]=["bronze","zinc"] +print(list) +# ['caramel', 'gold', 'bronze', 'zinc'] + +list=["caramel","gold","helim","silver","occur","bauxite"] +list[:2]=["bronze","zinc"] +print(list) +# ['bronze', 'zinc', 'helim', 'silver', 'occur', 'bauxite'] + +list=["caramel","gold","silver","occur"] +list[2:3]=["bronze","copper"] +print(list) +# ['caramel', 'gold', 'bronze', 'copper', 'occur'] + +list=["caramel","gold","silver","occur","zinc","bauxite"] +list[0:5:2]=["bronze","copper","platinum"] +print(list) +# ['bronze', 'gold', 'copper', 'occur', 'platinum', 'bauxite'] + +Reassigning a single element +list=["caramel","gold","silver","occur"] +list[3]="platinum" +print(list) +# ['caramel', 'gold', 'silver', 'platinum'] + +here we can't add the new element it throw error we need to reassign whole list + +``` +## deleting multiple elements + +``` +list=["caramel","gold","silver","occur"] +# del list +# print(list) + +list=["caramel","gold","silver","occur","Bauxite"] +del list[2:5] +print(list) +# ['caramel', 'gold'] + +del list[2:] +print(list) +# ['caramel', 'gold'] + +del list[:2] +print(list) +# ['silver', 'occur', 'Bauxite'] + +delete single element +list=["caramel","gold","silver","occur"] +del list[1] +print(list) +# ['caramel', 'silver', 'occur'] + +``` +## Multidimensional list in python + +``` +grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil'] +print(grocery_list[0][0]) +# caramel + +a=[[[1,2],[3,4],5],[6,7]] +test=a[0][1][1] +# 4 + +``` +## Concatenation of python list + +``` +Concatenation Operator(+) +a,b,c=[3,1,2],[5,4,6],[7,8] +print(a+b+c) +# [3,1,2,5,4,6,7,8] + +``` +## Iteration with loops + +``` +list1=[1,2,3] +list2=[8,4,5] + +for list in list2: + list1.append(list) +print(list1) + +# [1,2,3,8,4,5] + +list1=[1,2,3,4] +list2=[5,6,7,8] +list3=[9,10,11,12] +result= [] +for x in list1: + result.append(x) +for y in list2: + result.append(y) +for z in list3: + result.append(z) +print(result) + +# [1,2,3,4,5,6,7,8,9,10,11,12] + +mylist=['Dave','Micheal','Harry','Jon'] +k= [] +for x in mylist: + if(len(x)>4): + k.append(x.upper()) + else: + k.append(x.lower()) +print(k) + +``` +## List Comprehensions : + +``` +list1=[1,2,3,4] +list2=[5,6,7,8] +list3=[9,10,11,12] + +result = [element for lis in [list1, list2] for element in lis] +print(result) +# [1,2,3,4,5,6,7,8] + +result1 = [ element for list in [list1,list2,list3] for element in list] +print(result1) +# [1,2,3,4,5,6,7,8,9,10,11,12] + +result2 = [element for lis in [list1] for element in lis] +print(result2) +# [1,2,3,5] + +even=[2*i for i in range(1,11)] +print(even) +# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + +list1=[1,2,3] +list2=[4,5,6] +CombLst=[(x,y) for x in list1 for y in list2] +print(CombLst) +# [1,2,3,4,5,6] + +list = [x for x in range(21) if x%2==0] +print(list) +# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + +obj=["Even" if i%2==0 else "Odd" for i in range(10)] +print(obj) +# ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd'] + +squares = [x*x for x in range(11)] +print(squares) +# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] + +``` +## Operator (Unpacking) + +``` +list1=[1,2,3,4] +list2=[5,6,7,8] +list3=[9,10,11,12] +print([*list1,*list2,*list3]) + +# [1,2,3,4,5,6,7,8,9,10,11,12] + +``` + +## Python List operations + + +|Operator |Description |Example | +|-------------------|------------------------------------------------------------------------------|-------------------------------------| +| + Concatenation |Returns a list containing all the elements of the first and the second list. | >>> L1=[1,2,3] | +| | | >>> L2=[4,5,6] | +| | | >>> L1+L2 | +| | | [1, 2, 3, 4, 5, 6] | +| * Repetition |Concatenates multiple copies of the same list. | >>> L1*4 | +| | | [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]| +| | | | +| [] slice |Returns the item at the given index. A negative index counts the position |>>> L1=[1, 2, 3, 4, 5, 6] | +| | from the right side. |>>> L1[3] | +| | | 4 | +| | | >>> L1[-2] | +| | | 5 | +| | | | +| [ : ] | Range slice Fetches items in the range specified by the two index operands | >>> L1=[1, 2, 3, 4, 5, 6] | +| | separated by : symbol. | >>> L1[1:4] | +| | If the first operand is omitted, the range starts from the zero index. If the| [2, 3, 4] | +| | second operand is omitted, the range goes up to the end of the list. | >>> L1[3:] | +| | | [4, 5, 6] | +| | | >>> L1[:3] | +| | | [1, 2, 3] | +| in | Returns true if an item exists in the given list. | >>> L1=[1, 2, 3, 4, 5, 6] | +| | | >>> 4 in L1 | +| | | True | +| | | >>> 10 in L1 | +| | | False | +| not in | Returns true if an item does not exist in the given list. | >>> L1=[1, 2, 3, 4, 5, 6] | +| | | >>> 5 not in L1 | +| | | False | +| | | >>> 10 not in L1 | +| | | True | + +## Built -in list functions + +|Method |Description | +|---------------|-------------------------------------------------------------| +|all() | Returns True if all list items are true | +|any() | Returns True if any list item is true | +|enumerate() | Takes a list and returns an enumerate object | +|len() | Returns the number of items in the list | +|list() | Converts an iterable (tuple, string, set etc.) to a list | +|max() | Returns the largest item of the list | +|min() | Returns the smallest item of the list | +|sorted() | Returns a sorted list | +|sum() | Sums items of the list | + +``` + +list = [0,1,2,3,4,5,6,5] +print(len(list)) # 8 +print(max(list)) # 6 +print(min(list)) # 0 +print(sum(list)) # 26 +print(sorted(list)) # [0, 1, 2, 3, 4, 5, 5, 6] +print(list("Hockey")) # error "Hokey" string not found +print(any(['','',''])) # False +print(any(['','0','0','',''])) # True +#It returns True if all items in the list have a True value +print(all(['','',''])) # False +print(all(['1','2','1'])) # True + +``` + +## Buit in methods + + +|Method | Description | +|----------------|----------------------------------------------------------------------| +|append() | Adds an item to the end of the list | +|insert() | Inserts an item at a given position | +|extend() | Extends the list by appending all the items from the iterable | +|remove() | Removes first instance of the specified item | +|pop() | Removes the item at the given position in the list | +|clear() | Removes all items from the list | +|copy() | Returns a shallow copy of the list | +|count() | Returns the count of specified item in the list | +|index() | Returns the index of first instance of the specified item | +|reverse() | Reverses the items of the list in place | +|sort() | Sorts the items of the list in place | + +``` +list = [2,8,3,4] +print(list.append(5)) # it adds an item to end of the list +print(list.insert(3,5)) # it insert an item at specified position after element 3 +print(list.remove(2)) # removes the 2 element from the list +print(list.pop(3)) # here 3 is the index value it removes the element in specified index and display values +print(list.clear()) # it empties the list + +list1 = [ 1,3,5,3,8,9] +print(list1.index(3)) # it returns index no search for first matching index no of the items +print(list1.count(3)) # it return count value of 3 in the list of elements +print(list1.sort()) # it sorts the list in ascending order +print(list1.reverse()) # Prints the list in reverse order + +print(list("Hockey")) # ['H', 'o', 'c', 'k', 'e', 'y'] +print(list("Hockey","bold")) +``` \ No newline at end of file diff --git a/Python Tutorial/numbers.md b/Python Tutorial/numbers.md new file mode 100644 index 0000000..c12568d --- /dev/null +++ b/Python Tutorial/numbers.md @@ -0,0 +1,110 @@ +# Python Numbers +source: `{{ page.path }}` + +In Python, there are three distinct numeric types: + +##### Integers +Floating-point numbers +Complex numbers +Python Numbers - Integers, Floats, Complex Numbers +Integers +An integer is a whole number that can be positive or negative. + +# Following numbers are integers +```css +x = 10 +y = -10 +z = 123456789 +``` +In Python 3, there is no limit to how long an integer value can be. It can grow to have as many digits as your computer’s memory space allows. +``` +# Integers have unlimited precision +x = 99999999999999999999999999999999999999999999999999999999999999999999999999999999 +``` +We normally write integers in base 10. However, Python allows us to write integers in Hexadecimal (base 16), Octal (base 8), and Binary (base 2) formats. You can do that by adding one of the following prefixes to the integer. +```sh +Prefix Interpretation Base +‘0b’ or ‘0B’ Binary 2 +‘0o’ or ‘0O’ Octal 8 +‘0x’ or ‘0X’ Hexadecimal 16 +``` +``` +# Integers in binary, octal and hexadecimal formats + +# binary +print(0b10111011) +# Prints 187 + +# octal +print(0o10) +# Prints 8 + +# hex +print(0xFF) +# Prints 255 +In addition, Boolean is a sub-type of integers. + +# Boolean in python +x = True +x = False +``` +#### Floating-Point Numbers +Floating-point number or Float is a positive or negative number with a fractional part. +``` +# Following numbers are floats +x = 10.1 +y = -10.5 +z = 1.123456 +``` +You can append the character e or E followed by a positive or negative integer to specify `scientific notation`. +``` +# Scientific notation +print(42e3) +# Prints 42000.0 + +print(4.2e-3) +# Prints 0.0042 +``` +The maximum value a float can have is approximately 1.8×10308 . Any number greater than that is indicated by the string inf (infinity) +``` +# Maximum value of a float +print(1.79e308) +# Prints 1.79e+308 + +print(1.8e308) +# Prints inf +``` +However, the minimum value a float can have is approximately 5.0×10-324 . Any number, less than that is considered zero. +``` +# Minimum value of a float +print(5e-324) +# Prints 4.94065645841e-324 + +print(5e-325) +# Prints 0.0 +``` +#### Complex Numbers +A complex number is specified as real_part + imaginary_part, where the imaginary_part is written with a j or J. +``` +# Following numbers are complex numbers +x = 2j +y = 3+4j +``` +To extract real and imaginary parts from a complex number x, use x.real and x.imag +``` +x = 3+4j + +# real part +print(x.real) +# Prints 3.0 + +# imaginary part +print(x.imag) +# Prints 4.0 +``` +Table Of Contents +Numeric Types in Python +Integers +Floating-Point Numbers +Complex Numbers + diff --git a/Python Tutorial/operators.md b/Python Tutorial/operators.md new file mode 100644 index 0000000..6ad5e0b --- /dev/null +++ b/Python Tutorial/operators.md @@ -0,0 +1,227 @@ +# operators +source: `{{ page.path }}` + +Operators are used to perform operations on values and variables. The Python operators are classified into seven different categories: + +* Arithmetic operators +* Assignment operators +* Comparison operators +* Logical operators +* Identity operators +* Membership operators +* Bitwise operators +* Arithmetic Operators + +### Arithmetic operators +`Arithmetic operators` are used to perform simple mathematical operations on numeric values (except complex). + +|Operator |Meaning |Example | +|-----------|-----------------|-----------| +|+ |Addition |x + y | +|– |Subtraction |x – y | +|* |Multiplication |x * y | +|/ |Division |x / y | +|% |Modulus |x % y | +|** |Exponentiation |x ** y | +|// |Floor division |x // y | + +``` +Here are some examples: + +x = 6 +y = 2 + +# addition +print(x + y) # 8 + +# subtraction +print(x - y) # 4 + +# multiplication +print(x * y) # 12 + +# division +print(x / y) # 3 + +# modulus +print(x % y) # 0 + +# exponentiation +print(x ** y) # 36 + +# floor division +print(x // y) # 3 + +``` +For additional numeric operations see the [math module](https://docs.python.org/3/library/math.html) + +### Assignment Operators +Assignment operators are used to assign new values to variables. + +|Operator |Meaning |Example |Equivatent to | +|---------------|-------------------------------|----------------|----------------| +|= |Assignment | x = 3 | x = 3 | +|+= | Addition assignment | x += 3 | x = x + 3 | +|-= | Subtraction assignment | x -= 3 | x = x – 3 | +|*= | Multiplication assignment | x *= 3 | x = x * 3 | +|/= | Division assignment | x /= 3 | x = x / 3 | +|%= | Modulus assignment | x %= 3 | x = x % 3 | +|//= | Floor division assignment | x //= 3 | x = x // 3 | +|**= | Exponentiation assignment | x **= 3 | x = x ** 3 | +|&= | Bitwise AND assignment | x &= 3 | x = x & 3 | +|= | Bitwise OR assignment | `x |= 3` | `x = x | 3` | +|^= | Bitwise XOR assignment | x ^= 3 | x = x ^ 3 | +|>>= | Bitwise right shift assignment| x >>= 3 | x = x >> 3 | +|<<= | Bitwise left shift assignment | x <<= 3 | x = x << 3 | + + +### Comparison Operators +Comparison operators are used to compare two values. + +|Operator |Meaning |Example | +|----------|--------------------------|----------| +|== | Equal to | x == y | +|!= | Not equal to | x != y | +|> | Greater than | x > y | +|< | Less than | x < y | +|>= | Greater than or equal to | x >= y | +|<= | Less than or equal to | x <= y | + +Here are some examples: +``` +x = 6 +y = 2 + +# equal to +print(x == y) # False + +# not equal to +print(x != y) # True + +# greater than +print(x > y) # True + +# less than +print(x < y) # False + +# greater than or equal to +print(x >= y) # True + +# less than or equal to +print(x <= y) # False +``` +### Logical Operators +Logical operators are used to join two or more conditions. + +|Operator |Description |Example | +|-------------------|-----------------------------------------------------------|---------------------| +|and |Returns True if both statements are true |x > 0 and y < 0 | +|or |Returns True if one of the statements is true |x > 0 or y < 0 | +|not |Reverse the result, returns False if the result is true |not (x > 0 and y < 0)| + +Here are some examples: +``` +x = 2 +y = -2 + +# and +print(x > 0 and y < 0) # True + +# or +print(x > 0 or y < 0) # True + +# not +print(not(x > 0 and y < 0)) # False +``` +### Identity Operators +Identity operators are used to check if two objects point to the same object, with the same memory location. + +|Operator |Description |Example | +|-------------------|--------------------------------------------------------|-------------| +|is |Returns true if both variables are the same object | x is y | +|is not |Returns true if both variables are not the same object | x is not y| + +Here are some examples: +``` +x = [1, 2, 3] +y = [1, 2, 3] + +# is +print(x is y) # False + +# is not +print(x is not y) # True +``` +### Membership Operators +Membership operators are used to check if a specific item is present in a sequence (such as a string, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). + +|Operator |Description |Example | +|-----------------|------------------------------------------------------|-----------------| +|in |Returns True if a value is present in the sequence | x in y | +|not in |Returns True if a value is not present in the sequence| x not in y | + +Here are some examples: +``` +L = ['red', 'green', 'blue'] + +# in +print('red' in L) # True + +# not in +print('yellow' not in L) # True +``` +### Bitwise Operators +Binary operators are used to perform bit-level operations on (binary) numbers. + +|Operator |Meaning |Example | +|-------------|--------------|---------| +|& | AND | x & y | +|`|` | OR | `x | y` | +|^ | XOR | x ^ y | +|~ | NOT | ~x | +|<< | Left shift | x << 2| +|>> | Right shift | x >> 2| + +Here are some examples: +``` +x = 0b1100 +y = 0b1010 + +# and +print(bin(x & y)) # 0b1000 + +# or +print(bin(x | y)) # 0b1110 + +# xor +print(bin(x ^ y)) # 0b0110 + +# not +print(bin(~x)) # -0b1101 + +# shift 2 bits left +print(bin(x << 2)) # 0b1100 + +# shift 2 bits right +print(bin(x >> 2)) # 0b0011 +``` +### Operator Precedence (Order of Operations) +In Python, every operator is assigned a precedence. Operator Precedence determines which operations are performed before which other operations. + +Operators of highest precedence are performed first. Any operators of equal precedence are performed in left-to-right order. + +|Precedence |Operator | Description | +|----------------------|------------------------|---------------------------------------------------------| +|lowest precedence | or | Boolean OR | +| | and | Boolean AND | +| | not | Boolean NOT | +| | ==, ! =, <, <=, >, >=,| | +| | is, is not | comparisons, identity | +| | `|` | bitwise OR | +| | ^ | bitwise XOR | +| | & | bitwise AND | +| | <<, >> | bitwise shis | +| | +, – | addition, subtraction | +| | *, /, //, % | multiplication, division, floor division, modulo | +| | +x, -x, ~x | unary positive, unary negation, bitwise negation | +|highest precedence | ** | exponentiation | diff --git a/Python Tutorial/sets.md b/Python Tutorial/sets.md new file mode 100644 index 0000000..7faadc9 --- /dev/null +++ b/Python Tutorial/sets.md @@ -0,0 +1,491 @@ +# Sets + +source: `{{ page.path }}` + +A set object contains one or more items, not necessarily of the same type, which are separated by comma and enclosed in curly brackets {}. + +Python set is an unordered collection of unique items. They are commonly used for computing mathematical operations such as union, intersection, difference, and symmetric difference. + +```tip +1. sets is a collection of values/elements. +2. sets is represented in {} brackets. +3. sets allows both Homeogenous & Hetrogenous values/elements. +4. sets are mutable. +5. sets doesn't allow duplicate values/elements. +6. sets doesn't allow indexing and slicing. +7. sets doesnot maintain insertion order +``` +```note +1. Creating a set +2. Accessing a set +3. Deleting a set +4. Methods on sets +5. The Frozenset +6. Updating a set +7. Functions on sets +8. iterating on sets +``` + + +## Create and Accessing a Set +You can create a set by placing a comma-separated sequence of items in curly braces {}. +``` +# A set of strings +S = {'red', 'green', 'blue'} + +# A set of mixed datatypes +S = {1, 'abc', 1.23, (3+4j), True} +Sets don’t allow duplicates. They are automatically removed during the creation of a set. + +S = {'red', 'green', 'blue', 'red'} +print(S) +# Prints {'blue', 'green', 'red'} + +You can also create a set using a type constructor called set(). + +# Set of items in an iterable +S = set('abc') +print(S) +# Prints {'a', 'b', 'c'} + +# Set of successive integers +S = set(range(0, 4)) +print(S) +# Prints {0, 1, 2, 3} + +# Convert list into set +S = set([1, 2, 3]) +print(S) +# Prints {1, 2, 3} + +``` +## Deleting a set + +```python +numbers={3,2,1,4,6,5} + +1. `discard()` : This method takes the item to delete as an argument. + +numbers.discard(3) +print(numbers) +{1, 2, 4, 5, 6} + +As you can see in the resulting set, the item 3 has been removed. + +2. `remove()` + +Like the discard() method, remove() deletes an item from the set. + +numbers.remove(5) +print(numbers) +{1, 2, 4, 6} + +`discard() vs remove()`- + +These two methods may appear the same to you, but there’s actually a difference. If you try deleting an item that doesn’t exist in the set, discard() ignores it, but remove() raises a KeyError. + +numbers.discard(7) +print(numbers) +{1, 2, 4, 6} + +print(numbers.remove(7)) +Traceback (most recent call last): + +File “”, line 1, in +numbers.remove(7) +KeyError: 7 + +3. `pop()` + +Like on a dictionary, you can call the pop() method on a set. However, here, it does not take an argument. Because +a set doesn’t support indexing, there is absolutely no way to pass an index to the pop method. Hence, it pops out an +arbitrary item. Furthermore, it prints out the item that was popped. + +numbers.pop() +1 + +Let’s try popping anot/her element. +numbers.pop() +2 + +Let’s try it on another set as well. +{2,1,3}.pop() +1 + +4. `clear()` + +Like the pop method(), the clear() method for a dictionary can be applied to a Python set as well. It empties the +set in Python. + +print(numbers.clear()) + +``` + +```python +## Updating a set +Python set is mutable. But as we have seen earlier, we can’t use indices to reassign it. + +numbers={3,1,2,4,6,5} +numbers[3] + +File “”, line 1, in +numbers[3] +TypeError: ‘set’ object does not support indexing + +So, we use two methods for this purpose- add() and update(). We have seen the update() +method on tuples, lists, and strings. + +``` + +```javascript +numbers={3,1,2,4,6,5} + +1 . `add()` If you add an existing item in the set, the set remains unaffected. + +print(numbers.add(3.5)) +{1, 2, 3, 4, 5, 6, 3.5} + +2. `update()` This method can add multiple items to the set at once, which it takes as arguments. + +print(numbers.update([7,8],{1,2,9})) +{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9} + +``` + +## Methods on Sets + +|Method |Description | +|-----------------------------------|---------------------------------------------------------------------------| +|union() | Return a new set containing the union of two or more sets | +|update() | Modify this set with the union of this set and other sets | +|intersection() | Returns a new set which is the intersection of two or more sets | +|intersection_update() | Removes the items from this set that are not present in other sets | +|difference() | Returns a new set containing the difference between two or more sets | +|difference_update() | Removes the items from this set that are also included in another set | +|symmetric_difference() | Returns a new set with the symmetric differences of two or more sets | +|symmetric_difference_update() | Modify this set with the symmetric difference of this set and other set | +|isdisjoint() | Determines whether or not two sets have any elements in common | +|issubset() | Determines whether one set is a subset of the other | +|issuperset() | Determines whether one set is a superset of the other | + + +A = {1, 2, 3, 4, 5} +B = {4, 5, 6, 7, 8} + +#### Set Union +Union of A and B is a set of all elements from both sets.You can perform union on two or more sets using union() method or | operator. + +![](./images/union.PNG) + +```python +# by operator +print(A | B) # {1, 2, 3, 4, 5, 6, 7, 8} +# by method +print(A.union(B)) # {1, 2, 3, 4, 5, 6, 7, 8} +``` + +#### Set Intersection +Intersection of A and B is a set of elements that are common in both the sets. +Intersection is performed using & operator. Same can be accomplished using the intersection() method. +![](./images/intersection.PNG) + +```python +# by operator +print(A & B) # {4, 5} +# by method +print(A.intersection(B)) # {4, 5} +``` +#### Set Difference +Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B. Similarly, +B - A is a set of elements in B but not in A. + +Difference is performed using - operator. Same can be accomplished using the difference() method + +![](./images/difference.PNG) + +```python +# by operator +print(A - B) # {1, 2, 3} +# by method +print(A.difference(B)) # {1, 2, 3} +``` +#### Set Symmetric Difference : +Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection). +Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference(). + +![](./images/assymetricdifference.PNG) + +```python +# by operator +print(A ^ B) # {1, 2, 3, 6, 7, 8} +# by method +print(A.symmetric_difference(B)) # {1, 2, 3, 6, 7, 8} + +``` + +#### Set intersection_update + +The intersection of two or more sets is the set of elements which are common to all sets. + +This method returns None (meaning it does not have a return value). It only updates the set calling the intersection_update() method. + +result = A.intersection_update(B, C) +result will be None +A will be equal to the intersection of A, B, and C +B remains unchanged +C remains unchanged +```python +A = {1, 2, 3, 4} +B = {2, 3, 4, 5, 6} +C = {4, 5, 6, 9, 10} + +result = A.intersection_update(B) + +print('result =', result) # result = None +print('A =', A) # A = {2,3,4} +print('B =', B) # B = {2,3,4,5} + +intersection_update() with Two Parameters + +result = C.intersection_update(B, A) + +print('result =', result) # result = None +print('C =', C) # C = {4} +print('B =', B) # B = {2, 3, 4, 5, 6} +print('A =', A) # A = {1, 2, 3, 4} +``` +#### Set difference_update + +If A and B are two sets. The set difference of A and B is a set of elements that exists only in set A but not in B +```python +A.difference_update(B) +Here, A and B are two sets. difference_update() updates set A with the set difference of A-B. + +A = {1, 2, 3, 4} +B = {2, 3, 4, 5, 6} +C = {4, 5, 6, 9, 10} + +result = A.difference_update(B) +print('result =', result) # result = None +print('A =', A) # A = {1} +print('B =', B) # B = {2, 3, 4, 5, 6} + +print(C.difference_update(B, A)) # none +print('A =',A) # A = {1, 2, 3, 4} +print('B =',B) # B = {2, 3, 4, 5, 6} +print('C =',C) # C = {9, 10} +``` + +#### Set symmetric_difference_update +The symmetric difference of two sets A and B is the set of elements that are in either A or B, but not in their intersection. +```python +A = {1, 2, 3, 4} +B = {2, 3, 4, 5, 6} +C = {4, 5, 6, 9, 10} + +result = A.symmetric_difference_update(B) +print('result =', result) # result = None +print('A =', A) # A = {1, 5, 6} +print('B =', B) # B = {2, 3, 4, 5, 6} + +Here, the set A is updated with the symmetric difference of set A and B. However, the set B is unchanged. + +result = C.symmetric_difference_update(B) +print("result = ", result) # result = none +print('A =',A) # A = {1, 2, 3, 4} +print('B =',B) # B = {2, 3, 4, 5, 6} +print('C =',C) # C = {9, 10} + +"Note :" Multiple argument are not possible +``` +#### Set isdisjoint +Two sets are said to be disjoint sets if they have no common elements. +```python +A = {1, 5, 9, 0} +B = {2, 4, -5} +Here A and B are disjoint sets. + +A = {1, 2, 3, 4} +B = {5, 6, 7} +C = {4, 5, 6} + +print('Are A and B disjoint?', A.isdisjoint(B)) # Are A and B disjoint? True +print('Are A and C disjoint?', A.isdisjoint(C)) # Are A and C disjoint? False + +A = {'a', 'b', 'c', 'd'} +B = ['b', 'e', 'f'] +C = '5de4' +D ={1 : 'a', 2 : 'b'} +E ={'a' : 1, 'b' : 2} + +print('Are A and B disjoint?', A.isdisjoint(B)) # Are A and B disjoint? False +print('Are A and C disjoint?', A.isdisjoint(C)) # Are A and C disjoint? False +print('Are A and D disjoint?', A.isdisjoint(D)) # Are A and D disjoint? True +print('Are A and E disjoint?', A.isdisjoint(E)) # Are A and E disjoint? False + +``` +#### Set issubset +Determines whether one set is a subset of the other + +Set A is said to be the subset of set B if all elements of A are in B +```python +Syntax: A.issubset(B) + +A = {1, 2, 3} +B = {1, 2, 3, 4, 5} +C = {1, 2, 4, 5} + +print(A.issubset(B)) # Returns True + +# B is not subset of A +print(B.issubset(A)) # Returns False + +print(A.issubset(C)) # Returns False + +print(C.issubset(B)) # Returns True + +``` +#### Set issuperset +Determines whether one set is a superset of the other + +Set X is said to be the superset of set Y if all elements of Y are in X +```python +A = {1, 2, 3, 4, 5} +B = {1, 2, 3} +C = {1, 2, 3} + +Set A is said to be the subset of set B if all elements of B are in A + +`Syntax: A.issuperset(B)` + +print(A.issuperset(B)) # Returns True +print(B.issuperset(A)) # Returns False +print(C.issuperset(B)) # Returns True + +x = { 2, 4, 6, 8 } +y = { 2, 8 } +f1 = x.issuperset(y) # f1 = True +f2 = y.issuperset(x) # f2 = False + +``` +## Python Frozenset +Python provides another built-in type called a frozenset. Frozenset is just like set, only immutable (unchangeable). + +You can create a frozenset using frozenset() method. It freezes the given sequence and makes it unchangeable. +```python +S = frozenset({'red', 'green', 'blue'}) +print(S) +# Prints frozenset({'green', 'red', 'blue'}) + +As frozensets are unchangeable, you can perform non-modifying operations on them + +# finding size +S = frozenset({'red', 'green', 'blue'}) +print(len(S)) +# Prints 3 + +# performing union +S = frozenset({'red', 'green', 'blue'}) +print(S | {'yellow'}) +# Prints frozenset({'blue', 'green', 'yellow', 'red'}) +``` +methods that attempt to modify a frozenset will raise error. +```python +# removing an item +S = frozenset({'red', 'green', 'blue'}) +S.pop() +# Triggers AttributeError: 'frozenset' object has no attribute 'pop' + +# adding an item +S = frozenset({'red', 'green', 'blue'}) +S.add('yellow') +# Triggers AttributeError: 'frozenset' object has no attribute 'add' + +Unlike sets, frozensets are unchangeable so they can be used as keys to a dictionary. + +For example, D = {frozenset(['dev','mgr']):'Bob'} + +``` +## updating a set +Sets are mutable. However, since they are unordered, indexing has no meaning. + +We cannot access or change an element of a set using indexing or slicing. Set data type does not support it. +We can add a single element using the add() method, and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. + +```python +You can add a single item to a set using add() method. + +S = {'red', 'green', 'blue'} +S.add('yellow') +print(S) +# Prints {'blue', 'green', 'yellow', 'red'} + +You can add multiple items to a set using update() method. + +S = {'red', 'green', 'blue'} +S.update(['yellow', 'orange']) +print(S) +# Prints {'blue', 'orange', 'green', 'yellow', 'red'} + +## example 2 +data = {1, 3} +print(data) # {1, 3} + +data.add(2) +print(data) # {1, 2, 3} + +data.update([2, 5, 3, 4]) +print(data) # {1, 2, 3, 4, 5} + +data.update([7, 5], {1, 6, 8}) +print(data) # {1, 2, 3, 4, 5, 6, 7, 8} +``` +## functions in a set + +Python also has a set of built-in functions that you can use with set objects. + +|Method |Description | +|---------------|------------------------------------------------------------| +|all() | Returns True if all set items are true | +|any() | Returns True if any set item is true | +|enumerate() | Takes a set and returns an enumerate object | +|len() | Returns the number of items in the set | +|set() | Converts an iterable (set, string, set etc.) to a set | +|max() | Returns the largest item of the set | +|min() | Returns the smallest item of the set | +|sorted() | Returns a sorted set | +|sum() | Sums items of the set | + +```python +set = {0,1,2,3,4,5,6,5} + +print(len(set)) # 8 +print(max(set)) # 6 +print(min(set)) # 0 +print(sum(set)) # 26 +print(sorted(set)) # [0, 1, 2, 3, 4, 5, 5, 6] +# print(set("Hockey")) # error "Hockey" string not found +print(any(['','',''])) # False +print(any(['','0','0','',''])) # True +# It returns True if all items in the set have a True value +print(all(['','',''])) # False +print(all(['1','2','1'])) # True +print(enumerate(set)) # +``` +## Iterating on sets + +We can use a for loop to iterate through each item in a tuple +```python +for i in (1,3,2): + print(i) # (1,3,2) + +We can use a for loop to iterate through each item in a tuple. + +# Using a for loop to iterate through a tuple +for name in ('John', 'Kate'): + print("Hello", name) + +Hello John +Hello Kate + +``` diff --git a/Python Tutorial/tuples.md b/Python Tutorial/tuples.md new file mode 100644 index 0000000..69ce228 --- /dev/null +++ b/Python Tutorial/tuples.md @@ -0,0 +1,319 @@ +# Tuples + +source: `{{ page.path }}` + +A tuple is an ordered collection of values. +A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list. + +Tuples are a lot like Tuples: + +* Tuples are ordered – Tuples maintains a left-to-right positional ordering among the items they contain. +* Accessed by index – Items in a tuple can be accessed using an index. +* Tuples can contain any sort of object – It can be numbers, strings, Tuples and even other tuples. + +except: + +* Tuples are immutable – you can’t add, delete, or change items after the tuple is defined. + +```tip +# Python Tuples + +1. Tuples is a collection of values/elements. +2. Tuples is represented in () brackets. +3. Tuples allows both Homeogenous & Hetrogenous values/elements. +4. Tuples are immutable. +5. Tuples allow duplicate values/elements and insertion order. +6. Tuples allow indexing and slicing. +7. Implication of iterations is comparatively Faster +8. Tuples data type is appropriate for accessing the elements. +9. Tuples consume less memory as compared to the list. +10. Tuples does no have must built-in methods + +``` + +```note + +1. Creating a tuple +2. Accessing a tuple +3. Slicing a tuple +4. Deleting a tuple +5. Reassigning a tuple +6. Functions on tuples +7. Methods on tuples +8. operations on tuple +9. iterating a tuple +10. nested tuples + +``` +## Creating a tuple + +A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them. + +A tuple can have any number of items and they may be of different types (integer, float, list, string, + +``` +# Different types of tuples + +# Empty tuple +my_tuple = () +print(my_tuple) +#() + +# Tuple having integers +my_tuple = (1, 2, 3) +print(my_tuple) +# (1, 2, 3) + +# tuple with mixed datatypes +my_tuple = (1, "Hello", 3.4) +print(my_tuple) +# (1, 'Hello', 3.4) + +# nested tuple +my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) +print(my_tuple) +# ('mouse', [8, 4, 6], (1, 2, 3)) + +``` +A tuple can also be created without using parentheses. This is known as tuple packing. +``` +my_tuple = 3, 4.6, "dog" +print(my_tuple) + +# tuple unpacking is also possible +a, b, c = my_tuple + +print(a) # 3 +print(b) # 4.6 +print(c) # dog + +my_tuple = ("hello") +print(type(my_tuple)) # + +# Creating a tuple having one element +my_tuple = ("hello",) +print(type(my_tuple)) # + +# Parentheses is optional +my_tuple = "hello", +print(type(my_tuple)) # +``` +## Slicing a tuple +``` +# Positive index +# Accessing tuple elements using indexing +my_tuple = ('p','e','r','m','i','t') + +print(my_tuple[0]) # 'p' +print(my_tuple[5]) # 't' + +# IndexError: list index out of range +# print(my_tuple[6]) + +# Index must be an integer +# TypeError: list indices must be integers, not float +# my_tuple[2.0] + +# nested tuple +n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) + +# nested index +print(n_tuple[0][3]) # 's' +print(n_tuple[1][1]) # 4 +``` +``` +# Negative Index + +The index of -1 refers to the last item, -2 to the second last item and so on. + +# Negative indexing for accessing tuple elements +my_tuple = ('p', 'e', 'r', 'm', 'i', 't') + +print(my_tuple[-1]) # t + +print(my_tuple[-6]) # p +``` +``` +# Slicing +# Accessing tuple elements using slicing +my_tuple = ('p','r','o','g','r','a','m','i','z') + +# elements 2nd to 4th +print(my_tuple[1:4]) # ('r', 'o', 'g') + +# elements beginning to 2nd +print(my_tuple[:-7]) # ('p', 'r') + +# elements 8th to end +print(my_tuple[7:]) # ('i', 'z') + +# elements beginning to end +print(my_tuple[:]) # ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') + +# elements 1st to 7th with step 2 +print(my_tuple[1:7:2]) # ('r', 'g', 'a') + +# elements till 9th with negative step of -2 +print(my_tuple[8::-2]) # ('z', 'm', 'r', 'o', 'p') + +# start of 9 element and negative index of -7 with step -3 +print(my_tuple[8:-7:-3]) # ('z', 'a') + +``` +## Deleting a tuple + +As we discussed above, a Python tuple is immutable. This also means that you can’t delete just a part of it. You must delete an entire tuple, if you may. +``` +percentages=(99,95,90,89,93,96) +del percentages[4] + +del percentages[4] +TypeError: 'tuple' object doesn't support item deletion +``` + +## Reassigning a tuple + +``` + +my_tuple=(1,2,3,[4,5]) +my_tuple[2]=6 + +File “”, line 1, in + +# Set and print the initial tuple +weekenddays = ("Saturday", "Sunday") # "Saturday", "Sunday + +# Reassign and print +weekenddays = ("Sat", "Sun") # ('Sat', 'Sun') + +Although you can't change tuple items, you can change list items within a tuple. Here's an example of doing that: + +# Assign the tuple +t = (101, 202, ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]) +print(t) # (101, 202, ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']) + +# Update the third list item +t[2][2] = "Humpday" +print(t) # (101, 202, ['Monday', 'Tuesday', 'Humpday', 'Thursday', 'Friday']) + +``` +## Functions on tuples + +Python also has a set of built-in functions that you can use with tuple objects. + +|Method |Description | +|---------------|--------------------------------------------------------------| +|all() | Returns True if all Tuple items are true | +|any() | Returns True if any Tuple item is true | +|enumerate() | Takes a Tuple and returns an enumerate object | +|len() | Returns the number of items in the Tuple | +|Tuple() | Converts an iterable (tuple, string, set etc.) to a Tuple | +|max() | Returns the largest item of the Tuple | +|min() | Returns the smallest item of the Tuple | +|sorted() | Returns a sorted Tuple | +|sum() | Sums items of the Tuple | + +``` +tuple = (0,1,2,3,4,5,6,5) + +print(len(tuple)) # 8 +print(max(tuple)) # 6 +print(min(tuple)) # 0 +print(sum(tuple)) # 26 +print(sorted(tuple)) # [0, 1, 2, 3, 4, 5, 5, 6] +# print(tuple("Hockey")) # error "Hockey" string not found +print(any(['','',''])) # False +print(any(['','0','0','',''])) # True +#It returns True if all items in the tuple have a True value +print(all(['','',''])) # False +print(all(['1','2','1'])) # True +print(enumerate(tuple)) # + +``` + +## Methods in Tuple + +Python has a set of built-in methods that you can call on tuple objects. + +|Method | Description | +|----------------|------------------------------------------------------------------------| +|count() | Returns the count of specified item in the tuple | +|index() | Returns the index of first instance of the specified item | + +``` +tuple = (1,2,3,2,4,5,2) + +print(tuple.index(2)) # 1 +# As you can see, we have 2s at indices 1, 3, and 6. But it returns only the first index. + +print(tuple.count(2)) # 3 +# This method takes one argument and returns the number of times an item appears in the tuple. +``` +## operations + + +|Operator |Description |Example | +|-------------------|------------------------------------------------------------------------------|-------------------------------------| +| + Concatenation |Returns a Tuple containing all the elements of the first and the second Tuple.| >>> L1=[1,2,3] | +| | | >>> L2=[4,5,6] | +| | | >>> L1+L2 | +| | | >>> L2+(7,) | +| | | >>> (4,5,6,7) | +| | | [1, 2, 3, 4, 5, 6] | +| * Repetition |Concatenates multiple copies of the same Tuple. | >>> L1*4 | +| | | [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]| +| | | | +| [] slice |Returns the item at the given index. A negative index counts the position |>>> L1=[1, 2, 3, 4, 5, 6] | +| | from the right side. |>>> L1[3] | +| | | 4 | +| | | >>> L1[-2] | +| | | 5 | +| | | | +| [ : ] | Range slice Fetches items in the range specified by the two index operands | >>> L1=[1, 2, 3, 4, 5, 6] | +| | separated by : symbol. | >>> L1[1:4] | +| | If the first operand is omitted, the range starts from the zero index. If the| [2, 3, 4] | +| | second operand is omitted, the range goes up to the end of the Tuple. | >>> L1[3:] | +| | | [4, 5, 6] | +| | | >>> L1[:3] | +| | | [1, 2, 3] | +| in | Returns true if an item exists in the given Tuple. | >>> L1=[1, 2, 3, 4, 5, 6] | +| | | >>> 4 in L1 | +| | | True | +| | | >>> 10 in L1 | +| | | False | +| not in | Returns true if an item does not exist in the given Tuple. | >>> L1=[1, 2, 3, 4, 5, 6] | +| | | >>> 5 not in L1 | +| | | False | +| | | >>> 10 not in L1 | +| | | True | + + +## iterating Tuples + +We can use a for loop to iterate through each item in a tuple +``` +for i in (1,3,2): + print(i) # (1,3,2) + +We can use a for loop to iterate through each item in a tuple. + +# Using a for loop to iterate through a tuple +for name in ('John', 'Kate'): + print("Hello", name) + +Hello John +Hello Kate + +``` + +## Nested tuples + +``` +tuple=((1,2,3),(4,(5,6))) +Suppose we want to access the item 6. For that, since we use indices, we write the following code. + +tuple([1][1][1]) +6 + +``` + diff --git a/Python Tutorial/variablescope.md b/Python Tutorial/variablescope.md new file mode 100644 index 0000000..b037075 --- /dev/null +++ b/Python Tutorial/variablescope.md @@ -0,0 +1,155 @@ +# Variable Scope +source: `{{ page.path }}` + +Not all variables are accessible from all parts of our program. The part of the program where the variable is accessible is called its “scope” and is determined by where the variable is declared. + +Python has three different variable scopes: + +* Local scope +* Global scope +* Enclosing scope + +## Local Scope +A variable declared within a function has a LOCAL SCOPE. It is accessible from the point at which it is declared until the end of the function, and exists for as long as the function is executing. +``` +def myfunc(): + x = 42 # local scope x + print(x) + +myfunc() # prints 42 +``` +Local variables are removed from memory when the function call exits. Therefore, trying to get the value of the local variable outside the function causes an error. +``` +def myfunc(): + x = 42 # local scope x + +myfunc() +print(x) # Triggers NameError: x does not exist +``` +## Global Scope +A variable declared outside all functions has a GLOBAL SCOPE. It is accessible throughout the file, and also inside any file which imports that file. +``` +x = 42 # global scope x + +def myfunc(): + print(x) # x is 42 inside def + +myfunc() +print(x) # x is 42 outside def +``` +Global variables are often used for flags (boolean variables that indicate whether a condition is true). For example, some programs use a flag named verbose to report more information about an operation. +``` +verbose = True + +def op1(): + if verbose: + print('Running operation 1') +``` +## Modifying Globals Inside a Function +Although you can access global variables inside or outside of a function, you cannot modify it inside a function. + +Here’s an example that tries to reassign a global variable inside a function. +``` +x = 42 # global scope x +def myfunc(): + x = 0 + print(x) # local x is 0 + +myfunc() +print(x) # global x is still 42 +``` +Here, the value of global variable x didn’t change. Because Python created a new local variable named x; which disappears when the function ends, and has no effect on the global variable. + +To access the global variable rather than the local one, you need to explicitly declare x global, using the global keyword. +``` +x = 42 # global scope x +def myfunc(): + global x # declare x global + x = 0 + print(x) # global x is now 0 + +myfunc() +print(x) # x is 0 +``` +The x inside the function now refers to the x outside the function, so changing x inside the function changes the x outside it. + +Here’s another example that tries to update a global variable inside a function. +``` +x = 42 # global scope x + +def myfunc(): + x = x + 1 # raises UnboundLocalError + print(x) + +myfunc() +``` +Here, Python assumes that x is a local variable, which means that you are reading it before defining it. + +The solution, again, is to declare x global. +``` +x = 42 # global scope x + +def myfunc(): + global x + x = x + 1 # global x is now 43 + print(x) + +myfunc() +print(x) # x is 43 +``` +There’s another way to update a global variable from a no-global scope – use globals() function. + +## Enclosing Scope +If a variable is declared in an enclosing function, it is nonlocal to nested functions. It allows you to assign to variables in an outer, but no-global, scope. + +Here’s an example that tries to reassign enclosing (outer) function’s local variable inside a nested (inner) function. +``` +##### enclosing function +def f1(): + x = 42 + # nested function + def f2(): + x = 0 + print(x) # x is 0 + f2() + print(x) # x is still 42 + +f1() +``` +Here, the value of existing variable x didn’t change. Because Python created a new local variable named x that shadows the variable in the outer scope. + +Preventing that behavior is where the nonlocal keyword comes in. +``` +##### enclosing function +def f1(): + x = 42 + # nested function + def f2(): + nonlocal x + x = 0 + print(x) # x is now 0 + f2() + print(x) # x remains 0 + +f1() +``` +The x inside the nested function now refers to the x outside the function, so changing x inside the function changes the x outside it. + +The usage of nonlocal is very similar to that of global, except that the former is primarily used in nested methods. + +## Scoping Rule – LEGB Rule + +image: ![](./images/variable2.PNG) + +When a variable is referenced, Python follows LEGB rule and searches up to four scopes in this order: + +1. first in the local (L) scope, + +2. then in the local scopes of any enclosing (E) functions and lambdas, + +3. then in the global (G) scope, + +4. finally in then the built-in (B) scope + +and stops at the first occurrence. If no match is found, Python raises a NameError exception + diff --git a/README.md b/README.md index f640bd1..57e4bb4 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,5 @@ -# jekyll-rtd-theme -[![](https://github.com/rundocs/jekyll-rtd-theme/workflows/CI/badge.svg)][repository] -[![](https://img.shields.io/gem/v/jekyll-rtd-theme)][rubygem] -[![](https://img.shields.io/gem/dt/jekyll-rtd-theme)][rubygem] -[![](https://data.jsdelivr.com/v1/package/gh/rundocs/jekyll-rtd-theme/badge)][cdn] -[![](https://www.codefactor.io/repository/github/rundocs/jekyll-rtd-theme/badge)][codefactor] -[![](https://img.shields.io/badge/featured%20on-JekyllThemes-red.svg)](https://jekyll-themes.com) -[![](https://badges.gitter.im/rundocs/jekyll-rtd-theme.svg)][gitter] +# Python Notes -GitHub-flavored docs theme for Jekyll, based on sphinx_rtd_theme - -jekyll-rtd-theme - -## Quick start -```yml -remote_theme: rundocs/jekyll-rtd-theme ``` -You can [generate](https://github.com/rundocs/starter-slim/generate) with the same files and folders from [rundocs/starter-slim](https://github.com/rundocs/starter-slim/) - -## Features -- Automatically generate nested sidebar based on directory -- Multi-language supported -- Search engine optimized -- Document search (RegExp supported) -- Support third-party comments -- Google, Baidu, CNZZ Analytics supported -- Just need one file `_config.yml` to configure site - -## Documents -For full documentation, please refer to our website ([rundocs.io](https://rundocs.io/)) for details - -### test -- Latest test document: [rundocs.github.io/jekyll-rtd-theme](https://rundocs.github.io/jekyll-rtd-theme) -- Preview debug branch, please refer to [rundocs.github.io/debug](https://rundocs.github.io/debug) - -## The license -The theme is available as open source under the terms of the MIT License - -[repository]: https://github.com/rundocs/jekyll-rtd-theme -[rubygem]: https://rubygems.org/gems/jekyll-rtd-theme -[cdn]: https://cdn.jsdelivr.net/gh/rundocs/jekyll-rtd-theme/ -[codefactor]: https://www.codefactor.io/repository/github/rundocs/jekyll-rtd-theme -[gitter]: https://gitter.im/rundocs/jekyll-rtd-theme?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +Begineers Python Tutorial +``` \ No newline at end of file diff --git a/_config.yml b/_config.yml index 786ba6b..9c92b26 100644 --- a/_config.yml +++ b/_config.yml @@ -1,4 +1,4 @@ -title: jekyll-rtd-theme +title: Python Tutorial lang: en description: GitHub-flavored docs theme for Jekyll diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..25f29b7 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,11 @@ +site_name: Python Notes +pages: + - Python Tutorial: + - numbers: "numbers.md" + - operators: "operators.md" + - variables: "Variables.md" + - variable scope : "variablescope.md" +docs_dir: chapters +theme: readthedocs +plugins: + - search \ No newline at end of file diff --git a/test/README.md b/test/README.md index ac85902..a38f30e 100644 --- a/test/README.md +++ b/test/README.md @@ -2,7 +2,7 @@ sort: 2 --- -# Test Documentation +# Python Tutorial ``` {% raw %}{% include list.liquid all=true %}{% endraw %} diff --git a/test/markdown.md b/test/markdown.md index 185c1d1..ab95144 100644 --- a/test/markdown.md +++ b/test/markdown.md @@ -1,5 +1,5 @@ --- -sort: 1 +sort: 13 --- # Markdown Elements diff --git a/test_long/folder1/python.md b/test_long/folder1/python.md new file mode 100644 index 0000000..888d552 --- /dev/null +++ b/test_long/folder1/python.md @@ -0,0 +1,3 @@ +# python.md +source: `{{ page.path }}` +This is python introduction \ No newline at end of file