Tips in alphabetical order
- input GUI
- partial
- reduce
This page will contain alphabetical tips for python. You get the code here:
Open the cmd and, if you have installed git, write this:
git clone https://github.com/formazione/python_cheatsheet
Input GUI
from tkinter import simpledialog tk.Tk().withdraw() y = simpledialog.askinteger(title, sentence) return y x = winput("Hello", "How is 5 + 5?") print(x)
Partial
With partial you gave a fixed value to an existing function so that you do not have to rewrite the original
Example
from functools import partial def vat(price, percentage): return price * (100 + percentage) / 100 vat22 = partial(vat, percentage=22) computer_price_plus_vat = vat22(1000) print(computer_price_plus_vat)
out:
1220.0 >>>
Reduce
Reduce, from the module functools, lets you take a function with 2 arguments and use it with an iterable (ex: a list) to do with all the items of the iterable (list) what the function does with the 2 arguments. For example it can sum all the items in the list if the function sums the 2 arguments or can concatenate every string, if the original function concatenates two string.
Example
from functools import reduce def join(a: str, b: str) -> str: return a + " " + b result = reduce(join, ["I", "Love", "Python", "so", "much"]) print(result)
out:
I Love Python so much >>>