most of the time we come accross some codes which are similar and sometimes too long. won't it be nice if we have some shortcuts for writing our code? here are some easy shortcus use in python.
1. Shortcut operators: Operations like sum=sum+1 occur so often that there is a shortcuts
for them. Here are a couple of examples:
addition and subtraction Shortcuts
count=count+1 # we will rewrite it as count+=1 decreasing=decreasing-2 # is the same thing as decreasing-=5
multiplication and Division
product=product*2 #can be shorthand as product*=2 divide=divide/4 # is change to divide/=4
Modulus,Floor and Power:
remainder=remainder%5 # this is similar to remainder%=5 floor=floor//3 #its shortcuts form is floor//=3 Power=Power**2 #its shorthand form is power**=2
so each pairs of the statement above means the same thing and the most amazing part is that the shortcuts above work for almost all languages.
2. An assignment shortcut
Let assume we have the following codes.
a = 2 b = 2 c = 2
A nice shortcut is :
a = b = c = 2
3. List assignment shortcut
Say we have a list L with three elements in it, and we want to assign those elements to variable
names. We could do the following:
a = L b = L c = L
Instead, we can make it short to:
a,b,c = L
Similarly, we can assign three variables at a time like below:
a,b,c = 1,2,3
And, as we have seen once before in my post swapping , we can swap variables using this kind of assignment.
a,b,c = a,b,c
4. conditional shortcuts
Here are some examples:
let say we have the following stamentement
if a==1 and b==1 and c==1: # first one if 0<x and x<6:# second one
the shortcuts of the above statement is below:
if a==b==c==0: #this is the first short form if 0<x<6:# this is the second short form
if 1<x and x<y and y<10: #same as if 1<x<y<10:
hope you enjoy this!like and comment below.