DEV Community

loading...

Shorcuts in python

oladejo abdullahi
I am web developer and data scientist
Updated on ・2 min read

How to use Shortcuts

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

multiplication and Division

product=product*2 #can be shorthand as
product*=2
divide=divide/4 # is change to
divide/=4
Enter fullscreen mode Exit fullscreen mode

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

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

A nice shortcut is :

a = b = c = 2
Enter fullscreen mode Exit fullscreen mode

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[0]
b = L[1]
c = L[2]
Enter fullscreen mode Exit fullscreen mode

Instead, we can make it short to:

a,b,c = L
Enter fullscreen mode Exit fullscreen mode

Similarly, we can assign three variables at a time like below:

a,b,c = 1,2,3
Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

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

another one

if 1<x and x<y and y<10: #same as
if 1<x<y<10:
Enter fullscreen mode Exit fullscreen mode

hope you enjoy this!like and comment below.

Discussion (0)

Forem Open with the Forem app