Hello, buddies! There are many ways to write code but generally the first way for many people is very long and it can take you some time. So, here are some tips and tricks to code easily, like a pro! 😎
Use get()
with dictionaries
In Python, dictionaries are collections of data with key-value pairs.
A direct call of any value through its key is one of the most common mistakes in Python. It leads to bad behaviours.
If the key does not exist, the script exits. Endgame! Instead, use the get()
method, it already checks if the key exists:
team = {
"actor": "Christian Bale",
"director": "Christopher Nolan"
}
actress = team.get("bulls", 2000000)
In the above example, I don’t have to check if the key “bulls” exists, and the script does not stop. I can even specify a default value.
Use shorter if statements
Instead of writing:
if myvar == 9 or myvar ==1 or myvar == 7
you can do the following:
if myvar in [9,1,7]
It’s faster, and the code is more readable.
Chained Assignment
If you need multiple variables to reference the same object, you can use the chained assignment:
>>> x = y = z = 2
>>> x, y, z
(2, 2, 2)
Logical and elegant, right?
Check The Memory Usage Of An Object.
To check a object's memory usage, just use this
import sys
x = 1
print(sys.getsizeof(x))
==
is not is
==
does the same as in any other language. It checks if variables have equal values.
is
checks if two operands refer to the same object. Every time you add a variable in your script, it gets a new “slot” in memory. You can check it with the id()
method:
x = "unknown"
y = "elsewhere"
print(id(x))
print(id(y))
You get:
140476677427376
140476698294128
so :
if (x is y):
print("buddy")
else:
print("x is not y")
displays:
x is not y
However, Python has internal optimisations:
x = 111
y = 111
print(id(x))
print(id(y))
if (x is y):
print("buddy")
else:
print("x is not y")
will display something like that:
4457849408
4457849408
buddy
That’s super normal. Python uses the same memory slot for integers less than 256.
Therefore, be extra careful with the is
keyword.
Join Strings
When we want to join strings, normally we do:
name = 'Unity ' + 'buddy'
But from today,
name = 'Unity ' 'buddy'
Just space..
Do not switch between tabs and spaces
This one is especially not allowed in Python 3. If you have only one command line in your code block, using spaces instead of tabs won’t produce any error.
Choose whatever style you want, but keep consistency. Otherwise, you will get errors sooner or later.
If it’s not your code, please consider reformatting it. Most of the time, the IDE has options such as “convert tabs into spaces” for that.
Reserved keywords
All languages have reserved keywords. To get the full list just run the following in the Python interpreter:
help("keywords")
Your IDE is useful here too. Most of the time, if it supports Python (which is likely), reserved keywords have a specific color. Thats why most of python programmers prefer PyCharm.
Use try
/except
/else
and finally
It’s always a better idea to try code and catch errors instead of assuming everything will work as expected.
In Python, you can use exceptions like that:
answer = input()
try:
answer = 111/int(answer)
except:
print("Error, please check your input and use a positive number")
else:
print("The answer is", answer)
finally:
print("That's all folks!")
The keyword “finally” always displays, even if you get exceptions.
So buddies, that's what I found. I hope those tips and concepts will help you write better Python code!