Python Newbie 3

1. The walrus operator Walrus operator is the coolest feature that was added in the Python 3.8 update python codes. start = input("Do you want to start(y/n)?") print(start == "y") # double parentheses here # using parentheses with the walrus operator is encouraged print((start := input("Do you want to start(y/n)?")) == "y") # With parentheses if (sum := 10 + 5) > 10: print(sum) #return 15 # Without parentheses if sum := 10 + 5 > 10: print(sum) #return True a = [1, 2, 3, 4] if (n := len(a)) > 3: print(f"List is too long ({n} elements, expected <= 3)") 2....

Python Newbie 2

To make your codes more beautiful and more readable, try to use below checker to scan your python codes. 1. mypy Mypy is an optional static type checker for Python. from typing import Union, Any, List, Optional, NoReturn, Dict, Tuple, Annotated, AnyStr def fib(n: int) -> Iterator[int]: a, b = 0, 1 while a < n: yield a a, b = b, a + b Repo here. Mypy supports reading configuration settings from a file....

Python Newbie 1

1. functions def name_of_function(): ''' python function name should be snake chasing ''' Arbitary arguments *args **kwargs def func(*args): ''' will get a tuple ''' print(args) def func(**kwargs): ''' will get a dictionary ''' if 'fruit' in kwargs: print(f"choice is {kwargs['fruit']}") func(fruit='apple',veggie='lettuce') 2. yield What does the “yield” keyword do? the-python-yield-keyword-explained

April 24, 2021 51 words 1 min

Python Newbie 0

1. How to save lines to list in only one line def read_config(config): with open(config, 'r') as f: return list(map(lambda item: item.strip('\n'), f.readlines())) 2. How to get value from nested dictionary def safe_get(dct, keys): for key in keys.split("."): try: dct = dct[key] except: return None return dct 3. How to rewrite the file import json with open (filename, 'r+') as json_file: ... json_file.seek(0,0) json.dump(data, json_file) 4. How to eliminate duplicate values in list sth = list(set(sth)) 5....

April 6, 2021 277 words 2 min