Posts

Showing posts with the label Python Built in Functions

Python exec() Built in Function

The exec() function in Python is used to execute a dynamically generated code, which is a code that is created or modified at runtime. The exec() function takes a string or an object that contains a valid Python code and executes it as if it was written in a file. You can also pass a dictionary of global and local variables to the exec() function to modify the execution environment. Here are some examples of using exec() in Python: Execute a Python statement stored as a string: code = 'print("Hello, world!")' exec(code) Output: Hello, world! In this example, exec(code) executes the Python statement 'print("Hello, world!")', which prints the string "Hello, world!" to the console. Use exec() to execute a Python script stored in a file: with open('script.py', 'r') as file:     code = file.read() exec(code) In this example, we open the file 'script.py', read its contents into a string, and then use exec() to execu...

Python eval() Built in Function

The eval() function in Python is used to evaluate a string or an object that contains a valid Python expression, which is a code that returns a value. The eval() function takes a string or an object that contains a valid Python expression and evaluates it as if it was written in a file. You can also pass a dictionary of global and local variables to the eval() function to modify the evaluation environment. Here are some examples of using eval() in Python: Evaluate a mathematical expression stored as a string: result = eval('3 + 4 * 2') print(result) Output: 11 In this example, eval('3 + 4 * 2') evaluates the mathematical expression '3 + 4 * 2' and returns the result (11). Note that eval() can be dangerous if used improperly, as it allows arbitrary code execution. You should only use eval() with trusted input. Evaluate a Python expression that references variables in your program: x = 5 y = 10 result = eval('x * y') print(result) Output: 50 In this...

Python divmod() Built in Function

The divmod() function in Python is used to find the quotient and remainder of dividing two numbers. The divmod() function takes two numbers as arguments and returns a tuple containing the quotient and remainder as (quotient, remainder). The numbers can be integers or floats, but they must be non-complex. Here are some examples of using divmod() in Python: Divide two numbers and get the quotient and remainder: >>> divmod(10, 3) (3, 1) In this example, divmod(10, 3) divides 10 by 3, and returns a tuple containing the quotient 3 and the remainder 1. Calculate the number of hours and minutes in a given number of minutes: >>> total_minutes = 135 >>> hours, minutes = divmod(total_minutes, 60) >>> print(hours, "hours", minutes, "minutes") 2 hours 15 minutes In this example, we start with a total number of minutes (135) and use divmod(total_minutes, 60) to calculate the number of hours and minutes. The divmod() function returns a tu...

Python dir() Built in Function

The dir() function in Python is used to get a list of attributes and methods of an object. The dir() function takes an object as an argument and returns a list of strings containing the names of its attributes and methods. The object can be any Python data type or user-defined class. Here are some examples of using dir() in Python: Get all the attributes and methods of a built-in Python object:  >>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr_...

Python enumerate() Built in Function

