[Python] Why am I getting different outputs for a similar input?

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to solve the "Math Interptreter" problem of problem set 1 of harvard cs50 python course. The question is: In a file called interpreter.py, implement a program that prompts the user for an arithmetic expression and then calculates and outputs the result as a floating-point value formatted to one decimal place. Assume that the user’s input will be formatted as x y z, with one space between x and y and one space between y and z, wherein:

    x is an integer y is +, -, *, or / z is an integer For instance, if the user inputs 1 + 1, your program should output 2.0. Assume that, if y is /, then z will not be 0.

    I did the following:

    expression=input("Enter the expression: ").replace(" ","")
    if "+" in expression:
    operation="+"
    elif "-" in expression:
    operation="-"
    elif "*" in expression:
    operation="*"
    else:
    operation="/"
    position=expression.find(operation)
    x=int(expression[:position])
    y=int(expression[position:])
    print(x)
    print(operation)
    print(y)

    here


    I tried to remove the spaces and then check which operation is given by the user. Then, I tried to find the position of the operation using the find keyword in order to slice the string into two parts i.e. x (which will contain the fisrt integer) and y (which will contain the second integer). Then I was about to perform the operation. But, the error is that when I enter '55 + 6' as an input, x is assigned as 55 and y is assigned as 6. However, when I enter '55 - 6' as an input, x is assigned as 55 and y is assigned as -6. Why is y assigned as -6?

    Continue reading...

Compartilhe esta Página