Search code examples
pythonstringpython-3.9

Python: How to prevent special characters in input


My problem is when I enter a number in the input field, it becomes number with special character. I don't know why it's adding extra characters to input. You can see the example. I entered just 5.2 and it became '5.2&

"""
length of rectangle = a
width of rectangle = b
calculate the area and perimeter of the rectangle
"""

a = 6
b = float(input("width: "))

area = a*b
perimeter = (2*a) + (2*b)

print("area: " + str(area) + " perimeter: " + str(perimeter))
File "c:\Users\HP\OneDrive - Karabuk University\Belgeler\Downloads\first.py", line 8, in <module>
b = float(input("width: "))
ValueError: could not convert string to float: '5.2&

Could you please help me?


Solution

  • For me It's working fine...See my output..

    Note: It throws error at last line in your code because you can't concatenate a str with an int.

    So, you need to convert int to str before concatenating your variables

    a = 6
    b = float(input("width: "))
    print(b)
    
    area = a*b
    perimeter = (2*a) + (2*b)
    
    print("area: " + str(area) + " perimeter: " + str(perimeter))
    

    #output

    width: 5.2
    5.2
    area: 31.200000000000003 perimeter: 22.4
    

    Alternate solution 2

    Idk why it's adding extra chars to your user input...Anyway you can filter user input once entered as follows.

    import re
    a = 6
    b = (input("width: "))
    b=str(b)
    b=re.sub("[^0-9^.]", "", b)
    
    b=float(b)
    print(b)
    
    area = a*b
    perimeter = (2*a) + (2*b)
    
    print("area: " + str(area) + " perimeter: " + str(perimeter))
    

    output #

    width: 5.2b
    5.2
    area: 31.200000000000003 perimeter: 22.4