Python enumerate() is a built-in function that returns an enumerate object. It allows you to loop over a collection (such as a list, tuple, string, etc.) and keep track of the index and value of each element. You can use it in for loops or convert it to a list or dictionary. Here are some examples of how to use Python enumerate() : To print the index and value of each element in a list: Iterate over a list and print the index and value of each item: fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits):     print(index, fruit) Output: 0 apple 1 banana 2 cherry 0 apple 1 banana 2 cherry In this example, enumerate(fruits) returns an iterator that produces tuples containing the index and value of each item in the list. We use a for loop to iterate over this iterator and print the index and value of each item. Create a dictionary that maps the index of each word in a list to the word itself: words = ['foo', 'bar', 'baz...

Python float() Built in Function

The float() function in Python is used to convert a value into a floating point number, which is a number with a decimal point. For example, float(3) returns 3.0 and float(“5.5”) returns 5.5. You can also use float() with numbers that are too large or too small for Python to represent as integers, such as 1.82e310 or -32.54e100. Here are some examples of using float() in Python: # Example 1: Convert an integer to a float x = 25 y = float(x) print(y) # Output: 25.0 # Example 2: Convert a string to a float s = "12.34" z = float(s) print(z) # Output: 12.34 # Example 3: Convert an infinity value to a float inf = "infinity" w = float(inf) print(w) # Output: inf If you have any questions about this code, you can drop a line in comment .

Python format() Built Function

Python format() is a string method that allows you to format and insert values into a string. It can be used with positional arguments, keyword arguments, or both. You can also specify formatting options such as alignment, width, precision, etc. Here are some examples of how to use Python format() : To insert values into a string using positional arguments: txt = "My name is {0}, I'm {1}".format("John", 36) print(txt) Output: My name is John, I'm 36 To insert values into a string using keyword arguments: txt = "My name is {fname}, I'm {age}".format(fname="John", age=36) print(txt) Output: My name is John, I'm 36 To insert values into a string using both positional and keyword arguments: txt = "Hi {name}, welcome to {0} tutorials".format("Guru99", name="Jessica") print(txt) Output: Hi Jessica, welcome to Guru99 tutorials To align and pad values in a string using formatting options: txt = "{:...

Python frozenset() Built in Function

Python frozenset() is a built-in function that returns an immutable set object. A set is a collection of unique and unordered elements that supports operations like union, intersection, difference, etc. A frozenset is like a set, but it cannot be modified or changed once created. Here are some examples of how to use Python frozenset() : To create a frozenset from a list of fruits: fruits = ["apple", "banana", "cherry"] fset = frozenset(fruits) print(fset) Output: frozenset({'apple', 'banana', 'cherry'}) To create an empty frozenset: fset = frozenset() print(fset) Output: frozenset() To perform set operations with frozensets: a = frozenset([1, 2, 3]) b = frozenset([3, 4, 5]) print(a.union(b)) # returns a new frozenset with elements from both a and b print(a.intersection(b)) # returns a new frozenset with elements common to both a and b print(a.difference(b)) # returns a new frozenset with elements in a but not in b Output: fro...

Python getattr() Built in Function

Python getattr() is a built-in function that returns the value of a named attribute of an object. It can also take a default value as an optional argument, which is returned if the attribute does not exist. Here are some examples of how to use Python getattr() : To get the value of an existing attribute of an object: class Person:     name = "John"     age = 36     country = "Norway" person = Person() print(getattr(person, "name")) # returns "John" print(getattr(person, "age")) # returns 36 To get the value of a non-existing attribute of an object with a default value: class Person:     name = "John"     age = 36     country = "Norway" person = Person() print(getattr(person, "city", "Unknown")) # returns "Unknown" To implement a custom getattr() method for an object that dynamically computes attribute values: class Square:     def __init__(self, side):     ...

Python globals() Built in Function

Python globals() is a built-in function that returns a dictionary containing the current global symbol table. A symbol table is a data structure that stores information about the names and values of variables, functions, classes, etc. in a program. A global symbol table contains the names and values that are accessible from any scope in the program. Here are some examples of how to use Python globals() : To access and modify a global variable using globals() : x = 10 # global variable print("The value of x is:", x) # prints 10 globals()["x"] = 20 # modifies x using globals() print("The value of x is:", x) # prints 20 To get information about the current program using globals() : print("The name of this module is:", globals()["__name__"]) # prints __main__ print("The file name of this module is:", globals()["__file__"]) # prints the file name To define a new global variable using globals() :  globals()["y...

Python hasattr() Built in Function

Python hasattr() is a built-in function that returns True if an object has a given attribute, otherwise False. An attribute can be a variable, a method, a property, etc. that belongs to an object. Here are some examples of how to use Python hasattr() : To check if an object has an attribute defined in its class: class Car:     brand = "Ford"     number = 7786 car = Car() print(hasattr(car, "brand")) # returns True print(hasattr(car, "color")) # returns False To check if an object has an attribute defined dynamically: class Person:     name = "John"     age = 36 person = Person() person.country = "Norway" # defines a new attribute dynamically print(hasattr(person, "country")) # returns True To check if an object has a method or a property: class Circle:     def __init__(self, radius):         self.radius = radius     def area(self): # defines a method  ...

Python hash() Built in Function

Python hash() is a built-in function that returns the hash value of an object if it has one. A hash value is an integer that represents the identity of an object and can be used to compare objects for equality or to store them in a dictionary or a set. Here are some examples of how to use Python hash() : To get the hash value of different types of objects: print(hash(181)) # returns 181 print(hash(181.23)) # returns 530343892119126197 print(hash("Python")) # returns 2230730083538390373   To get the hash value of a user-defined class: class Person:     def __init__(self, name, age):         self.name = name         self.age = age     def __hash__(self):         return hash((self.name, self.age)) person1 = Person("John", 36) person2 = Person("Mary", 28) print(hash(person1)) # returns -9209083346939511628 print(hash(person2)) # returns -920908334...

Python help() Built in Function

Python help() is a built-in function that invokes the built-in help system. The help system provides information about the syntax, parameters, return values and examples of Python objects such as modules, classes, functions, etc. Here are some examples of how to use Python help() : To get the general help message: help() To get the help message for a specific object: help(print) # prints the help message for the print function help(list) # prints the help message for the list class help(math) # prints the help message for the math module To get the help message for a specific attribute or method of an object: help(list.append) # prints the help message for the append method of list class help(math.pi) # prints the help message for the pi attribute of math module You can also use the argparse module to create a command-line interface for your Python script that displays a help message when invoked with the -h or --help option. For example: import argparse parser = argparse.Argum...

Python hex() Built in Function

The hex() function in Python is a built-in function that converts an integer to its corresponding hexadecimal number and returns it as a string. The hexadecimal representation is in lowercase prefixed with 0x. For example: >>> hex(255) # convert 255 to hexadecimal '0xff >>> hex(-35) # convert -35 to hexadecimal '-0x23' >>> type(hex(10)) # check the return type of hex() <class 'str'> You can also use the float.hex() method to convert a floating-point number to its hexadecimal representation. For example: >>> float.hex(2.5) # convert 2.5 to hexadecimal '0x1.4000000000000p+1' >>> float.hex(0.0) # convert 0.0 to hexadecimal '0x0.0p+0' If you want to learn more about Python built-in functions, you can check out some of the web pages on Python hex() function. If you have any questions about this code, you can drop a line in comment .

Python id() Built Function

The id() function in Python is a built-in function that returns a unique id for the specified object. All objects in Python have their own unique id, which is assigned to them when they are created. The id is an integer number that represents the memory address of the object. For example: >>> x = ('apple', 'banana', 'cherry') # create a tuple object >>> id(x) # get the id of x 140472391630016 >>> y = 5 # create an integer object >>> id(y) # get the id of y 140472391630016 >>> z = "geek" # create a string object >>> id(z) # get the id of z 139793848214784 You can use the id() function to compare two objects and check if they are identical (have the same memory address) or not. For example: >>> a = 5 # create an integer object with value 5 >>> b = 5 # create another integer object with value 5 >>> c = 6 # create an integer object with value 6 >>> id(a) ==...

Python input() Built in Function

The input() function allows user input from the standard input device (usually keyboard). It takes an optional prompt parameter that displays a message before taking the input. The input() function returns a string value that can be assigned to a variable or used directly. Here are some examples of using the input() function: # Example 1: Input with prompt name = input("Enter your name: ") # Enter your name: John print("Hello, " + name) # Hello, John # Example 2: Input without prompt color = input() # Red print("Your favorite color is " + color) # Your favorite color is Red # Example 3: Input with Unicode characters emoji = input("Enter an emoji: ") # Enter an emoji: 😊 print("You entered " + emoji) # You entered 😊 # Example 4: Input a number and convert it to integer age = int(input("Enter your age: ")) # Enter your age: 25 print("You are " + str(age) + " years old") # You are 25 years old If...

Python int() Built in Function

The int() function converts a value to an integer object. It can take a number or a string as an argument, and an optional base parameter that specifies the number format. The default base is 10. Here are some examples of using the int() function: # Example 1: Convert a floating point number to an integer x = int(3.14) # x is 3 # Example 2: Convert a string to an integer y = int("42") # y is 42 # Example 3: Convert a hexadecimal string to an integer with base 16 z = int("FF", 16) # z is 255 # Example 4: Convert a binary string to an integer with base 2 w = int("1010", 2) # w is 10 If you have any questions about this code, you can drop a line in comment .

Python isinstance() Built in Function

The isinstance() function checks whether an object is an instance of a specified class or type. It returns True if the object belongs to the class or type, otherwise False. Here are some examples of using the isinstance() function: # Example 1: Check for built-in types mystr = "Hello World" num = 100 flt = 10.2 print(isinstance(mystr, str)) # True print(isinstance(mystr, int)) # False print(isinstance(num, int)) # True print(isinstance(num, str)) # False print(isinstance(flt, float)) # True print(isinstance(flt, int)) # False # Example 2: Check for multiple types using a tuple mylist = [1, 2, 3] mytuple = (4, 5, 6) myset = {7, 8 ,9} print(isinstance(mylist, (list, tuple))) # True print(isinstance(mytuple, (list, tuple))) # True print(isinstance(myset, (list ,tuple))) # False # Example 3: Check for custom classes using inheritance class Animal:     pass class Dog(Animal):     pass class Cat(Animal):     pass class Bird:   ...

Python issubclass() Built in Function

The issubclass() function checks if a class is a subclass of another class. It returns True if the first argument is a subclass of the second argument, otherwise False. Here are some examples of using the issubclass() function: # Example 1: Check for built-in types print(issubclass(int, object)) # True print(issubclass(str, object)) # True print(issubclass(bool, int)) # True print(issubclass(list, tuple)) # False # Example 2: Check for custom classes using inheritance class Animal:     pass class Dog(Animal):     pass class Cat(Animal):     pass class Bird:     pass dog = Dog() cat = Cat() bird = Bird() print(issubclass(Dog ,Animal)) # True print(issubclass(Cat ,Animal)) # True print(issubclass(Bird ,Animal)) # False print(issubclass(dog ,Dog)) # TypeError: issubclass() arg 1 must be a class If you have any questions about this code, you can drop a line in comment .

Python iter() Built in Function

The iter() function returns an iterator object for a given iterable or a callable object. An iterator is an object that can be iterated over, meaning that you can traverse through all the values. Here are some examples of using the iter() function: # Example 1: Get an iterator from a list fruits = ["apple", "banana", "cherry"] fruits_iter = iter(fruits) print(next(fruits_iter)) # apple print(next(fruits_iter)) # banana print(next(fruits_iter)) # cherry # Example 2: Get an iterator from a custom class class Counter:     def __init__(self, max):         self.max = max     def __iter__(self):         self.num = 0         return self     def __next__(self):         if self.num < self.max:             self.num += 1      ...