DEV Community

loading...
Cover image for 7 useful python tips

7 useful python tips

sonikabaniya profile image Sonika Baniya Updated on ・3 min read

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}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Discussion (15)

pic
Editor guide
Collapse
vestemir profile image
bkrzys

Operation done in 1st point isn't technically multiple variable assignment but tuple unpacking. What you have on the right side is an implicit tuple created due to the commas and then you unpack its values to the variables on the left side of the assignment.

Collapse
sonikabaniya profile image
Sonika Baniya Author

Yeah but this method is named as ' multiple variable assignment ', no?

Collapse
vestemir profile image
bkrzys

Tuple unpacking is more specific. 'multiple variable assignment' would be also `a = b = c = None', wouldn't it?
Here, a comma on the right side of the assignment represents implicit tuple creation, which is first executed and then unpacked.

Collapse
paddy3118 profile image
Paddy3118

floor, ceil but no trunc?!

# FUNCTIONS THAT GENERATE INTEGERS FROM FLOATS IN DIFFERENT WAYS.
ceil
  Return the ceiling of x as an Integral.

  This is the smallest integer >= x.

floor
  Return the floor of x as an Integral.

  This is the largest integer <= x.

trunc
  Truncates the Real x to the nearest Integral toward 0.

  Uses the __trunc__ magic method.

 ceil( 1.2) ==  2; floor( 1.2) ==  1; trunc( 1.2) ==  1
 ceil( 0.2) ==  1; floor( 0.2) ==  0; trunc( 0.2) ==  0
 ceil(   0) ==  0; floor(   0) ==  0; trunc(   0) ==  0
 ceil(-0.2) ==  0; floor(-0.2) == -1; trunc(-0.2) ==  0
 ceil(-1.2) == -1; floor(-1.2) == -2; trunc(-1.2) == -1

trunc acts like floor for n >=0 and like ceil for n < 0
Enter fullscreen mode Exit fullscreen mode
Collapse
sonikabaniya profile image
Sonika Baniya Author

seemed to have missed it out, will be mindful about this from now onwards :))

Collapse
suecarmol profile image
Susana Cárdenas Molinar

That dir() tip is super useful! Thank you for this :)

Collapse
sonikabaniya profile image
Sonika Baniya Author

Very happy to know it helped :))

Collapse
anishde12020 profile image
Anish De

Nice!!! Really helpful tips!

Collapse
sonikabaniya profile image
Sonika Baniya Author

thank you Anish

Collapse
0trenixjetix profile image
0trenixjetix

Your prints don't have parenthesis in the 4th tip

Collapse
sonikabaniya profile image
Sonika Baniya Author

Thank you for pointing this out, i fixed it now :))

Collapse
wireless90 profile image
wireless90

For/while else loop tip is cool

Collapse
sonikabaniya profile image
Collapse
manibibek profile image
Bibek Mani Acharya

Good one Sonika

Collapse
sonikabaniya profile image