def form_integer(number):
if number < 0:
print("Please provide a non-negative integer.")
return None
num_str = str(number)
num_digits = len(num_str)
last_digit = int(num_str[-1])
result = num_digits * 10 + last_digit
return result
number = int(input("Enter a positive integer: "))
new_integer = form_integer(number)
if new_integer is not None:
print(f"The newly formed integer is: {new_integer}")
#source code --> clcoding.com
Code Explanation:
1. Function Definition
def form_integer(number):
Defines a function named form_integer that accepts one parameter, number. This function processes the given number to generate a new integer.
2. Input Validation
if number < 0:
print("Please provide a non-negative integer.")
return None
Checks if the input number is negative. If it is, the function:
Prints a message: "Please provide a non-negative integer."
Returns None to terminate the function early and avoid further processing.
3. Convert Number to String
num_str = str(number)
Converts the input number to a string (num_str) so that its digits can be easily accessed and processed.
4. Count Digits
num_digits = len(num_str)
Calculates the total number of digits in the input number using the len() function. The result is stored in num_digits.
5. Extract the Last Digit
last_digit = int(num_str[-1])
Extracts the last digit of the number by accessing the last character of the string (num_str[-1]) and converting it back to an integer.
6. Form New Integer
result = num_digits * 10 + last_digit
Forms a new integer using the formula:
new integer=(number of digits×10)+(last digit)
7. Return Result
return result
Returns the newly formed integer (result) to the caller.
8. Input and Function Call
number = int(input("Enter a positive integer: "))
Prompts the user to input a positive integer.
Converts the input to an integer and stores it in the variable number.
new_integer = form_integer(number)
Calls the form_integer function with number as the argument.
Stores the returned value in the variable new_integer.
9. Output the Result
if new_integer is not None:
print(f"The newly formed integer is: {new_integer}")
Checks if the returned value (new_integer) is not None. If valid:
Prints the newly formed integer.
10. Error Handling
If the user enters a negative number, the program handles it gracefully by displaying a message and skipping further processing.
0 Comments:
Post a Comment