Assign Operator to Variable in Python

assign operator to variable in python?

You can use the operator module and a dictionary:

import operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
}
op_char = input('enter a operand')
op_func = ops[op_char]
result = op_func(a, b)

How to store and use mathematical operators as python variable

You can use the operator module for common operators and make a lookup dictionary to map symbols to functions. If you want operators not in that module, you can simply define custom functions and add look them up the same way:

import operator

operatorlookup = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")

op = operatorlookup.get(do_what)

if op is not None:
result = op(float(num1), float(num2))
else:
result = "Unknown operator"
print("result is: " + str(result))

Assigning operator to a variable in Python

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

How to make an operator variable?

Use len() to count the number of characters in n:

while True:
current_number = int(input("Enter the number that you wish to be displayed: "))
print(f"The current displayed number is: {current_number}")
n = input()
if set(n) == {"+"}:
print(current_number + len(n))
elif set(n) == {"-"}:
print(current_number - len(n))
Enter the number that you wish to be displayed: 37
The current displayed number is: 37
+++++
42

Note that with this approach there's no need to arbitrarily limit the number of characters, although you can still do that explicitly by rejecting inputs where len(n) > 5.

Your original version of the check for if the string contains all "+" or "-" doesn't work:

if n == "+" or "++" or "+++" or "++++" or "+++++":

because (n == "+") or ("++") will simply return "++" (which is true) if n == "+" is not True. A "correct" way to write this check would be:

if n in ("+", "++", "+++", "++++", "+++++"):

or more simply (since these specific strings are all substrings of "+++++":

if n in "+++++":

My version of the code does this instead:

if set(n) == {"+"}:

which works by converting n to a set (reducing it to only the unique characters) -- if n contains all "+"s, then its set is {"+"}. This works for any length of n.

logical operators 'or' and 'and' in variable python

and and or are operators, like + and -, and cannot be assigned to variables. Unlike + et al., there are no functions that implement them, due to short-circuting: a and b only evaluates b if a has a truthy value, while foo(a, b) must evaluate both a and b before foo is called.

The closest equivalent would be the any and all functions, each of which returns true as soon as it finds a true or false value, respectively, in its argument.

>>> any([1+2==3, 3+1==5])  # Only needs the first element of the list
True
>>> all([3+1==5, 1+2==3]) # Only needs the first element of the list
False

Since these are ordinary functions, you can bind them to a variable.

if True:
logical_obj = any
else:
logical_obj = all

if logical_obj([1 + 2 == 3, 3 + 1 == 5]):
pass

The list has to be fully evaluated before the function can be called, but if the iterable is lazily generated, you can prevent expressions from being evaluated until necessary:

>>> def values():
... yield 1 + 2 == 3
... print("Not reached by any()")
... yield 3 + 1 == 5
... print("Not reached by all()")
...
>>> any(values())
True
>>> all(values())
Not reached by any()
False

assigned = or == or == to variables python django

Yes, you can use the operator library: (You'll obviously have to use a different name than operator for the variable in that case!) Usage would be like the below (only the significant lines shown to give you the idea):

import operator
...
if age <= 11
compare_function = operator.le
...
[...
if compare_function(info.age, age):
...]

Or if you don't want to import that for some reason, it's not too hard to define these on your own with lambda functions, eg:

if age <= 11:
operator = lambda a, b: a <= b

And use as

if operator(info.age, age)

inside your list comprehension.

Python conditional assignment operator

No, the replacement is:

try:
v
except NameError:
v = 'bla bla'

However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:

try:
v = complicated()
except ComplicatedError: # complicated failed
v = 'fallback value'

and never be unsure whether v is set or not. If it's one of many options that can either be set or not, use a dictionary and its get method which allows a default value.



Related Topics



Leave a reply



Submit