Posts

Showing posts from 2023

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      ...

Python len() Built in Function

The len() function returns the number of items in an object. It can be used with different data types such as strings, lists, tuples, dictionaries, sets, etc. Here are some examples of using the len() function: # Example 1: Get the length of a string name = "Alice" length = len(name) print(length) # 5 # Example 2: Get the length of a list fruits = ["apple", "banana", "cherry"] length = len(fruits) print(length) # 3 # Example 3: Get the length of a tuple colors = ("red", "green", "blue") length = len(colors) print(length) # 3 # Example 4: Get the length of a dictionary person = {"name": "Bob", "age": 25, "gender": "male"} length = len(person) print(length) # 3 # Example 5: Get the length of a set numbers = {1, 2, 3, 4} length = len(numbers) print(length) # 4 If you have any questions about this code, you can drop a line in comment .

Python list() Built in Function

The list() function is a built-in function that creates a list object from an iterable object. A list object is a collection that is ordered and changeable. You can add, remove, or modify items in a list. Here are some examples of using the list() function: # Example 1: Create a list from a string name = "Alice" name_list = list(name) print(name_list) # ['A', 'l', 'i', 'c', 'e'] # Example 2: Create a list from a tuple colors = ("red", "green", "blue") colors_list = list(colors) print(colors_list) # ['red', 'green', 'blue'] # Example 3: Create a list from another list fruits = ["apple", "banana", "cherry"] fruits_list = list(fruits) print(fruits_list) # ['apple', 'banana', 'cherry'] # Example 4: Create an empty list empty_list = list() print(empty_list) # [] If you have any questions about this code, you can drop a line in c...

Python locals() Built in Function

The locals() function in Python returns a dictionary containing the current local symbol table. A symbol table contains necessary information about the current program, such as variable names and values. The locals() function can be used to access or modify local variables inside a function or a class. Here are some examples of using locals() function in Python: Using locals() function in Python # This example prints the local symbol table of the global scope x = 10 y = 20 print(locals()) # Output: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000021E9F8A7D30>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 10, 'y': 20} Using Python locals() function inside local scope # This example prints the local symbol table of a function def foo():     a = 1 ...

Python map() Built in Function

The map() function in Python executes a specified function for each item in an iterable. The item is sent to the function as a parameter. The map() function returns a map object, which is an iterator that yields the results of applying the function to each item. The map object can be converted into a list, tuple, set, or other collection type. Here are some examples of using map() function in Python: Using map() with a single iterable # This example applies the len() function to each element of a list and returns a list of lengths words = ["apple", "banana", "cherry"] lengths = list(map(len, words)) print(lengths) # Output: [5, 6, 6] Using map() with multiple iterables # This example applies the pow() function to two lists of numbers and returns a list of powers base = [2, 3, 4] exponent = [1, 2, 3] powers = list(map(pow, base, exponent)) print(powers) # Output: [2, 9, 64] Using map() with lambda functions # This example uses a lambda function to squ...

Python max() Built in Function

The max() function in Python returns the item with the highest value, or the item with the highest value in an iterable. An iterable can be a list, tuple, set, dictionary, string, etc. The max() function can also take two or more arguments and return the largest one. Here are some examples of using max() function in Python: Using max() with a single iterable # This example returns the largest number in a list numbers = [18 ,52 ,23 ,41 ,32] largest = max(numbers) print(largest) # Output: 52 Using max() with multiple arguments # This example returns the largest number among four arguments result = max(5 ,10 ,25 ,99) print(result) # Output: 99 Using max() with strings # This example returns the alphabetically last string in a list words = ["apple" ,"banana" ,"cherry" ,"date"] last = max(words) print(last) # Output: date Using max() with a key function # This example returns the longest string in a list using len() as a key function words = [...

Python memoryview() Built in Function

The memoryview() function in Python returns a memory view object of a given argument. A memory view object allows you to access the internal data of an object that supports the buffer protocol without copying it. The buffer protocol provides a way to access the low-level memory of an object. Examples of objects that support the buffer protocol are bytes, bytearray, array.array, etc. Here are some examples of using memoryview() function in Python: Using memoryview() with a bytearray # This example creates a memory view object from a bytearray and prints its elements byte_array = bytearray('ABC', 'utf-8') mv = memoryview(byte_array) print(mv[0]) # Output: 65 print(bytes(mv[0:2])) # Output: b'AB' print(list(mv[0:3])) # Output: [65 ,66 ,67] Using memoryview() to modify internal data # This example modifies the first element of a bytearray using a memory view object byte_array = bytearray('ABC', 'utf-8') print('Before update:', byte_ar...

Python min() Built in Function

