I am building a basic calculator on python to get to know the basics of programming and what not. Basically my issue is that when I am squaring a number with my calculator it will still ask for my second number, while it spits out the correct answer still I would like it to not ask for my second number when the square function is used.
name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: "))
if Component == "*":
print(num1 * num2)
if Component == "+":
print(num1 + num2)
if Component == "/":
print(num1 / num2)
if Component == "-":
print(num1 - num2)
if Component == "sqr":
print(num1 ** 2)
try this num2 = float(input("Enter your last number...: ")) if Component.strip() != "sqr" else 0 instead.
Full code here:
name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: ")) if Component.strip() != "sqr" else 0
if Component == "*":
print(num1 * num2)
if Component == "+":
print(num1 + num2)
if Component == "/":
print(num1 / num2)
if Component == "-":
print(num1 - num2)
if Component == "sqr":
print(num1 ** 2)
Related
I am building a calculator and I want to know if i can make num2 input be skipped when "root" option is chosen.
This is my code:
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
if op not in operators:
print("Invalid operator")
start()
num2 = float(input("Enter a 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 == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
I want this to get ignored:
num2 = float(input("Enter a number: "))
When this is the case:
elif op == "root":
print(math.sqrt(num1))
Put the second number input statement behind an if:
op = input("Enter a operator: ")
if op != "root":
num2 = float(input("Enter a number: "))
To do this, you could do:
if op != "root":
num2 = float(input("Enter a number: "))
This would skip the num2 input if op == "root"
There can be many different ways. One suggestion would be as below.
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
# HERE
if op != "root" and op in operators:
num2 = float(input("Enter a number: "))
elif op not in operators:
print("Invalid operator")
start()
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 == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
or
# HERE
if op in operators:
if op != "root":
num2 = float(input("Enter a number: "))
else:
print("Invalid operator")
start()
Here are the instructions I received for my assignment:
4) Add the following function into Mylib
scalc(p1)
p1 will be a string like this "N1, N2, operator"
examples
scalc("20,30,*")
the result will be 600
scalc("50,20,+")
the result will be 70
scalc("50,20,-")
the result will be 30
scalc("60,20,/")
the result will be 30
use string functions to parse the first number, the second number, and the operator from the input string.
use the prior functions (add, subtract, divide and multiply ) to do the calculations.
And here is my attempt that is not working. I have the add() sub() mult() div() functions, I'm just not showing them here.
I know it's something very simple that likely has to do with where I call the function scalc(p1). What is the proper way to do that?
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[3] == "+":
add()
elif astring[3] == "-":
sub()
elif astring[3] == "*":
mult()
elif astring[3] == "/":
div()
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
EDIT: Here is the Answer. I did not have arguments being passed to my functions. By adding num1 and num2 to every instance of my arithmetic functions, they were able to receive the new variable values.
#Define the main program function
def main():
#Define input function
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
print("You must enter a number!")
else:
break
#Declare variables
rangeLower = float_input("Enter your Lower range: ")
rangeHigher = float_input("Enter your Higher range: ")
num1 = float_input("Enter your First number: ")
num2 = float_input("Enter your Second number: ")
#Define formula functions
def add(num1, num2):
sum = num1 + num2
print("The Result of",num1,"+",num2,"=", sum)
def sub(num1, num2):
diff = num1 - num2
print("The Result of",num1,"-",num2,"=", diff)
def mult(num1, num2):
product = num1 * num2
print("The Result of",num1,"*",num2,"=", product)
def div(num1, num2):
if num2 == 0:
print("The Result of",num1,"/",num2,"= You cannot divide by Zero")
else:
quotient = num1 / num2
print("The Result of",num1,"/",num2,"=", quotient)
#If-else
if num1 < rangeLower or num1 > rangeHigher or num2 < rangeLower or num2 > rangeHigher:
print("The input values are outside the input ranges.")
print("Please check the number and try again.")
print("Thanks for using our calculator")
else:
#Call functions
add(num1, num2)
sub(num1, num2)
mult(num1, num2)
div(num1, num2)
print("Thanks for using this calculator!")
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1, num2)
elif astring[2] == "-":
sub(num1, num2)
elif astring[2] == "*":
mult(num1, num2)
elif astring[2] == "/":
div(num1, num2)
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
This does it. There were a couple errors. First, in Python you start counting at 0, so you wanted to use astring[2] instead of astring[3]. Also you needed a value to be returned:
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1,num2)
elif astring[2] == "-":
sub(num1,num2)
elif astring[2] == "*":
mult(num1,num2)
elif astring[2] == "/":
div(num1,num2)
return value
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
Example:
input: "20,30,+"
Out[2]: 50.0
I got to do this calculator on python 3 that must execute on loop until the user types exit. Besides, programming ahead of the user typing invalid characters, such as letters when asked to type an operator or a number.
I must use while, if... However, I cannot use import.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator != "+" or "-" or "*" or "/":
print ("You must enter an operator")
break
no1 = input("Enter a number: ")
no2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else :
output = int(num1) / int(num2)
print("The result is " + str(result))
print("See you soon!")
I expect it to actually not stop when we enter anything but an operator, I want it to loop back to:
operator = input("Give me an operator or \"exit\" to stop : ")
You will find below this your code that work as expected, however lets start with general rules.
Be attentif, when you declare a variable, use the same elsewhere in your code.
Test, simple part of your code before trying to do a script. You condition to test operator was totally broken.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: #<== here you condition is wrong ,do this instead
print ("You must enter an operator")
continue
try:
num1 = int(input("Enter a number: ")) #
num2 = int(input("Enter a number: ")) # <== both of this variable are not use else where ,rename to be consitdnt with the rest of your code
except ValueError:
print("Please enter an integer")
if operator == "+":
output = num1 + num2
elif operator == "-":
output = num1 - num2
elif operator == "*":
output = num1 * num2
else :
output = num1 / num2
print("The result is " + str(output)) #<=== here also, results was not defined
print("See you soon!")
Put a generic else statement which will continue with the next iteration.
if condition1 :
//logic
elif condition2 :
//logic
else:
continue
Your problem is that you are doing:
if operator != "+" or "-" or "*" or "/":
And what that is really doing, is that:
if operator != "+" or 45 or 42 or 47: (ASCII representation of these characters)
What this means, is that the condition is true no matter what, because or n where N is not 0, would pass any time.
You want:
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
You want an AND gate.
Also, I noticed you are saying no1 = input(...) then doing int(num1) instead of int(no1).
As for jumping back to input, you use continue
Final code:
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output)) # this was previously str(result) but result is was not defined
print("See you soon!")
BUT! if you are feeling new today, you can use the walrus operator introduced in PEP 572 and available from python 3.8
while (operator := input("Give me an operator or \"exit\" to stop : ")) != "exit":
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output))
print("See you soon!")
EDIT:
Edited the final code to use continue, previous version was.
Also added a python 3.8 implementation.
EDIT2:
Just correcting some stuff, making sentences truer.
new to coding and lots of the vernacular is not yet under my belt.
I was practicing some very basic stuff, and I created a new project after finishing the last exercise. All the code looks good and should work, but I'm getting an error that is quoting code from the previous exercise. Am I missing something?
Here's the code I'm trying to execute:
# Enter Calculation: 5 * 6
# answer should be 30
num1, operator, num2 = raw_input('Enter calculation:').split()
num1 = int(num1)
operator = int(operator)
num2 = int(num2)
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-":
print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == "*":
print("{} * {} = {}".format(num1, num2, num1 * num2))
elif operator == "/":
print("{} / {} = {}".format(num1, num2, num1 / num2))
And when I enter 5 * 6 it brings up this error message:
Traceback (most recent call last):
File "C:\Users\Rocky\PycharmProjects\PythonTutorial.py\pythontut.py", line
5, in <module>
miles = float(raw_input('Enter a number: '))
ValueError: invalid literal for float(): 5 * 6
The code for this previous exercise is:
# Problem: Receive miles and convert to kilometers
# Kilometers = miles * 1.60934
# Enter miles 5
# 5 miles = 8.04
miles = float(raw_input('Enter a number: '))
def kilo_conversion(miles):
if miles > 0 or miles < 0:
conversion = miles * 1.60934
print 'Your distance of {} miles in kilometers is: {}'.format(miles,
conversion)
else:
print 'Nice. Try again with a number greater than zero!'
kilo_conversion(miles)
operator variable can't be typecasted to int. Try removing that line.
num1, operator, num2 = input('Enter calculation:').split()
num1 = int(num1)
num2 = int(num2)
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-":
print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == "*":
print("{} * {} = {}".format(num1, num2, num1 * num2))
elif operator == "/":
print("{} / {} = {}".format(num1, num2, num1 / num2))
GOT IT! Thanks for the help, guys. I just closed everything and copy/pasted the code into a new project. I think I just needed to clear the air. Still getting an error message, but at least it pertains to the code in the window. Thanks again :)
I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
I am not able to do two operations at once either.
Use functions from the operator module or simple functions you define yourself to the calculation work, then map the operation name from the queencommand string to those functions:
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
operator.add could be replaced by lambda a, b: a + b, etc. if you don't want to use a module for those operations.
Here is a fully fledged calculator. See if it helps:
def multiplication():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 * num2
print(ans)
def addition():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 + num2
print(ans)
def subtraction():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 - num2
print(ans)
def division():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 / num2
print(ans)
def Help():
print("""Welcome to Calculator P1!!!
Type "x" for multiplication.
Type "+" for addition.
Type "-" for subtraction.
Type "/" for division.""")
while True:
print("Type 'help' for introduction or instructions")
choice = input("Operator: ")
if choice == "x" or choice == "muliplication":
multiplication()
elif choice == "+" or choice == "addition":
addition()
elif choice == "-" or choice == "subtraction":
subtraction()
elif choice == "/" or choice == "division":
division()
elif choice == "help":
Help()
answer = input('Run again? (y/n): ')
if answer == 'n':
break
elif answer == 'y':
continue
else:
print("""Unrecognized Input.
<<<<RESTARTING PROGRAM>>>>""")
continue