Bytes

Popular Functions in Python

Module - 6 Functions in Python
Popular Functions in Python

Overview:

Python functions are pieces of code that can be reused and passed around. They are utilized to break down an expansive program into littler chunks, making it less demanding to debug and keep up. Functions are declared using the def keyword and can take optional parameters. They can also return values utilizing the return keyword. Functions can be used to perform assignments such as calculations, string manipulations, and file operations. Also, functions can be used to make classes and modules.

What are some popular functions in Python

  1. print: prints a specified message to the screen
print("Hello World")  # Output: Hello World

Hello world message is printed here

  1. type: 1. returns the type of an object
 x = 10
print(type(x))  # Output: <class 'int'>

x=10 is taken, and input and its type int is returned

  1. input: reads a line of input from the user
x = input("Enter a number: ")  # Output: Enter a number:

The number is inputted here

  1. abs: returns the absolute value of a number
print(abs(-90))  # Output: 90

An absolute value of -90 is returned, which is 90

  1. pow: returns the result of a number raised to a specified power
pow(2, 3)  # Output: 8

The power of 2^3, which is 8, is returned

  1. sorted: returns a sorted list of elements
sorted([2, 3, 1, 4, 5])  # Output: [1, 2, 3, 4, 5]

The list of values is sorted

  1. max: returns the largest element in an iterable object
max(2, 10, -5)  # Output: 10

The maximum of the list, which is 10, is returned

  1. round: rounds a number to a specified number of decimal places
round(3.14159)  # Output: 3

It rounds off the value and returns 3

  1. id:  returns the identity of an object
id(10)  # Output: 140735457659248

The identity of 10 is returned

  1. ord: returns the Unicode code point for a character
ord('a')  # Output: 97

Ascii code of a is returned

  1. len:  returns the length of an object
len('Hello World')  # Output: 11

The length of the message is displayed

  1. sum: returns the sum of the items of an iterable object
sum([2, 4, 6, 8])  # Output: 20

The sum of the list is returned

  1. help: prints information about a specified object
help()  # Output: help>

For any help or information, this is used

  1. Lambda: creates an anonymous function
Lambda x: x + 1  # Output: <function <lambda> at 0x0000020F2F35EAE8>

The lambda function takes in a single argument (x) and adds 1 to it.

  1. Map: applies a function to all the items of an iterable object
Map(lambda x: x + 1, [1, 2, 3, 4])  # Output: <map object at 0x0000020F2F35E9E8>

The map function takes in a function (in this case the lambda function) and an iterable (in this case a list of numbers [1,2,3,4]) and applies the function to each element of the iterable and returns a map object.

  1. Filter: creates a list of elements for which a function returns true
Filter(lambda x: x > 2, [1, 2, 3, 4])  # Output: <filter object at 0x

The map function takes in a function (in this case, the lambda function) and an iterable (in this case, a list of numbers [1,2,3,4]) and applies the function to each element of the iterable, and returns a map object.

  1. Enumerate: adds a counter to an iterable object.
my_list = ["apple", "banana", "cherry"]
for index, item in enumerate(my_list):
  print(index, item)

# Output:
# 0 apple
# 1 banana
# 2 cherry

The enumerate function takes an iterable (in this case, a list of strings ["apple", "banana", "cherry"]). It returns an enumerate object, which contains the index and value of each iterable element.

  1. Eval: evaluates a string as a Python expression
x = 1
y = 2
eval('x + y')  # Output: 3

The eval function takes a string as input and evaluates it, returning the result.

  1. Range: generates a sequence of numbers within a specified range
list(range(1, 10))  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The range function takes in two numbers (in this case, 1 and 10) and returns a range object containing the numbers between the two numbers (in this case, 1, 2, 3, 4, 5, 6, 7, 8, 9).

20. Groupby: is used to split the data into groups based on some criteria.

# Grouping data based on 'Team' 
import pandas as pd 

# Initialize dataframe 
df = pd.DataFrame({'Team': ['A','B','C','A','B','C','A','B','C'], 
                   'Score': [1,2,3,4,5,6,7,8,9]}) 

# Group data based on 'Team'
df_grouped = df.groupby('Team')

# Print the grouped data
print(df_grouped)

This code uses the groupby() function from the pandas library to group the data in the dataframe df based on the 'Team' column. The result of the groupby() function is stored in the df_grouped dataframe. Finally, the grouped data is printed to the console.

Conclusion

We found how these built-in functions can perform different assignments, from fundamental arithmetic to complex database operations. We learned how to create our functions and call them in her code. Along the way, we tested distinctive methods to improve the code, such as looping and nesting. As we continued to investigate and practice, we begun to gain a more profound understanding of Python and its capabilities.

Key takeaways

  1. Built-in functions are pre-defined, standardized functions available in most programming languages.
  2. They can save time and effort when coding, as they are already written and tested.
  3. Built-in functions are often optimized for performance, which can improve the speed of your code.
  4. Built-in functions can perform complex operations in a single line of code.
  5. Built-in functions are often well-documented and easy to use, making them ideal for beginners.
  6. Built-in functions can be used to manipulate data, perform calculations, and more.
  7. It is important to understand the arguments and parameters of a built-in function before using it.

Quiz

  1. What is the purpose of a function in Python?
    1.  To provide a way to structure programs into logical units
    2. To execute a block of code multiple times
    3. To create a variable
    4. To perform mathematical operations

Answer:a. To provide a way to structure programs into logical units

  1. What is the purpose of the sorted() function in Python? 
    1. To sort a list of elements 
    2. To convert a list to a dictionary  
    3. To find the length of a string 
    4. To create a new list

Answer:a. To sort a list of elements

  1. What is the purpose of the len() function in Python?  
    1. To sort a list of elements 
    2. To convert a list to a dictionary 
    3. To find the length of a string 
    4. To create a new list

Answer:c. To find the length of a string

  1. What is the purpose of the dict() function in Python? 
    1. To sort a list of elements
    2. To convert a list to a dictionary 
    3. To find the length of a string  
    4. To create a new list

Answer:b. To convert a list to a dictionary

Online Python Compiler (Editor / Interpreter)
Open Compiler
Recommended Courses
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Masters Program in Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's best Masters program in Data Science and Artificial Intelligence. Get the best jobs in top tech companies. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter
Explore Courses

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

view Allview-all

Top Articles toRead

view Allview-all
AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter