import operator
num1 = float(input("Enter first number: "))
operation = ("")
ops = {
"+" : operator.add,
"_" : operator.add,
"*" : operator.mul,
"/" : operator.div
}
while operation != ops:
operation = input("Enter operator: ")
print("false entry")
num2 = float(input("Enter second number:"))
result = (float(num1) + ops + float(num2))
print(result)
I'm trying to make the operator, if the input is not a operator, repeat and ask to retype is until it is equal to one of the operations listed in the dictionary.
I only started coding like 4 days ago and don't really know what the problem is. I'd be happy if anyone could help me.
Nice try! There are a few problems here...
In ops, you should change the second key/value pair to include subtraction, maybe you are looking for something like this:
ops = {
"+" : operator.add,
"-" : operator.sub,
"*" : operator.mul,
"/" : operator.div
}
When asking for the operator, you must check if operator is in ops keys. You are now checking if operator is equal to ops dictionary. As pointed out by #Ayam It could be something like this:
operation = input("Enter operator: ")
while operation not in ops:
print("false entry")
operation = input("Enter operator: ")
Finally, there is a problem when making the calculation. Once you have the operation and you are sure it is in ops keys, you can use the value (in this case, a function) linked to that key:
result = ops[operation](num1, num2)
print('result is', result)
Hope this helps! Keep learning! :)
You are close! Try this:
operation = input("Enter operator: ")
while operation not in ops:
print("false entry")
operation = input("Enter operator: ")
What goes wrong in your code is that the operation variable is compared to the dictionary called ops. By checking 'operator in ops' you check if operator corresponds to one of the keys of ops.
try this:
import operator
num1 = float(input("Enter first number: "))
operation = ("")
ops = {
"+" : operator.add,
"_" : operator.add,
"*" : operator.mul,
"/" : operator.truediv
}
while operation not in ops:
operation = input("Enter operator: ")
if(operation not in ops):
print("false entry")
num2 = float(input("Enter second number:"))
result = (ops.get(operation)(float(num1),float(num2)))
print(result)
Few changes:
while operation != ops: is comparing a string to a whole dict so extract the keys out first and then compare
while operation not in ops:
You only print "False entry" if operation is not valid so:
if(operation not in ops):
print("false entry")
Why are you adding the dict and the 2 values here
result = (float(num1) + ops + float(num2))
You want to use the operator function. The value part of the dict so you have to extract it with dict.get(key). Also the operator functions requires both the argument so do this:
`result = (ops.get(operation)(float(num1),float(num2)))`
Example:
ops.get("+")(2,2) returns operator.add(2,2) = 4
import operator
num1 = float(input("Enter first number: "))
ops = {"+" : operator.add, "_" : operator.add,"*" : operator.mul,"/" : operator.truediv}
operation = input("Enter operator: ")
while True:
if operation not in ops:
print("Wrong input")
operation=input("Enter operator: ")
else:
break
num2 = float(input("Enter second number:"))
result = ops[operation](num1, num2)
print('result is', result)
Related
I'm very very veryy new to python and coding in general. I'm still learning the very basics, but I'm also trying to just play around and try out different things in python. I have tried making a very basic calculator that can +, -, *, /, take a number to the power of another number, and take the square root of 1 number.
Only thing I don't know how to do is skip the third input with num2, when I put in operator "sqrt" so I only take the sqrt of num1. Also I want to tell the user that if they put in an input for num1 that is less than 0 then they get an error.
Idk if I need to learn more to do something like this? I haven't learned about loops yet so I'm still very very new. Hope I can get some helps
#Making a basic calculator
from math import*
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
elif op == "^":
print(pow(num1,num2))
elif op == "sqrt":
print(sqrt(num1))
elif op == "sqrt" and num1 <= 0:
print("You cannot take the square root of numbers smaller than 0")
else:
print("Invalid operator")
The simplest thing to do is check what op is and only ask for num2 if you need it:
op = input("Enter operator: ")
if op != "sqrt":
num2 = float(input("Enter second number: "))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new to python, just started learning, and wanted to test my skills by building a simple arithmetic calculator. I've tied up most loose ends in my code, but don't know how to provide an error message and new input line to the user when they place a letter/word in the input line for numbers. Again, I'm very new to python and have no idea how to fix this. Also curious about how ugly my code looks. Any advice is appreciated, thanks.
print("Welcome to the Basic Python Calculator!")
def calculator():
num1 = input("Name your first number: ")
num2 = input("Name your second number: ")
operator = input("Name an operation. Add, Subtract, Multiply, or Divide. (Match Capitalization)\n")
while operator != "Add" and operator != "Subtract" and operator != "Multiply" and operator != "Divide":
operator = input("Name an operation. Add, Subtract, Multiply, or Divide. (Match Capitalization)\n")
if operator == "Add":
result = float(num1) + float(num2)
print(num1 + " + " + num2 + " = " + str(result))
elif operator == "Subtract":
result = float(num1) - float(num2)
print(num1 + " - " + num2 + " = " + str(result))
elif operator == "Multiply":
result = float(num1) * float(num2)
print(num1 + " ● " + num2 + " = " + str(result))
elif operator == "Divide":
result = float(num1) / float(num2)
print(num1 + "/" + num2 + " = " + str(result))
calculator()
You can do this by using a try/catch block along with a while loop. So when you want to take number input, do this
while true:
user_input = input("Enter a number")
try:
user_input_number = int(user_input)
break
except:
print("ERROR")
print(user_input_number)
You can simply use isnumeric() (i.e num1.isnumeric(), num2.isnumeric()) to see if you have a number or not. and using that you'll know how to deal with the input. You won't need a try catch, although having one would be a good idea.
Side note for floats: for float strings, one quick way could be to remove . and check the resulting string with isnumeric to know if you are dealing with numbers
i'm quite new at Python and I wondered how to make a calculator that i can add, subtract, multiply, divide and other operators on more than two numbers . I would be thankful if you gave me an explanation. I'm questioning because I have in my mind an awful and inefficient method of doing this , that being adding more elif tags for more operators and more numbers
TL:DR (i guess) :
i thinked about making a calculator made with python that has options for more operator and numbers ( but i don't know how to make a simpler one :
i.e.:30 + 30 * 30.
67.874 / 20.
69 + 69 + 69 + 69 + 69 + 69.
30 ** ( i think this is a power operator ) 2.
etc.
I can help you if you didin't understand what i want , you can question me
this is my normal calculator without input of more than two numbers and one operator
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
num1 = float(input("Enter a number :"))
op = input("Enter your selected operator :")
num2 = float(input("Enter another number :"))
if op == "+":
print(num1, "+", num2, "=", add(num1, num2))
elif op == "-":
print(num1, "-", num2, "=", subtract(num1, num2))
elif op == "*":
print(num1, "*", num2, "=", multiply(num1, num2))
elif op == "/":
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid input")
I know this comment/answer code isn't having indenting , but stack woudn't let me post with indenting and the file itself does have indenting so idk
result = None
operand = None
operator = None
wait_for_number = True
while True:
if operator == '=':
print(f"Result: {result}")
break
elif wait_for_number == True:
while True:
try:
operand = float(input("Enter number: "))
except ValueError:
print("Oops! It is not a number. Try again.")
else:
if result == None:
result = operand
else:
if operator == '+':
result = result + operand
elif operator == '-':
result = result - operand
elif operator == '*':
result = result * operand
elif operator == '/':
result = result / operand
break
wait_for_number = False
else:
while True:
operator = input("Enter one of operators +, -, *, /, =: ")
if operator in ('+', '-', '*', '/', '='):
break
else:
print("Oops! It is not a valid operator. Try again.")
wait_for_number = True
your question isn’t clear enough, but if I got it right than this should work. Important to note: using the eval() function is not a good practice since it can be really dangerous if the inputs are not coming from you. Here are some of the dangers of it: https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
The code:
# the function takes an operator as a string like: “*” and multiple numbers thanks to the * (args) operator.
def calculate(operator, *numbers):
result = numbers[0]
#the for cycle goes through all numbers except the first
for number in range(1, len(numbers)):
#the eval() function makes it possible to python to interpret strings as a code part
result = eval(f"{result} {operator} {str(numbers[i])}")
print(result)
Here is the code without eval().
import operator
# the function takes an operator as a string like: “*” and multiple numbers thanks to the * (args) operator.
def calculate(op, *numbers):
# binding each operator to its string counterpart
operators = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
result = numbers[0]
#the for cycle goes through all numbers except the first
for number in range(1, len(numbers)):
# carrying out the operation, using the dictionary above
result = operators[op](result, numbers[number])
print(result)
This question already has answers here:
assign operator to variable in python?
(5 answers)
Closed 1 year ago.
I am new to python and was trying to write something like this below (code A) so it does eactly like code B. I want to make use of user input of mathematical operators as do_what variable. How can we write this code (A) in python so it would work like code B?
code A
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter a calculation symbol for calculation you want to perform: ")
result = float(num1) do_what float(num2)
print("result is: " + str(result))
code B
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = int(num1) + int(num2)
print("result is: " + str(result))
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))
You might also be interested in knowing about the inbuilt function eval. This reduces the if and else loops to a single statement for this particular example of yours
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")
result = eval(num1 + do_what + num2)
print("result is: %s" %result)
# Enter a number: 3
# Enter another number: 18
# Enter calculation symbols for calculation you want to perform: *
# result is: 54
EDIT
To make eval slightly safe in this particular case, you can perhaps use something like this
if do_what in ['+', '-', '*', '**', '/']:
result = eval(num1 + do_what + num2)
print("result is: %s" %result)
else:
print ("Enter an arithmetic operator")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")
if do_what=='+':
result = float(num1) + float(num2)
elif do_what=='-':
result = float(num1) - float(num2)
elif do_what=='*':
result = float(num1) * float(num2)
elif do_what=='/':
result = float(num1) / float(num2)
print("result is: " + str(result))
If security is not your concern you could use eval to achieve this
result = eval(str(num1) + do_what + str(num2))
The problem is that eval literally evaluates everything you write as python code, so don't do this if you mean for this to be used by others
I want to make python ask questions to the user - from random variables in lists.
It needs to ask the question requiring an input from the user.
This is my code so far:
import time
import random
question = "0"
score = "0"
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz")
time.sleep(2)
numbers = list(range(1, 50))
operators = ["+", "-", "*"]
numbers1 = list(range(1,10))
print(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers1)))`
How would I make the last line of code ask a question and get an input from the user?
Also how would I make it so that python says whether this is correct when I do not know what python will ask?
The answer is already in your code.
user_input = input(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers)) + "? ") should work.
It gets a sample random number from numbers, gets a random operator from operators, gets another random number from numbers, and stores the input to the variable user_input.
To get Python to check your answer, store the randomly generated arguments inside variables and check them. (If there is a better way of doing this, I would appreciate it if someone pointed it out to me).
operand1 = random.choice(numbers)
operand2 = random.choice(numbers)
operator = random.choice(operators)
if operator == '+':
answer = operand1 + operand2
elif operator == '-':
answer = operand1 - operand2
else:
answer = operand1 * operand2
user_input = input(str(operand1) + operator + str(operand2) + "? ")
if str(answer) == user_input:
print('Correct!')
else:
print('Wrong!')
EDIT: #mhawke's answer has a better way of storing and manipulating the operands. Instead of storing the operators in a list, store them in a dict and map them to their corresponding operator function as so:
import operator
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul}
operand1 = random.choice(numbers)
operand2 = random.choice(numbers)
op = random.choice(operators)
expected_answer = op(operand1, operand2)
Documentation for operator.
For the second part of your question, how to determine whether the user entered the correct answer, you can store the randomly selected values and evaluate the resulting expression. Then compare that to the user's value:
import operator
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul}
operand1 = random.choice(numbers)
operand2 = random.choice(numbers1)
op = random.choice(operators)
expected_answer = op(operand1, operand2)
user_answer = input('{} {} {} = ?: '.format(operand1, op, operand2)
if int(user_answer) == expected_answer:
print('Correct!')
else:
print('Wrong. The correct answer is {}'.format(expected_answer)
The operators are stored in a dictionary. The operator tokens (+, -, *) are the keys in this dictionary, and the values are functions from the operator module that perform the operations. Using a dictionary like this is very flexible because if you wanted to support a new operator, e.g. division, you can just add it to the operators dictionary:
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, '/': operators.div}