0

I'm a beginner in Python and I can't figure out the assignment of an operator to a variable.

I've read assign operator to variable in python? but I still can't figure out my problem.

a = str(+) This line of code gives an Invalid Syntax Error.

Whereas, a =input() works completely fine when we give an operator as input. This operator is stored as string type because whatever you enter as input, input function converts it into a string.

Why str() is not able to store an operator as a string whereas input() can do the same task without any error?

2
  • 2
    But the user isn't giving an operator as input. The user is giving a string, "+", which merely happens to resemble the addition operator. It's a use-mention distinction sort of thing. Commented Sep 17, 2019 at 13:29
  • For your situation, you should be able to just do this: a = "+" Commented Sep 17, 2019 at 13:32

3 Answers 3

2

Based on the other post, you'd have to do

import operator
a = operator.add

The answer there just does a lookup in a dictionary

You're not giving an operator to input(), you're always inputting and outputting a string, which could be any collection of characters & symbols

Sign up to request clarification or add additional context in comments.

4 Comments

I'm almost certain the OP does not want a = '<built-in function add>', a string representation of a built-in function.
a = operator.add, though, may be a possibility.
Actually I'm trying to write a function to design a calculator which takes two values and an operator in the form of variable as an argument. The operation is performed on the values on the basis of the operator received, but I was not able to store the operator in a variable.
You can just store the characters, then compare and do the appropriate ops. There's several ways to handle it martinbroadhurst.com/shunting-yard-algorithm-in-python.html
2

+ is not an identifier or value of any kind; it is part of Python's syntax. You probably want a = str("+") (or simply a = "+").

input doesn't take a value; whatever environment you are running in already takes care of converting your keystrokes to strings for input to read and return.

If you want a to be a callable function, then you can use operator.add as mentioned in @cricket_007's answer (though not passed through str, but used directly per my comment to that answer).

2 Comments

The call to str() doesn't do anything here -- it's passed a string and returns the same string
True; I'll adjust that.
0

To add to the above answers you can validate the input as an integer:

while True:
    try:
       userInput = int(input('Enter a number:> '))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.