Nameerror: name 'Y' is not defined

Asked

Viewed 907 times

-1

So I’m trying to make a very simple calculator, (one of my first "projects"). In this calculator you need to choose an operation. Each operation has an associated number, and I use if and Elif to make the choice of the operation. However, when choosing the operation using input, at the time of the application check the chosen values, it says that the variable in this case y has not been defined. Edit: The problem has been solved but now it’s another problem in which after choosing the numbers the program doesn’t do the math and simply ends.

y = input('.:')

n1 = float(input("Primeiro Número "))
n2 = float(input("Segundo Número "))

if y == 1:
    print(n1, "+" ,n2, "=" (n1+n2))

if y == 2:
    print(n1, "-" ,n2, "=" (n1-n2))
elif y == 3:
    print(n1, "x" ,n2, "=" (n1*n2))
if Y == 4:
    print(n1, "/" ,n2, "=" (n1/n2))
calc()
  • In the last if, y is uppercase. python is case sensitive, so it interprets it as a new variable, which has not yet been defined.

  • Ah, it makes sense, thanks for the help, I hadn’t noticed

  • Solved this error, but now there is another problem... After choosing the numbers the application does not do the math, the app simply ends.

  • @Nuckhouse Probably the program ends and the window immediately closes without giving time to see the result. Try to put a input() at the end, after all the y.

1 answer

1

At last if its variable is Y uppercase. In Python, there are differences between uppercase and minuscule letters in variable names. That’s why he says that Y there is no - usey.

Another thing wrong there is that the return of input always is a string - when you ask for the numbers that will be the operands, you call float on the return of input, and this will convert them into numbers: ok. But when you ask for the desired operation, you leave it as it is, and we if below, compare the input value with integer numbers: the result will always be False. You must either convert the entered value to integer by calling int, or compare it with strings, putting the values right in the == in quotes in "if". (ex.: if y == "1":)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.