Python Tricks
Cool python hacks!
- More readability
- Use context manager to manage file handling
- Using the enumerate function
- Using the ZIP function
- Quick note about unpacking values
- Accepting passwords
Adding underscores to numbers
num1 = 10000000000
num2 = 90000000
sum1 = num1 + num2
print(sum1)
num1 = 10_000_000_000
num2 = 90_000_000
sum2 = num1 + num2
print(sum2)
sum1 == sum2
print(f'{sum2:,}')
Note that the type of the output gets changed, obviously
print(type(f'{sum2:,}'))
f = open('myfile.csv', 'r')
file_contents = f.read()
f.close()
Try a context manager instead. This way you don't have to remember to close the file handle
with open('myfile.csv', 'r') as f:
file_contents = f.read()
The above concept of context managers is applicable not only to files, but to any other resource you might use such as threads.
words = ['A', 'and', 'B', 'play', 'God of war', 'together']
index = 1
for word in words:
print(index, word)
index += 1
There's a better way to do this
for ix, word in enumerate(words, start=1):
print(ix, word)
persons = ['Bruce Wayne', 'Clark Kent', 'Peter Parker']
heroes = ['Batman', 'Superman', 'Spiderman']
universes = ['DC', 'DC', 'Marvel']
for person, hero, universe in zip(persons, heroes, universes):
print(f'{hero} is actually {person} created by {universe}')
a,b,c = (1,2,3,4,5)
a,b,c,d,e = (1,2,3)
Unpacking fewer variables
a, b, *c = (1,2,3,4,5)
print(f'a = {a}')
print(f'b = {b}')
print(f'c = {c}')
from getpass import getpass
username = input("Username: ")
password = getpass("Password: ")
print("Logging in...")
That's it for now!