If statements printing after a variable is entered - python

I'm new to programming/coding and I'm using Python in my course. I have been asked to create a calculator that can add, subtract, divide and multiply. I'm trying to get the program to receive the numbers through input, then ask for what to do with it (eg. plus or minus) through a number entered and then give a result. I have the input stages of the code working but when I get to the last part I cant get it to work. This is the code
FirstNumber = "blank1"
SecondNumber = "blank2"
Device = "blank3"
FirstNumber = input("First number?")
SecondNumber = input("Second number?")
Device = input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide.")
if "Device" == 1:
print("FirstNumber"+"SecondNumber")
When it gets the the end it does nothing, help please.

The condition "Device" == 1 will always be False because no string is equal to an integer. You probably want to change it to Device == 1, but this will (likely) still fail because on python3.x, input returns a string. You probably want something like:
Device = int(input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide."))
if Device == 1:
print(FirstNumber + SecondNumber)
Of course, for the same reason, you'll probably also want to convert FirstNumber and SecondNumber into some numeric type ...

ops = {
"+": lambda a,b: a+b,
"-": lambda a,b: a-b,
"*": lambda a,b: a*b,
"/": lambda a,b: a/b
}
a = int(input("Please enter the first number: "))
op = input("Please enter an operator: ")
b = int(input("Please enter the second number: "))
print("{} {} {} == {}".format(a, op, b, ops[op](a,b)))

Related

How to restart a programm if input is invalid python

first project beginner here! I just finished my first project, a somewhat working calculator i know it is not that great but as i said beginner. I would like to limit the options for number = input meaning if you write anything else than add,substract,divide or multiply you receive an error like " please try again" and afterwards the programm is restarted
Help very much appreciated Thank you.
list = ("add", "substract", "divide" , "multiply" )
number = input("do you want to add substract divide or multiply? ")
if number in list:
print("ok")
else:
print("try again")
number_one = float(input("enter your first number "))
number_two = float(input("enter your second number "))
if number == "add":
solution_one = number_one + number_two
print(solution_one)
if number == "substract":
solution_two = number_one - number_two
print(solution_two)
if number == "divide":
solution_three = number_one / number_two
print(solution_three)
if number == "multiply":
solution_four = number_one * number_two
print(solution_four)
i could only find solutions regarding while loops but i did not know how to use them in this case as these weren't strings but integers.
The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.
while True:
number = input("do you want to add substract divide or multiply? ")
if number in ("add", "substract", "divide" , "multiply" ):
print("ok")
break
print("try again")
Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!
You could consider using the operator module.
Build a dictionary that maps the user's selected operation with the relevant function.
import operator
OMAP = {
'add': operator.add,
'subtract': operator.sub,
'divide': operator.truediv,
'multiply': operator.mul
}
while (op := input('Do you want to add, subtract, multiply, divide or end? ')) != 'end':
try:
if (func := OMAP.get(op)):
x = float(input('Enter your first number: '))
y = float(input('Enter your second number: '))
print(func(x, y))
else:
raise ValueError(f'"{op}" is not a valid choice')
except ValueError as e:
print(e)

Is this an efficient calculator in Python?

Is this an efficient calculator in Python?
def calculator():
print("\nBasic Calculator.\n")
num_1 = input("Enter your first number: ")
operation = input("Enter your operation: ")
num_2 = input("Enter your second number: ")
if operation == ("+"):
sum = float(num_1) + float(num_2)
print ("The answer is:",(sum))
elif operation == ("-"):
sum = float(num_1) - float(num_2)
print ("The answer is:",(sum))
elif operation == ("*"):
sum = float(num_1) * float(num_2)
print ("The answer is:",(sum))
elif operation == ("/") and num_2 == ("0"):
print ("\nYou cannot divide by zero.")
elif operation == ("/"):
sum = float(num_1) / float(num_2)
print ("The answer is:",(sum))
else:
print("Invalid Operation.")
restart = input("\nDo you want to enter another equation? Yes or No?").lower()
if restart == ("yes"):
calculator()
else:
print ("\nEnding Program.")
quit()
calculator()
You can use eval()
a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))
0.5
Handle shenanigans by users:
a = 1
b = 0
operation = '/'
try:
print(eval(f'{a} {operation} {b}'))
except Exception as exp:
print(exp)
Here is another basic example:
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
try:
x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
if sign == '0':
break
else:
print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
print("Something went wrong, check your input")
It's decent, but reviews of working code belong on CodeReview.SE, not here.
Call the result variable result instead of sum, that obviously only is meaningful for addition.
As per AlexanderLekontsev's answer, you don't need a huge big if...else ladder that always computes result and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and default arg2=None, that way you can handle unary functions.
You're assuming the user types in valid floats in response to num_1, num_2. But what if they press return? or type pi or e? or 'help' or :-D etc. You should catch the exception ValueError: could not convert string to floatand display the user's invalid input back to them, "expected a number"(/"operator").
You only need num_2 if operation is a binary not a unary operation, but future stuff like sqrt, log, log10, trigonometrics (sin, cos, tan), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence.
Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal 7e8 and float/general/exponential notation 7e8? You might need multiple try...except clauses. You might add a HEX mode in future. But then you'll need to generalize from num1 to say arg1, and if arg1 == HEX then enable(/toggle) hex mode, and recurse/loop.
Suggest printing print("Invalid Operation: must be +,-,*,/,..."), this actually tells the user which operations are legal. So: % isn't, neither is ^, neither is log, cos, sqrt etc.
So if you implement the above, you can support things like e^x
Supporting parentheses would require recursion.
Try this:
def calculate(num1, num2, operator):
operator = operator.strip()
if operator.strip() in ['+', '-', '*', '/']:
if operator == '/' and eval(num2) == 0:
return None
try:
result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
except:
return ""
return result
num1 = '3'
num2 = '5'
operator = '+'
result = calculate(num1, num2, operator)
if result == '':
print('Wrong expression !')
elif result == None:
print('Dive bye zero !')
else:
print(f'The answe is {result} !')
Your code is alright but we can improvise by using eval()
print(" Basic Calculator ")
i = ""
while i != 'exit':
i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
print(eval(i))
Here is a very clean and short calculator script:
num1 = float(input("Enter a number: "))
op = (input("Enter an operation: "))
num2 = float(input("Enter another number: "))
if op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "^":
print(num1 ** num2)
else:
print("error, you did not enter a supported operation")
Also if you were wondering ** means ^ or to the power of.
Try this:
this calculator will take several inputs, and you can choose to clear the values or to delete it before computing the result.
values_collector = [] #empty list for all values
multi = 1
total = 0
index = 0
print('''For addition press the +,
For Subtraction press the -
For division press the /
For Multiplication press the *''')
entries = int(input('Enter the number of the values you want to compute: '))
signs = input('Enter the sign: ')
while index < entries:
my_input = int(input('Enter your values: '))
values_collector.append(my_input)
index +=1
to_remove = input('Do you want to remove any values, enter Y for yes and N for no ').upper()
if to_remove == 'Y':
values_re=[]
x = 0
no_to_remove = int(input('How many variables do you want to remove: '))
while x < no_to_remove:
my_removed = int(input('Enter your values: '))
values_re.append(my_removed)
x +=1
for y in values_re:
values_collector.remove(y)
my_clear = input("Do you want to clear all the values press Y for yes and N for No ").upper()
if my_clear == 'Y':
values_collector.clear()
print('There is no values to compute because its cleared')
elif my_clear == 'N':
if signs == '+':
for x in range(len(values_collector)):
total +=values_collector[x]
elif signs == '-':
for x in range(len(values_collector)):
total -=values_collector[x]
elif signs == '*':
for x in range(len(values_collector)):
multi *=values_collector[x]
total = multi
elif signs == '/':
for x in range(len(values_collector)):
multi /=values_collector[x]
total = multi
print('The computation of all the values {} is {}'.format(values_collector, total))
enter code here

