7 useful python tips
Sonika Baniya
Posted on April 9, 2021
1. Multiple variable assignment
You can assign values to multiple variables on one line. You can also assign different data type in single line. A simple use case is shown below:
>>> a,b,c = 4, ‘Sonika’, {‘name’:’Sonika’,’lastname’:’Baniya’}
>>> print(a,b,c)
#output
4 Sonika {‘name’: ‘Sonika’, ‘lastname’: ‘Baniya’}
2. For/while else loop
Yes, for else loop. In so many programming language, else statement is restricted to use only with if statement. In python (only for python version 3.X) , the else block just after for/while is executed only when the loop is NOT terminated by a break statement.
def contains_even_number(l):
for num in l:
if num % 2 == 0:
print ("True,list contains an even number")
break
else:
print ("False, list does not contain an even number")
print ("For List 1:")
contains_even_number([1, 3, 6])
print ("For List 2:")
contains_even_number([1, 7, 3])
#output
For List 1:
True, list contains an even number
For List 2:
False, list does not contain an even number
Similarly, we can use it for while loop.
3. Chain comparison
Chain comparison returns boolean value. Most importantly, it can be chained arbitrarily. Its more self explanatory this way:
5 < 8 < 9 #returns true
6 > 8 < 10 < 15 #returns false
4. floor() and ceil() functions
The floor() method takes a numeric number as an argument and returns the largest integer not greater than the input value. The ceil() method takes a numeric number as an argument and returns the smallest integer not smaller than the input value. A simple example would be
#floor method
import math
print ("math.floor(-23.11) : ", math.floor(-2.22))
print ("math.floor(300.16) : ", math.floor(40.17))
print ("math.floor(300.72) : ", math.floor(40.72))
#output
math.floor(-2.22) : -3.0
math.floor(40.17) : 40.0
math.floor(40.72) : 40.0
#ceil method
import math
# prints the ceil using floor() method
print ("math.ceil(-23.11) : ", math.ceil(-2.22))
print ("math.ceil(300.16) : ", math.ceil(40.17))
print ("math.ceil(300.72) : ", math.ceil(40.72))
#output
math.ceil(-2.22) : -2.0
math.ceil(40.17) : 41.0
math.ceil(40.72) : 41.0
5. Inspect object by dir()
We can inspect the object by simply calling dir() method. Here is the very simple example of using inspect object with dir() method. This saves a lot of time and we don't have to google everytime when we need it.
>>> test = "Sonika"
>>> print(dir(test))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> test = [1,2]
>>> print(dir(test))
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
6. Reverse string with slice:
There are multiple ways to reverse string but this method has to be the best one. There are so many use case of slice as you can see here. To reverse string we do "someString"[::-1] . A simple use case is:
>>>print("Sonika"[::-1])
#output
akinoS
7. N times strings:
Printing n strings is easier than we thought it would be. Its quite self explanatory as following:
print("S" + "o"*2 + "n"*3 + "i"*4 +"k"*5 +"a"*6)
#output
Soonnniiiikkkkkaaaaaa
Hope this helps!
Posted on April 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.