# 2) Write a program to input a string from the user evaluate using Try and Except

try:
    a = str(input("Enter the value of X :"))
    b = str(input("Enter the value of Y :"))
    
    
    print(a,b)
except Exception as e :
    print("Exception value is not string caught :",e)
    
print("byy")

i am using that but not exception error properly

What do you want to do with your code?

input a string from the user evaluate using Try and Except.
means i wanna check input is string or not , if value is not string than i wanna print except …

You have a problem? Looks right to me.
Although… “check if input is a string” is a pointless task I think. Like, the input will ALWAYS be considered a string. At least I have no idea what you could possible put into the input, that wouldn’t be a string.

Yes, the input will always be a string, It could be easier to rather check is the input is an int.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I agree with some of the above comments. Overall this isn’t the best way to check. Another issue is that try/except blocks don’t always help you understand what went wrong.

It would be good to separate the things you are doing. For example, having a function like is_not_number() that takes a string and returns a bool. Then you could use these kind of steps for your program:

  1. Get input from user
  2. Validate the input
  3. If input is a string, proceed to whatever is next. If not a string, print some good feedback for the user.

Depending on how you set this up, if the input is not a string, you could continue to ask the user for input until the input is valid.

Note: If you are passing a string to int() it will not always have the results that you want. A string of “1.1” will give an error. Python has another builtin function that can handle that case better, but I will leave that up to you to discover.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.