eunsang
eunsang

Reputation: 23

Can you explain how int function(int()) works in Python?

Hello I just have a question about int function. It convert data(for example, string) to int data. My question is how this function works like this? I tried to implement int function myself without any help with built-in function,and I realized this is really hard working. I searched about int function, most of sites have simple description. Just saying 'Return an integer object' like this. It looks easy but hard for me...

I searched and didn't found what I want

Upvotes: -5

Views: 94

Answers (1)

Brijesh Dubey
Brijesh Dubey

Reputation: 1

Pythons int() function does more than just converting a string to integer.The behavior varies based on the argument and an optional base parameter. we can break down behavior as follows:

  1. No arguments int() # returns 0
  2. Numeric Arguments
    • If the argument if an integer
       int(5) # return 5
    
    • If argument if a float, then it will remove(truncate) the fractional part
       int(2.04) # return 2
    
  3. string Arguments
    • int() strips any whitespace, and also can handle an optional sign(+ or -) and then converts the sequence of digits to an integer.
  • For example:
int("  -10  ")  # returns -10
  • We can also provide an optional base for conversion
int("1010", 2)  # returns 10 (binaray to decimal)

Steps in the conversion process

  1. String Handling
    • Strip whitespace.
    • Handling leading sign(+ or -).
  2. Validation
    • To check all charters are vailid digits for the given base.
  3. Digit conversion
    • Convert each charater to its corresponding numerical value.
  4. Accumulation
    • Compute the integer value by iterating through each digit

For example:


def custom_integer_converter(s, base=10):
    # Ensure input is a string
    if not isinstance(s, str):
        raise TypeError("Input must be a string")
    
    s = s.strip().lower()  # Handle whitespace and case insensitivity
    
    if not s:
        raise ValueError("Empty string after stripping whitespace")
    
    # Determine the sign
    sign = 1
    if s[0] == '-':
        sign = -1
        s = s[1:]
    elif s[0] == '+':
        s = s[1:]
    
    if not s:
        raise ValueError("No digits after sign")
    
    # Validate characters and convert to integer
    value = 0
    for c in s:
        # Convert character to numerical value
        if c.isdigit():
            digit = ord(c) - ord('0')
        else:
            digit = ord(c) - ord('a') + 10
        
        # Check if digit is valid for the base
        if not (0 <= digit < base):
            raise ValueError(f"Invalid character '{c}' for base {base}")
        
        value = value * base + digit
    
    return sign * value

enter image description here The image contains the implementation of the code mentioned above, along with tested inputs.

Upvotes: -4

Related Questions