Cookie Consent by Free Privacy Policy Generator Aktuallisiere deine Cookie Einstellungen ๐Ÿ“Œ Guide to Python's Built-in Functions


๐Ÿ“š Guide to Python's Built-in Functions


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Overview

Python offers a set of built-in functions that streamline common programming tasks. This guide categorizes and explains some of these essential functions.

Basic Functions

print(): Prints the specified message to the screen or other standard output device.

print("Hello, World!")  # Output: Hello, World!

input(): Allows the user to take input from the console.

name = input("Enter your name: ")
print(f"Hello, {name}!")

len(): Returns the length (number of items) of an object or iterable.

my_list = [1, 2, 3, 4]
print(len(my_list))  # Output: 4

type(): Returns the type of an object.

print(type(10))      # Output: <class 'int'>
print(type(3.14))    # Output: <class 'float'>
print(type("hello")) # Output: <class 'str'>

id(): Returns a unique id for the specified object.

id(my_list)

repr(): Returns a readable version of an object. ie, returns a printable representation of the object by converting that object to a string

repr(my_list)  # Output: '[1, 2, 3, 4]'

Data Type Conversion

int():Converts a value to an integer.

print(int("123"))  # Output: 123

float()Converts a value to a float.

print(float("123.45"))  # Output: 123.45

str():Converts a value to a string.

print(str(123))  # Output: '123'

bool():Convert any other data type value (string, integer, float, etc) into a boolean data type.

  • False Values: 0, NULL, empty lists, tuples, dictionaries, etc.
  • True Values: All other values will return true.
print(bool(1))  # Output: True

list(): Converts a value to a list.

print(list("hello"))  # Output: ['h', 'e', 'l', 'l', 'o']

tuple(): Converts a value to a tuple.

print(tuple("hello"))  # Output: ('h', 'e', 'l', 'l', 'o')

set(): Converts a value to a list.

print(set("hello"))  # Output: {'e', 'l', 'o', 'h'}

dict(): Used to create a new dictionary or convert other iterable objects into a dictionary.

dict(One = "1", Two = "2")  # Output: {'One': '1', 'Two': '2'}
dict([('a', 1), ('b', 2), ('c', 3)], d=4)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Mathematical Functions

abs(): Returns the absolute value of a number.

print(abs(-7))  # Output: 7

round(): Returns the absolute value of a number.

print(round(3.14159, 2))  # Output: 3.14

min(): Returns the smallest item in an iterable or the smallest of two or more arguments.

print(min([1, 2, 3, 4, 5]))  # Output: 1

max(): Returns the largest item in an iterable or the largest of two or more arguments.

print(max([1, 2, 3, 4, 5]))  # Output: 5

sum(): Sums the items of an iterable from left to right and returns the total.

print(sum([1, 2, 3, 4, 5]))  # Output: 15

pow(): Returns the value of a number raised to the power of another number.

print(pow(2, 3))  # Output: 8

Sequence Functions

enumerate(): Adds a counter to an iterable and returns it as an enumerate object.

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry

zip(): Combines multiple iterables into a single iterator of tuples.

names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
# Output:
# Alice is 24 years old
# Bob is 50 years old
# Charlie is 18 years old

sorted(): Returns a sorted list from the elements of any iterable.

print(sorted([5, 2, 9, 1]))  # Output: [1, 2, 5, 9]

reversed(): Returns a reversed iterator.

print(list(reversed([5, 2, 9, 1]))))  
# Output: [1, 9, 2, 5]

range(): Generates a sequence of numbers.

for i in range(5):
    print(i)
# Output: 0, 1, 2, 3, 4

Object and Class Functions

isinstance(): Checks if an object is an instance or subclass of a class or tuple of classes.

class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()
print(isinstance(dog, Dog))       # True
print(isinstance(dog, Animal))    # True
print(isinstance(dog, str))       # False

issubclass(): Checks if a class is a subclass of another class.

print(issubclass(Dog, Animal))  # True
print(issubclass(Dog, object))  # True
print(issubclass(Animal, Dog))  # False

hasattr(): Checks if an object has a specified attribute.

