Passing String Value To The Function In Python

INTRODUCTION

This Python program efficiently demonstrates how to pass a string to a function, format it, and display key information. It begins by offering the user two options: pass a string or exit. When the user chooses to pass a string, the program checks for validity, ensuring it’s not empty, and then passes it to a function that prints the string in different formats, calculates its length, and returns a custom message. Through smooth transitions between user inputs and validations, the program handles errors gracefully and allows repeated string entries or an exit option.

PROGRAM

Python Code To Pass String Value To The Function In Python

def passing_a_string(value):
    print("\nPassed String Value Is At End--->", value)
    print(value, "<---Passed Value Is At Beginning")
    print("The Length Of String:",len(value))
    string = f"This Is The String-> {value} Which  Is Been Passed"
    return string


while True:
    try:
        print("\t**********PASSING A STRING TO A FUNCTION**********")
        print("\nSELECT THE BELOW OPTIONS")
        print("\t1.TO PASS A STRING")
        print("\t2.EXIT THE PROGRAM")
        options = int(input("ENTER THE OPTION[1/2]:"))

        if options == 1:
            n = input("\nEnter The String To Pass:").strip()
            if n:
                result=passing_a_string(n)
                print(result)
            else:
                print("Please Enter A Non-Empty String.")
        
       
        
        elif options == 2:
            print("Exiting The Program.....")
            break
        
        else:
            print("Invalid Option!!! Please Choose From [1/2]")
    
    except ValueError:
        print("Invalid Input!!! Enter The Options In Number [1/2]")

Defining the function

def passing_a_string(value):
    print("\nPassed String Value Is At End--->", value)
    print(value, "<---Passed Value Is At Beginning")
    print("The Length Of String:", len(value))
    string = f"This Is The String-> {value} Which  Is Been Passed"
    return string

The program begins by defining the passing_a_string function. It accepts a string value as input. Inside the function, the string is printed twice: first at the end of a message and then at the beginning. The length of the string is also calculated using len(value) and displayed. Lastly, it returns a formatted message containing the passed string.

Starting the loop

while True:
    try:
        print("\t**********PASSING A STRING TO A FUNCTION**********")
        print("\nSELECT THE BELOW OPTIONS")
        print("\t1.TO PASS A STRING")
        print("\t2.EXIT THE PROGRAM")
        options = int(input("ENTER THE OPTION[1/2]:"))

The program enters a while True loop to keep presenting the menu until the user decides to exit. It prints a header, followed by two options:1.  passing a string or 2. exiting the program. The user is prompted to enter their choice, which is then converted to an integer using int(input()).

Handling option 1 (passing a string)

if options == 1:
    n = input("\nEnter The String To Pass:").strip()
    if n:
        result = passing_a_string(n)
        print(result)
    else:
        print("Please Enter A Non-Empty String.")

If the user selects option 1, the program asks for a string. The strip() method removes any extra spaces from the input. If the string is non-empty, it is passed to the passing_a_string function, which processes it and returns a result. The program then prints this result. If the input string is empty, the program informs the user to enter a valid string.

Handling option 2 (exit)

elif options == 2:
    print("Exiting The Program.....")
    break

when the user chooses option 2, the program prints an exit message and uses break to terminate the loop, ending the program

Handling invalid options

else:
    print("Invalid Option!!! Please Choose From [1/2]")

If the user enters a number other than 1 or 2, the program catches this and informs the user that only valid options (1 or 2) are acceptable.

Handling non-integer inputs

except ValueError:
    print("Invalid Input!!! Enter The Options In Number [1/2]")

the try-except block ensures that if the user inputs a non-numeric value (e.g., a letter or symbol), the program catches the ValueError and informs the user to input a number (1 or 2). The loop then repeats, prompting the user again.

OUTPUT

**********PASSING A STRING TO A FUNCTION**********
SELECT THE BELOW OPTIONS

1.TO PASS A STRING
2.EXIT THE PROGRAM

ENTER THE OPTION[1/2]:1
Enter The String To Pass:Python

Passed String Value Is At End---> Python
Python <---Passed Value Is At Beginning
The Length Of String: 6
This Is The String-> Python Which  Is Been Passed

**********PASSING A STRING TO A FUNCTION**********
SELECT THE BELOW OPTIONS

1.TO PASS A STRING
2.EXIT THE PROGRAM

ENTER THE OPTION[1/2]:2
Exiting The Program.....

CONCLUSION

In conclusion, the program effectively handles user input with clear transitions and steps. It actively processes string inputs and returns formatted outputs through a function. The while True loop keeps the program running until the user exits, with straightforward error handling for invalid options and non-numeric inputs, ensuring a smooth and interactive experience throughout.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top