Issue in providing special character as input in python [duplicate]

I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.

Python ask for user input without a newline?

I just started python a few days ago and have been working on a calculator (not extremely basic, but also not advanced). The problem doesn't prevent code from running or anything, it is just a visual thing.
Output in the console looks like this (stuff in parenthesis is explaining what is happening and is not actually part of the output):
4 (user prompted for first number, press enter afterwards)
+ (user prompted for an operator, press enter afterwards
5 (user prompted for second number, press enter afterwards)
9.00000 (answer is printed)
Process finished with exit code 0
Basically what I want it to look like is this when I'm entering it into the console:
4+5
9.00000
I don't want it to start a newline after I enter a number or operator or whatever, it looks more like an actual calculator when it prints along one line. Is this possible to do and if so how? Btw I know end="" works with print but not with input since it doesn't accept arguments. Also I know the whole calculator thing is kind of redundant considering you can make calculations really easily in the python IDLE but I thought it was a good way for me to learn. Here is the entire code if you need it:
import math
while True:
try:
firstNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
while True:
operators = ['+', '-', '*', '/', '!', '^']
userOperator = str(input())
if userOperator in operators:
break
else:
print("Enter a valid operator... ", end="")
if userOperator == operators[4]:
answer = math.factorial(firstNumber)
print(answer)
pause = input()
raise SystemExit
while True:
try:
secondNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
if userOperator == operators[0]:
answer = firstNumber + secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[1]:
answer = firstNumber - secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[2]:
answer = firstNumber * secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[3]:
answer = firstNumber / secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[5]:
answer = firstNumber ** secondNumber
print('%.5f' % round(answer, 5))
pause = input()
raise SystemExit
Your problem is that you're asking for input() without specifying what you want. So if you take a look at the first one: firstNumber = float(input()) It's executing properly, but you hit enter it gives an error which is only then you're specifying what you want.
Try replacing with these:
...
try
firstNumber = float(input("Please enter a number... "))
...
userOperator = str(input("Enter a valid operator... "))
...
secondNumber = float(input("Please enter a number... "))
Is that what you're looking for?
Using my method I suggested:
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
Using your method:
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
Extra newlines which is what I'm assuming you're referring to.
That's a nice exercise, and as I wrote in the comments, I would ignore whitespaces, take the expression as a whole from the user and then parse it and calculate the result. Here's a small demo:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def calc(expr):
if is_number(expr):
return float(expr)
arr = expr.split('+')
if len(arr) > 1:
return sum(map(calc, arr))
arr = expr.split('-')
if len(arr) > 1:
return reduce(lambda x,y: x-y, map(calc, arr))
arr = expr.split('*')
if len(arr) > 1:
return reduce(lambda x,y: x*y, map(calc, arr), 1)
arr = expr.split('/')
if len(arr) > 1:
return reduce(lambda x,y: x/y, map(calc, arr))
print calc("3+4-2 *2/ 2") # 5

How can i reverse the output in my binary adder?

So im trying to create a simple program that will add two binary strings together, im almost done but the output it creates is reversed, how would i implement a way to reverse it in my code? I want to remove the "ob" at the start of the output as well.
repeat = True
while repeat==True:
num1 = input("what number would you like to add ")
if num1.isdigit():
a= int(num1)
elif not num1.isdigit():
continue
a = int(num1, 2)
num2 = input("what number would you like to add to it ")
if num2.isdigit():
b= int(num2)
elif not num2.isdigit():
continue
b = int(num2, 2)
ans = bin(a+b)[2:]
print("Your addition of numbers, in binary is " + ans)
choice=input("Would you like to start again, y/n")
if choice== "y":
repeat=True
else:
print("Its not like i wanted you here or anything baka")
repeat=False
You could just reverse the string using:
ans = ans[::-1]

Categories