GeezerVison is showing github.com — Basic python codes · DevOpsStuff/Programming-Language@32aa0e5
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +*.pyc | | 2 | +*.vscode |
Collapse file Copy file name to clipboard +28Lines changed: 28 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +#!/usr/bin/env python3 | | 2 | + | | 3 | +""" | | 4 | +The use of Assertion is to let developers find the likely root cause | | 5 | +of a bug more quickly. It should be never raised unless we have bug in your program | | 6 | +""" | | 7 | + | | 8 | +def apply_discount(product, discount): | | 9 | + price = int(product['price'] * (1.0 - discount)) | | 10 | + assert 0 <= price <= product['price'] | | 11 | + return price | | 12 | + | | 13 | +# Now try applying this fucntion | | 14 | +# Given the shoe price as 1500 rupees | | 15 | +shoes = {'name': 'Ambur Shoes', 'price': 1500} | | 16 | + | | 17 | +# Now at 25% we should expect, 1125 Rupees | | 18 | +print(apply_discount(shoes,0.25)) | | 19 | + | | 20 | +# Now apply invalid discounts. like 200% it should throw AssertError | | 21 | +print(apply_discount(shoes,2.0)) | | 22 | + | | 23 | +# Two pitfalls of using Assert Statements | | 24 | + | | 25 | +# 1) Never Use Assestion for Data Validatation | | 26 | +# 2) Asserts thats Never Fail | | 27 | +# eg) assert(1 == 2, 'This should Fail') | | 28 | + |
Collapse file Copy file name to clipboard +65Lines changed: 65 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +#!/usr/bin/env python3 | | 2 | + | | 3 | +# with statement | | 4 | +""" | | 5 | +with open('hello.txt','w') as f: | | 6 | + f.write('hello,world!') | | 7 | +""" | | 8 | +# Nothing much right, Opening files in a `with` statement is recomemded | | 9 | +# Because whenever you open files, you are supposed to close the file. | | 10 | + | | 11 | +""" | | 12 | +This is what above code does using with statement | | 13 | +f = open('hello.txt','w') | | 14 | +try: | | 15 | + f.write('hello,world') | | 16 | +finally: | | 17 | + f.close() | | 18 | +""" | | 19 | +""" | | 20 | +What is Context Managers? | | 21 | +
| | 22 | +It is a simple "protocol" that your objects needs to follow in order to | | 23 | +support with statement. All you need to do is add `__enter__` and `__exit__` methods to an object if you | | 24 | +want it to function as a context Manager. | | 25 | +
| | 26 | +Take the below Example, | | 27 | +
| | 28 | +Class MyOpen: | | 29 | + def __init__(self, name): | | 30 | + self.name = name | | 31 | +
| | 32 | + def __enter__(self): | | 33 | + self.file = open(self.name,'w') | | 34 | + return self.file | | 35 | + | | 36 | + def __exit__(self,exc_type,exc_val,exc_tb): | | 37 | + if self.file: | | 38 | + self.file.close() | | 39 | +
| | 40 | +with MyOpen('hello.txt') as f: | | 41 | + f.write('helloworld') | | 42 | +
| | 43 | +""" | | 44 | + | | 45 | +# The above approach is more of a class based approach | | 46 | +# lets use another approch using `contextlib` | | 47 | + | | 48 | +""" | | 49 | +from contextlib import contextmanger | | 50 | +
| | 51 | +@contextmanager | | 52 | +def MyOpen(name): | | 53 | + try: | | 54 | + f = open(name, 'w') | | 55 | + yield f | | 56 | + finally: | | 57 | + f.close() | | 58 | +
| | 59 | +with MyOpen('hello.txt') as f: | | 60 | + f.write('hello world') | | 61 | +""" | | 62 | + | | 63 | + | | 64 | + | | 65 | + |
Collapse file Copy file name to clipboard +22Lines changed: 22 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +""" | | 2 | +1) Old-Style | | 3 | +
| | 4 | +>>> name = "Tesla" | | 5 | +>>> 'hello, %s' % name | | 6 | +'hello, Tesla' | | 7 | +
| | 8 | +2) New Style | | 9 | +
| | 10 | +>>> 'hello, {}'.format(name) | | 11 | +'hello, Tesla' | | 12 | +>>> | | 13 | +
| | 14 | +3) f'strings (python3.6+) | | 15 | +4) Template String | | 16 | +
| | 17 | +>>> from string import Template | | 18 | +>>> t = Template('Hey, $name') | | 19 | +>>> t.substitute(name=name) | | 20 | +'Hey, Tesla' | | 21 | +>>> | | 22 | +""" |
Collapse file Copy file name to clipboard +106Lines changed: 106 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +""" | | 2 | +UnderScores: | | 3 | +
| | 4 | +1) Single UNderscores: _var | | 5 | +
| | 6 | +It is more of a indication to the Python Programmers, a kind of private variable | | 7 | +But doesn't enforce it. | | 8 | +
| | 9 | +class Test: | | 10 | + def __init__(slef): | | 11 | + self.foo = 11 | | 12 | + self._bar = 23 | | 13 | +
| | 14 | +t = Test() | | 15 | +print(t.foo) | | 16 | +print(t._bar) | | 17 | +
| | 18 | +# my_module | | 19 | +def external(): | | 20 | + return 23 | | 21 | +
| | 22 | +def _internal(): | | 23 | + pass | | 24 | +
| | 25 | +from my_module import * | | 26 | +external() | | 27 | +prints 23 | | 28 | +_internal() | | 29 | +NameError Not defined | | 30 | +
| | 31 | +Note: WildCard imports should be avoided | | 32 | +
| | 33 | +2) Single Trailing Underscore: "var_" | | 34 | +
| | 35 | +Sometimes for the NameConvention we use the words like, | | 36 | +len,class,string | | 37 | +
| | 38 | +use trialing characters | | 39 | +
| | 40 | +len_ = len(a) | | 41 | +
| | 42 | +def make_object(name,class): #Invalid Syntax | | 43 | +
| | 44 | +def make_object(name,class_): # Valid Syntax | | 45 | +
| | 46 | +3) Double Leading Underscore: "__var" | | 47 | +
| | 48 | +class Test: | | 49 | + def __init__(self): | | 50 | + self.foo = 1 | | 51 | + self._bar = 2 | | 52 | + self.__bax = 3 | | 53 | +
| | 54 | +>>> t = Test() | | 55 | +>>> dir(t) | | 56 | +['_Test__bax', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bar', 'foo'] | | 57 | +>>> | | 58 | +
| | 59 | +Hope You have noticed something from the output. Interstingly you might seen this two variables | | 60 | +self.foo = 1 | | 61 | +self._bar = 2 | | 62 | +but, also this, '_Test__bax' -> is called 'Name Managling' | | 63 | +
| | 64 | +class ExtentedTest(Test): | | 65 | + def __init__(self): | | 66 | + super().__init__() | | 67 | + self.foo = 'overridden' | | 68 | + self._bar = 'overridden' | | 69 | + self.__bax = 'overridden' | | 70 | +
| | 71 | +>>> t2 = ExtentedTest() | | 72 | +>>> t2.foo | | 73 | +'overridden' | | 74 | +>>> t2._bar | | 75 | +'overridden' | | 76 | +>>> t2.__baz | | 77 | +Traceback (most recent call last): | | 78 | + File "<stdin>", line 1, in <module> | | 79 | +AttributeError: 'ExtentedTest' object has no attribute '__baz' | | 80 | +
| | 81 | +This is called Name Managling | | 82 | +
| | 83 | +>>> dir(t2) | | 84 | +['_ExtentedTest__bax', '_Test__bax', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bar', 'foo'] | | 85 | +
| | 86 | +>>> t2._ExtentedTest__bax | | 87 | +'overridden' | | 88 | +>>> t2._Test__bax | | 89 | +3 | | 90 | +
| | 91 | +Dunders | | 92 | +
| | 93 | +Anything thats starts and ends with __ | | 94 | +like, __init__ | | 95 | +
| | 96 | +4) single Underscore: _ | | 97 | +
| | 98 | +means "Dont Care" | | 99 | +
| | 100 | +>>> a = [random.randint(1,10)] * 10 | | 101 | +>>> a | | 102 | +[2, 2, 2, 2, 2, 2, 2, 2, 2, 2] | | 103 | +for _,v in enumerate(a): | | 104 | + print(v) | | 105 | +
| | 106 | +""" |
Collapse file Copy file name to clipboard +6Lines changed: 6 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +{ | | 2 | + "python.linting.pylintEnabled": false, | | 3 | + "python.linting.enabled": false, | | 4 | + "python.linting.flake8Enabled": true, | | 5 | + "python.pythonPath": "/usr/bin/python" | | 6 | +} |
Collapse file Copy file name to clipboard +7Lines changed: 7 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +def get_final_line(filename): | | 2 | + final_line = '' | | 3 | + for current_line in open(filename): | | 4 | + final_line = current_line | | 5 | + return final_line | | 6 | + | | 7 | +print(get_final_line('/etc/hosts')) |
Collapse file Copy file name to clipboard +35Lines changed: 35 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +#!/usr/bin/env python | | 2 | + | | 3 | +""" | | 4 | +Number guessing Game | | 5 | +""" | | 6 | + | | 7 | +import random | | 8 | + | | 9 | +def guessing_game(): | | 10 | + """ | | 11 | + Generate a random number between 1 to 100, and ask for the input till | | 12 | + you guess the number | | 13 | + """ | | 14 | + answer = random.randint(1,100) | | 15 | + noOfGuess = random.randint(1,5) | | 16 | + | | 17 | + while noOfGuess: | | 18 | + user_guess = int(input('Whats your guess? ')) | | 19 | + | | 20 | + if user_guess == answer: | | 21 | + print(f'Right! your guess is correct') | | 22 | + break | | 23 | + elif user_guess < answer: | | 24 | + print(f'You guess is too low') | | 25 | + else: | | 26 | + print(f'You guess is too high') | | 27 | + | | 28 | + noOfGuess = noOfGuess - 1 | | 29 | + else: | | 30 | + print(f'no of guess is over') | | 31 | + | | 32 | + | | 33 | + | | 34 | +guessing_game() | | 35 | + |
Collapse file Copy file name to clipboard +10Lines changed: 10 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +#!/usr/bin/env python | | 2 | + | | 3 | +def hex_output(): | | 4 | + decnum = 0 | | 5 | + hexnum = input('Enter a hex number to convert: ') | | 6 | + for power, digit in enumerate(reversed(hexnum)): | | 7 | + decnum += int(digit,16) + (16 ** power) | | 8 | + print(decnum) | | 9 | + | | 10 | +hex_output() |
Collapse file Copy file name to clipboard +25Lines changed: 25 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +#!/usr/bin/env python | | 2 | + | | 3 | +def run_timing(): | | 4 | + """ | | 5 | + Asks the user repeatedly for numberic input. Prints the average time and number of runs | | 6 | + """ | | 7 | + | | 8 | + num_of_runs = 0 | | 9 | + total_time = 0 | | 10 | + | | 11 | + while True: | | 12 | + one_run = input('Enter 10 Km run time: ') | | 13 | + | | 14 | + if not one_run: | | 15 | + break | | 16 | + | | 17 | + num_of_runs += 1 | | 18 | + total_time += float(one_run) | | 19 | + | | 20 | + average_time = total_time / num_of_runs | | 21 | + | | 22 | + print(f'Average of {average_time}, over {num_of_runs} runs') | | 23 | + | | 24 | +run_timing() | | 25 | + |
|