class Car:
    def __init__(self, model):
        self.model = model

car = Car("Toyota")
print(hasattr(car, "model"))    # True
print(hasattr(car, "color"))    # False

getattr(): Returns the value of a specified attribute of an object.

print(getattr(car, "model"))    # Toyota
print(getattr(car, "color", "Unknown"))  # Unknown (default value)

setattr(): Sets the value of a specified attribute of an object.

setattr(car, "color", "Red")
print(car.color)  # Red

delattr(): Deletes a specified attribute from an object.

delattr(car, "color")
print(hasattr(car, "color"))    # False

Functional Programming

lambda: Used to create small anonymous functions.

add = lambda a, b: a + b
print(add(3, 5))  # 8

map(): Applies a function to all the items in an iterable.

numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared))  # [1, 4, 9, 16]

filter(): Constructs an iterator from elements of an iterable for which a function returns

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # [2, 4, 6]

I/O Operations

open(): Opens a file and returns a corresponding file object.
write(): Writes data to a file.

file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

close(): Closes an open file.

file = open("example.txt", "r")
print(file.read())  # Line A\nLine B\nLine C
file.close()
print(file.closed)  # True

read(): Reads data from a file.

file = open("example.txt", "r")
content = file.read()
print(content)  # Hello, world!
file.close()

readline()

file = open("example.txt", "w")
file.write("Line 1\nLine 2\nLine 3")
file.close()

file = open("example.txt", "r")
print(file.readline())  # Line 1
print(file.readline())  # Line 2
file.close()

readlines()

file = open("example.txt", "r")
lines = file.readlines()
print(lines)  # ['Line 1\n', 'Line 2\n', 'Line 3']
file.close()

writelines()

