A Comprehensive Guide to Built-in Functions in Python

A Comprehensive Guide to Built-in Functions in Python


A Comprehensive Guide to Built-in Functions in Python

Python is a popular language used for a wide range of programming applications. One of the benefits of Python is the vast array of built-in functions that simplify programming and make it easier to write efficient code. In this article, we’ll explore some of the most commonly used built-in functions in Python, and provide examples of how they can be used.

What are Built-in Functions?

Built-in functions are pre-defined functions that are included in the Python language. They are designed to perform specific tasks, such as manipulating strings, performing mathematical operations, or handling files. Unlike user-defined functions, built-in functions do not require any explicit definition or import statements. They are always available to the programmer.

Python has many built-in functions that can be used to perform a variety of tasks. In this guide, we’ll take a look at some of the most commonly used built-in functions in Python, and provide examples of how they can be used.

Examples of Built-in Functions

Mathematical Functions

Python includes a number of built-in mathematical functions that can be used to perform basic arithmetic operations. Some of the most commonly used mathematical functions in Python include:

  • abs() – returns the absolute value of a number
  • pow() – raises a number to a specified power
  • round() – rounds a number to a specified number of decimal places
  • max() – returns the largest value in a list or tuple
  • min() – returns the smallest value in a list or tuple

print(abs(-10)) # Output: 10
print(pow(2, 3)) # Output: 8
print(round(3.14159, 2)) # Output: 3.14
print(max(2, 5, 8, 1)) # Output: 8
print(min(2, 5, 8, 1)) # Output: 1
        

Here are a few more examples of mathematical built-in functions in Python:

  • divmod() - returns the quotient and remainder when one number is divided by another
  • sum() - returns the sum of all the elements in a list or tuple
  • round() - rounds a number to the nearest integer
  • floor() - returns the largest integer less than or equal to a given number
  • ceil() - returns the smallest integer greater than or equal to a given number

print(divmod(10, 3)) # Output: (3, 1)
my_list = [1, 2, 3, 4, 5]
print(sum(my_list)) # Output: 15
print(round(3.7)) # Output: 4
import math
print(math.floor(3.9)) # Output: 3
print(math.ceil(3.1)) # Output: 4
        

String Functions

Python also includes a number of built-in functions for manipulating strings. Strings are a fundamental data type in Python, and they are used extensively in programming. Some of the most commonly used string functions in Python include:

  • len() – returns the length of a string
  • capitalize() – capitalizes the first letter of a string
  • replace() – replaces a specified substring with another substring
  • split() – splits a string into a list of substrings based on a specified delimiter
  • join() – joins a list of strings into a single string using a specified delimiter

text = "hello world"
print(len(text)) # Output: 11
print(text.capitalize()) # Output: Hello world
print(text.replace("world", "Python")) # Output: hello Python
print(text.split(" ")) # Output: ['hello', 'world']
words = ["hello", "world"]
print(" ".join(words)) # Output: hello world
        

Here are a few more examples of string built-in functions in Python:

  • lower() – returns a string in all lowercase letters
  • upper() – returns a string in all uppercase letters
  • strip() – removes leading and trailing whitespace from a string
  • startswith() – returns True if a string starts with a specified substring
  • endswith() – returns True if a string ends with a specified substring

text = " Hello, World! "
print(text.lower()) # Output: " hello, world! "
print(text.upper()) # Output: " HELLO, WORLD! "
print(text.strip()) # Output: "Hello, World!"
print(text.startswith("Hello")) # Output: False
print(text.endswith("!")) # Output: True
        

List Functions

Python includes a number of built-in functions for manipulating lists. Lists are another fundamental data type in Python, and they are used extensively in programming. Some of the most commonly used list functions in Python include:

  • append() – adds an element to the end of a list
  • remove() – removes the first occurrence of a specified element from a list
  • sort() – sorts the elements of a list
  • reverse() – reverses the order of the elements in a list
  • count() – returns the number of times a specified element appears in a list

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
fruits.sort()
print(fruits) # Output: ['apple', 'cherry', 'orange']
fruits.reverse()
print(fruits) # Output: ['orange', 'cherry', 'apple']
print(fruits.count("cherry")) # Output: 1
        

Here are a few more examples of list built-in functions in Python:

  • extend() – adds the elements of one list to the end of another list
  • index() – returns the index of the first occurrence of a specified element in a list
  • insert() – inserts an element at a specified index in a list
  • pop() – removes and returns the element at a specified index in a list
  • clear() – removes all the elements from a list

my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
print(my_list.index(3)) # Output: 2
my_list.insert(1, 6)
print(my_list) # Output: [1, 6, 2, 3, 4, 5]
removed_element = my_list.pop(2)
print(my_list) # Output: [1, 6, 3, 4, 5]
print(removed_element) # Output: 2
my_list.clear()
print(my_list) # Output: []
        

Dictionary Functions

Python dictionaries are another fundamental data type in Python, and they are used extensively in programming. Dictionaries are a collection of key-value pairs, and they can be used to store and retrieve data efficiently. Some of the most commonly used dictionary functions in Python include:

  • keys() – returns a list of all the keys in a dictionary
  • values() – returns a list of all the values in a dictionary
  • items() – returns a list of all the key-value pairs in a dictionary
  • get() – returns the value associated with a specified key
  • pop() – removes the key-value pair associated with a specified key