The min() function in Python returns the smallest item in an iterable or the smallest item among two or more arguments. An iterable can be a list, tuple, set, dictionary, string, etc. The min() function can also take a key function to customize the comparison criteria. Here are some examples of using min() function in Python: Using min() with a single iterable # This example returns the smallest number in a list numbers = [9 ,34 ,11 ,-4 ,27] smallest = min(numbers) print(smallest) # Output: -4 Using min() with multiple arguments # This example returns the smallest number among four arguments result = min(5 ,10 ,25 ,99) print(result) # Output: 5 Using min() with strings # This example returns the alphabetically first string in a list words = ["apple" ,"banana" ,"cherry" ,"date"] first = min(words) print(first) # Output: apple Using min() with a key function # This example returns the shortest string in a list using len() as a key function w...

Python next() Built in Function

The next() function in Python returns the next item from an iterator. An iterator is an object that can be iterated over, such as a list, tuple, string, etc. The next() function can also take a default value as a second argument, which is returned if the iterator has no more items. Here are some examples of using next() function in Python: Using next() with a list iterator # This example creates an iterator from a list and prints its items one by one mylist = iter(["apple" ,"banana" ,"cherry"]) x = next(mylist) print(x) # Output: apple x = next(mylist) print(x) # Output: banana x = next(mylist) print(x) # Output: cherry Using next() with a default value # This example returns a default value when the iterator has reached its end mylist = iter(["apple" ,"banana" ,"cherry"]) while True:     item = next(mylist ,"end")     if item == "end":         break     print(item) # Output: apple banana cherry Us...

Python object() Built in Function

The object() function in Python returns a new featureless object that has no attributes. It is a base class for all other classes in Python. The object() function can also be used to test if an object is an instance of a class. Here are some examples of using object() function in Python: Using object() to create a featureless object # This example creates an object using object() and tries to access its attributes obj = object() print(obj) # Output: <object object at 0x000001F8C9A6E0D0> print(obj.name) # Output: AttributeError: 'object' object has no attribute 'name' Using object() as a base class # This example creates a class that inherits from object and adds some attributes class Bike(object):     def __init__(self ,name ,gear):         self.name = name         self.gear = gear     def __str__(self):         return f"{self.name} has {se...

Python oct() Built in Function

The oct() function in Python converts an integer number into an octal string. Octal strings in Python are prefixed with 0o. The oct() function can also convert numbers from other bases, such as binary or hexadecimal, into octal. Here are some examples of using oct() function in Python: Using oct() with a decimal number # This example converts a decimal number into an octal string x = oct(12) print(x) # Output: 0o14 Using oct() with a binary number # This example converts a binary number into an octal string x = oct(0b1010) print(x) # Output: 0o12 Using oct() with a hexadecimal number # This example converts a hexadecimal number into an octal string x = oct(0xAF) print(x) # Output: 0o257 If you have any questions about this code, you can drop a line in comment .

Python open() Built in Function

The open() function is used to open a file and return a file object that can be used to read or write data. The syntax of the open() function is: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) The file parameter is the name of the file or a path to it. The mode parameter specifies how the file should be opened. There are different modes for reading, writing and appending data. Some common modes are: “r” - Read - Default value. Opens a file for reading, error if the file does not exist “w” - Write - Opens a file for writing, creates the file if it does not exist “a” - Append - Opens a file for appending, creates the file if it does not exist “r+” - Read/Write - Opens a file for both reading and writing, error if the file does not exist Here are some examples of using the open() function in Python: To open a text file named “demofile.txt” in read mode and print its content: f = open("demofile.txt", "r...

Python ord() Built in Function

The ord() function is used to get the integer value that represents the Unicode code point of a character. The syntax of the ord() function is: ord(char) The char parameter is a string of length one that contains a Unicode character. The return value is an integer between 0 and 1114111 (inclusive). Some common Unicode code points are: 48 for ‘0’ 65 for ‘A’ 97 for ‘a’ 8364 for ‘€’ Here are some examples of using the ord() function in Python: To get the Unicode code point of an integer character: print(ord('8')) # prints 48 To get the Unicode code point of an alphabet character: print(ord('R')) # prints 82 To get the Unicode code point of a special character: print(ord('&')) # prints 38 To get the Unicode code point of a non-ASCII character: print(ord('€')) # prints 8364  If you have any questions about this code, you can drop a line in comment .

Python print() Built in Function

The print() function is used to display output to the standard output device (usually the screen). The syntax of the print() function is: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) The objects parameter is required and can be any number of objects that you want to print. The objects will be converted to strings before printing. The sep parameter is optional and specifies how to separate the objects if there are more than one. The default value is a single space ’ '. The end parameter is optional and specifies what to print at the end of the line. The default value is a newline character ‘\n’. The file parameter is optional and specifies an object with a write method where the output will be printed instead of sys.stdout (the standard output). The flush parameter is optional and specifies whether to forcibly flush the stream after printing. Here are some examples of using the print() function in Python: To print a simple message: print("H...