lines = ["Line A\n", "Line B\n", "Line C\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()

file = open("example.txt", "r")
print(file.read())  # Line A\nLine B\nLine C
file.close()

with

with open("example.txt", "w") as file:
    file.write("Hello, world!")
# No need to call file.close(), it's done automatically

Memory Management

del(): Deletes an object.

x = 10
print(x)  # Output: 10
del x
# print(x)  # This will raise a NameError because x is deleted.

globals(): Returns a dictionary representing the current global symbol table.

def example_globals():
    a = 5
    print(globals())
example_globals()
# Output: {'__name__': '__main__', '__doc__': None, ...}

locals(): Updates and returns a dictionary representing the current local symbol table.

def example_locals():
    x = 10
    y = 20
    print(locals())
example_locals()
# Output: {'x': 10, 'y': 20}

vars(): Returns the dict attribute of the given object.

class Example:
    def __init__(self, a, b):
        self.a = a
        self.b = b

e = Example(1, 2)
print(vars(e))  # Output: {'a': 1, 'b': 2}

Miscellaneous

help(): Invokes the built-in help system.

help(len)
# Output: Help on built-in function len in module builtins:
# len(obj, /)
#     Return the number of items in a container.

dir(): Attempts to return a list of valid attributes for an object.

print(dir([]))
# Output: ['__add__', '__class__', '__contains__', ...]

eval(): Parses the expression passed to it and runs Python expression within the program.

x = 1
expression = "x + 1"
result = eval(expression)
print(result)  # Output: 2

exec(): Executes the dynamically created program, which is either a string or a code object.

code = """
for i in range(5):
    print(i)
"""
exec(code)
# Output: 
# 0
# 1
# 2
# 3
# 4

compile(): Compiles source into a code or AST object.

source = "print('Hello, World!')"
code = compile(source, '<string>', 'exec')
exec(code)
# Output: Hello, World!

Conclusion

Python's built-in functions are essential tools that facilitate a wide range of programming tasks. From basic operations to complex functional programming techniques, these functions make Python versatile and powerful. Familiarizing yourself with these functions enhances coding efficiency and effectiveness, enabling you to write cleaner and more maintainable code.

If you have any questions, suggestions, or corrections, please feel free to leave a comment. Your feedback helps me improve and create more accurate content.

Happy coding!!!

...



๐Ÿ“Œ Guide to Python's Built-in Functions


๐Ÿ“ˆ 31.97 Punkte

๐Ÿ“Œ Serverless Prey - Serverless Functions For Establishing Reverse Shells To Lambda, Azure Functions, And Google Cloud Functions


๐Ÿ“ˆ 31.9 Punkte

๐Ÿ“Œ Functions of Commercial Bank: Primary Functions and Secondary Functions


๐Ÿ“ˆ 31.9 Punkte

๐Ÿ“Œ Exploring SQL Functions: Harnessing the Power of Built-in Functions


๐Ÿ“ˆ 30.89 Punkte

๐Ÿ“Œ Durable functions in Python for Azure Functions | Azure Friday


๐Ÿ“ˆ 27.19 Punkte

๐Ÿ“Œ Arrow Functions vs. Regular Functions in JavaScript: A Comprehensive Guide


๐Ÿ“ˆ 27.06 Punkte

๐Ÿ“Œ Python: Check file existence with built-in functions


๐Ÿ“ˆ 26.18 Punkte

๐Ÿ“Œ Comparing List Comprehensions vs. Built-In Functions in Python: Which Is Better?


๐Ÿ“ˆ 26.18 Punkte

๐Ÿ“Œ A Guide to Python Lambda Functions, with Examples


๐Ÿ“ˆ 22.35 Punkte

๐Ÿ“Œ Python Functions: A beginnerโ€™s Guide - Part 1.


๐Ÿ“ˆ 22.35 Punkte

๐Ÿ“Œ Exploring Scopes in Functions in python: A Hands-On Guide


๐Ÿ“ˆ 22.35 Punkte

๐Ÿ“Œ Exploring Data with NumPy: A Guide to Statistical Functions in Python


๐Ÿ“ˆ 22.35 Punkte

๐Ÿ“Œ I Built 11 Python Projects with Chat GPT #chatgpt #python


๐Ÿ“ˆ 21.47 Punkte

๐Ÿ“Œ I Built 11 Python Projects with Chat GPT #chatgpt #python


๐Ÿ“ˆ 21.47 Punkte

๐Ÿ“Œ How I built my ideal daily Python newsletter with AWS and Python


๐Ÿ“ˆ 21.47 Punkte

๐Ÿ“Œ Hooking Linux Kernel Functions, Part 2: How to Hook Functions with Ftrace


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ Hooking Linux Kernel Functions, Part 2: How to Hook Functions with Ftrace


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ Durable Functions 2.0 - Serverless Actors, Orchestrations, and Stateful Functions


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ Polypyus - Learns To Locate Functions In Raw Binaries By Extracting Known Functions From Similar Binaries


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ You Need to Know About Pure Functions & Impure Functions in JavaScript


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ The difference between Arrow functions and Normal functions in JavaScript


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ JavaScript Arrow Functions vs Regular Functions


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ Diferenรงas prรกticas entre GCP Cloud Functions e AWS Lambda Functions


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ Pratical Differences between GCP Cloud Functions and AWS Lambda Functions


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ 7 Differences Between Arrow Functions and Traditional Functions


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ C User-Defined Functions vs Library Functions


๐Ÿ“ˆ 21.27 Punkte

๐Ÿ“Œ Why Leveraging PHP Built-in Functions Can Enhance Your Application's Performance


๐Ÿ“ˆ 20.25 Punkte

๐Ÿ“Œ If Android were to be built today, which parts of it could be built with mainstream GNU/Linux components? (i.e.: glibc and not bionic)


๐Ÿ“ˆ 19.24 Punkte

๐Ÿ“Œ How we ran a Unix-like OS (Xv6) on our home-built CPU with our home-built C compiler


๐Ÿ“ˆ 19.24 Punkte

๐Ÿ“Œ So I Built This: Broadening the Impact of What Youโ€™ve Built in the Lab


๐Ÿ“ˆ 19.24 Punkte

๐Ÿ“Œ Any books similar to Black Hat Python, or Violent Python that use Python v3?


๐Ÿ“ˆ 17.78 Punkte

๐Ÿ“Œ What Makes Python Python? (aka Everything About Pythonโ€™s Grammar)


๐Ÿ“ˆ 17.78 Punkte











matomo