Everyone Should Know These 8 Python Functions

Nibesh Khadka
4 min readApr 19, 2021

--

Be Happy With Python Built-in’s

Python programming language comes with many builtin methods that can be life saviors for coders. Today I am writing this blog on some of those promptly used methods

1. Help

Help method provides information of methods that that is passed through it. The porper syntax to use help is : help(name_of_method).

help(print)<<Output>>Help on built-in function print in module builtins:print(...)print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default.Optional keyword arguments:file:  a file-like object (stream); defaults to the current sys.stdout.sep:   string inserted between values, default a space.end:   string appended after the last value, default a newline.flush: whether to forcibly flush the stream.(END)

In above code block we tried to help to know about method. When you call help method, it starts an interactive help session in command prompt. You can move up and down with up and down arrows respectively, and when you’re done you can take exit by press “q” key.

2. Print

It prints messages on the screen.

Syntax: print(object(s), sep=separator, end=end, file=file, flush=flush),

where object is what you want to print. Don’t worry about other parameters they are optional and very rarely used.

print("My name is {}. I am {} years old.".format("Nibesh Khadka",27))<<Output>>My name is Nibesh Khadka. I am 27 years old.

We have printed string using print method. The “”.format(),is one of the methods to write strings.

3. Len

Len method takes one input and can output’s the length of the provided input. The type of input should be a sequence or collections for instance strings, list, set, dictionaries, tuples but not integers.

Syntax: len(object) , where object is input.

len("dafadsf")<<Output>>7len({'afd':'ad'})<<Output>>1

To find out more you can always use help or visit online documentations.

4. Range

Range is used to get a sequence of numbers with in provided limits. Mostly its used with list or for methods to get a desired sequence of numbers.

Syntax: range(start, stop, step)

Where start is starting number, stop is the end of sequence but exclusive i.e end number is not included. Lastly step is optional parameter which means how many gaps or steps to take between each number.

## List Comprehension and Range[i for i in range(1, 300, 30)]<<Output>>[1, 31, 61, 91, 121, 151, 181, 211, 241, 271]## List Comprehension and Range[i for i in range(0, 30)]<<Output>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]## For Loops and Range>>> for i in range(1,5):...     print("Number",i)...Number 1Number 2Number 3Number 4

As you saw in first example, when step is provides there 30 numbers gap between each number. Also the last number is not included. Hence, be careful to provide higher number if you want to include end number.

5. Min and Max

Min and Max stands for minimum and maximum respectively. They take a sequence of numbers like lists or multiple values, compare them and return minimum or maximum values.

Syntax:

min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument.

# With arguments
min(1,3,5,6)
<<Output>>
1

# With sequences
min([1,3,5,6])
<<Output>>
1


## For Dictionaries
dict_1 ={'one':1,'two':2}

#get key with max value
max(dict_1, key=lambda k:dict_1[k])
'two'

6. Sorted

Sorted is a very helpful function to sort values in ascending or descending order.

Syntax: sorted(iterable, /, *, key=None, reverse=False)

Where, iterable is list , A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

list_1 =[1,35,12,31,315214,152543]#In ascending ordersorted(list_1,reverse=False)<<Output>>[1, 12, 31, 35, 152543, 315214]# In descending ordersorted(list_1,reverse=True)<<Output>>[315214, 152543, 35, 31, 12, 1]

7. Round, Abs

There are methods related to numbers. Round method is used to round of the decimal numbers to a desired decimal places. Abs value is gain absolute(positive) value of a number.

Syntax:

round(number, ndigits=None)
Round a number to a given precision in decimal digits.

ndigits is number of digits to round of to, default is None means no all decimals are removed

abs(x, /)
Return the absolute value of the argument.

round(23.253,3)<<Output>>23.253round(23.253,2)<<Output>>23.25round(23.253,1)<<Output>>23.3
abs(-2.34)<<Output>>2.34

8. Dir

Dir Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. With names I mean everything like related methods, functions, variables.

Syntax.

dir([object])

Check out the difference.

# First time without declaring functiondir()['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'dict_1', 'i', 'list_1', 'x_1', 'x_2']# Create a function>>> def add_numbers():...     num1=12...     num2 = 13...     return num1+num2...# Now print dir again.>>> dir()['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'add_numbers', 'dict_1', 'i', 'list_1', 'x_1', 'x_2']

As you can see the it list everything within the scope/range. And on second time the new function add_numbers is also among the list.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Nibesh Khadka
Nibesh Khadka

Written by Nibesh Khadka

Software Developer, Content Creator and Wannabe Entrepreneur

No responses yet

Write a response