person = {"name": "John", "age": 25, "country": "USA"}
print(person.keys()) # Output: dict_keys(['name', 'age', 'country'])
print(person.values()) # Output: dict_values(['John', 25, 'USA'])
print(person.items()) # Output: dict_items([('name', 'John'), ('age', 25), ('country', 'USA')])
print(person.get("name")) # Output: John
person.pop("age")
print(person) # Output: {'name': 'John', 'country': 'USA'}
        

Here are a few more examples of built-in dictionary functions in Python:

  • update() - updates the keys and values in a dictionary with another dictionary or key-value pairs
  • clear() - removes all the key-value pairs from a dictionary
  • copy() - returns a shallow copy of a dictionary
  • popitem() - removes and returns a random key-value pair from a dictionary

person = {"name": "John", "age": 25, "country": "USA"}
person2 = {"name": "Jane", "city": "New York"}
person.update(person2)
print(person) # Output: {'name': 'Jane', 'age': 25, 'country': 'USA', 'city': 'New York'}
person.clear()
print(person) # Output: {}
person = person2.copy()
print(person) # Output: {'name': 'Jane', 'city': 'New York'}
person.popitem()
print(person) # Output: {'name': 'Jane'}
        

File Handling Functions

Python provides built-in functions for handling files. These functions can be used to open, read, write, and close files in Python. Some of the most commonly used file handling functions in Python include:

  • open() – opens a file and returns a file object
  • read() – reads the contents of a file
  • write() – writes data to a file
  • close() – closes a file object

# Open a file
file = open("example.txt", "w")

# Write data to the file
file.write("Hello, world!")

# Close the file
file.close()

# Open the file again and read its contents
file = open("example.txt", "r")
print(file.read()) # Output: Hello, world!
file.close()
        

File Handling Functions (continued)

Here are a few more examples of built-in file handling functions in Python:

  • readline() – reads a single line from a file
  • readlines() – reads all the lines from a file and returns them as a list
  • writelines() – writes a list of strings to a file
  • seek() – sets the current position in a file
  • tell() – returns the current position in a file

# Open a file
file = open("example.txt", "r")

# Read a single line from the file
line = file.readline()
print(line) # Output: Hello, world!

# Read all the lines from the file and return them as a list
lines = file.readlines()
print(lines) # Output: ['Hello, world!\\\\n', 'This is a test file.\\\\n']

# Close the file
file.close()

# Open the file again and write a list of strings to it
file = open("example.txt", "w")
file.writelines(["This is line 1.\\\\n", "This is line 2.\\\\n", "This is line 3.\\\\n"])
file.close()

# Open the file again and read its contents
file = open("example.txt", "r")
print(file.read()) # Output: This is line 1.\\\\nThis is line 2.\\\\nThis is line 3.\\\\n
file.close()

# Open the file again and set the current position to the beginning of the file
file = open("example.txt", "r")
file.seek(0)

# Read the first two characters from the file
print(file.read(2)) # Output: Th

# Get the current position in the file
print(file.tell()) # Output: 2

# Close the file
file.close()
        

Type Conversion Functions

Python provides built-in functions for converting data from one type to another. These functions can be used to convert between different data types, such as integers, floats, strings, and lists. Some of the most commonly used type conversion functions in Python include:

  • int() – converts a string or float to an integer
  • float() – converts a string or integer to a float
  • str() – converts any data type to a string
  • list() – converts any iterable to a list

print(int("42")) # Output: 42
print(float("3.14")) # Output: 3.14
print(str(42)) # Output: "42"
print(list("hello")) # Output: ['h', 'e', 'l', 'l', 'o']
        

Here are a few more examples of built-in type conversion functions in Python:

  • bool() – converts a value to a Boolean (True or False) value
  • tuple() – converts any iterable to a tuple
  • set() – converts any iterable to a set
  • dict() – converts a sequence of key-value pairs to a dictionary

print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(tuple("hello")) # Output: ('h', 'e', 'l', 'l', 'o')
print(set([1, 2, 3, 2, 1])) # Output: {1, 2, 3}
print(dict([("name", "John"), ("age", 25), ("country", "USA")])) # Output: {'name': 'John', 'age': 25, 'country': 'USA'}
        

Input and Output Functions

Python provides built-in functions for getting input from the user and printing output to the console. These functions can be used to interact with the user and display information in the console. Some of the most commonly used input and output functions in Python include:

  • input() – gets input from the user
  • print() – prints output to the console

name = input("What is your name? ")
print("Hello, " + name + "!")
        

Conclusion

In this guide, we’ve explored some of the most commonly used built-in functions in Python. These functions can simplify programming and make it easier to write efficient code. Whether you’re manipulating strings, performing mathematical operations, handling lists, working with dictionaries, handling files, or getting input from the user and printing output to the console, Python’s built-in functions can help you get the job done. By mastering these functions, you’ll be well on your way to becoming a proficient Python programmer.


#python #pythonprogramming #functions #content

要查看或添加评论,请登录

社区洞察