How to pass an expression as input and it gives the ceil value as the output?

401 Views Asked by At

a. In variables a,b gets the input from the user so as to evaluate the expression from the given input and it gives the ceil and floor values as the output.

 def ceil_flooor():
    a = float(input())
    b = float(input())
    
    print(math.ceil(a))
    print(math.floor(b))

input : 5.5+6.5-8.5 output: 4(ceil value),3(floor value)

I am getting the below error:

"ValueError: could not convert string to float: '5.5+6.5-8.5'"

1

There are 1 best solutions below

1
Chandler Bong On BEST ANSWER

float() can't evaluate expressions. To achieve what you have in mind, you have to use eval(). This will help evaluate input expressions.

def ceil_flooor():
    a = eval(input())  # <==== edited this line in your code
    b = eval(input())  # <==== edited this line in your code
    
    print(math.ceil(a))
    print(math.floor(b))
    
ceil_flooor()

Input:

5.5 + 1

2.1 + .2

Output:

7

2