如何使输入变量按字面量类型传递?求修改指定Python代码
Fix: Pass Input as Literal Type (Int/Float/String) in Python
Got it, let's sort out this issue! The root problem here is that Python's input() function always returns a string by default—even if you type a number like 10, it gets stored as the string "10". That's why your str_len() function isn't detecting integers/floats correctly.
Here's the modified code that will parse the input into its actual literal type:
def str_len(s): if type(s) == int: return "You entered Integer, Please enter strings only to get length" elif type(s) == float: return "You entered float, Please enter strings only to get length" else: return len(s) # Process input to convert to its literal type user_input = input("Enter a string to get its length: ") # First try converting to integer try: parsed_input = int(user_input) except ValueError: # If int conversion fails, try float try: parsed_input = float(user_input) except ValueError: # If both fail, keep as string parsed_input = user_input # Test the function print(str_len(parsed_input))
How This Works
- When you input
10, the code first converts the string"10"to an integer10, sostr_len()correctly detects it as an int. - If you input
10.5, it converts to a float10.5after failing the int conversion. - For inputs like
"hello"or"test123", both conversion attempts fail, so it stays as a string, andstr_len()returns its length.
Optional Optimization (Handle 10.0 as Integer)
If you want inputs like "10.0" (which is technically a float) to be treated as an integer, you can add an extra check:
def str_len(s): if type(s) == int: return "You entered Integer, Please enter strings only to get length" elif type(s) == float: return "You entered float, Please enter strings only to get length" else: return len(s) user_input = input("Enter a string to get its length: ") parsed_input = user_input try: num = float(user_input) # Check if the float is a whole number if num.is_integer(): parsed_input = int(num) else: parsed_input = num except ValueError: # Leave as string if conversion fails pass print(str_len(parsed_input))
This version will convert "10.0" to the integer 10, making the type detection even more accurate to the user's literal input intent.
内容的提问来源于stack exchange,提问作者gkiranreddy
相关产品推荐
相关产品推荐

