I'm new programmer and I am begginer, this my first time use stack overflow, I trying now to calcul a calculator calcul numbers like normal calculator, I want write something such as (" 7 - 2 * 3") and the code give the result.
The code is chaos im just begginer so please just try understand that and help me.
when you try the code input numbers and operators with space like this 5 + 5.
This the code :
from functools import reduce
question = input("Enter your calcul : ")
nums = question.split()
numbers = nums[0::2]
def calcul(num1, num2):
for x in variation:
if x == '+':
return num1 + num2
elif x == '-':
return num1 - num2
elif x == '*':
return num1 * num2
elif x == '/':
return num1 / num2
def wayy(lt):
for x in lt:
if '+' == x :
yield'+'
if '-' == x :
yield'-'
if '*' == x :
yield'*'
if '/' == x :
yield'/'
variations = [] # [ + , - , * , / ]
variation = wayy(nums)
for x in variation:
variations.append(x)
print(variations)
nm = []
for n in numbers:
n = int(n)
nm.append(n)
calcule = reduce(calcul, nm)
print(calcule)
I try coding a calculator and i have a problem i think it is in calcul function when i input the numbers the result is "None" I know the problem in function (calcul) but I dont know how I can fix it.
Only change "variation" to "variations" in the "calcul" function.
def calcul(num1, num2):
for x in variations:
if x == '+':
return num1 + num2
elif x == '-':
return num1 - num2
elif x == '*':
return num1 * num2
elif x == '/':
return num1 / num2
Since "variation" is a "Generator" object, but "variations" is a list of Strings (what you need).
Related
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator.")
except ValueError:
print("Enter valid inputs.")
Want to write a statement to continue running the calculator after the answer is shown as output. Example, 2.0 + 2.0 = 4.0
I want the code to ask 'Do you want to continue operations with 4? Type 'y' for yes and 'n' for no.'
And then let's say I enter the multiply operator again, and another number to do the calculation with, it should show, 4.0 * 2.0 = 8.0
Okay, as stated in the comments to your original question, you were super close. All you needed to do is wrap your logic in a loop so you can iterate over the items, which I do in my example below with a while True loop. Then outside of that loop, you needed to track a value that the user creates...for example:
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
try:
# track this value out of loop so it isn't reset
tracked_value = None
# make a continuous loop...
while True:
# anything here will reiterate unless broken
# tracked_value will always be none unless the user opts to reuse it below...
if tracked_value is None:
num1 = float(input("Enter first number: "))
else:
# now we can turn num1 into the tracked value, the user wishes to reuse it
num1 = tracked_value
print(f'You opted to reuse the tracked value for number 1, which was: "{num1}"')
# always will be asked.
num2 = float(input("Enter second number: "))
# print options
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
# honestly I would alter your dict to remove the need for
# this huge conditional, but I didn't want to change too much
# ex: method = operations.get(operator, None)... if method not None: answer = method(num1, num2)
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator. Try again...")
# 'continue' so you don't hit the code below, this starts the loop again
continue
# now logic is done, ask if they wish to continue or break
should_continue = input(f"Do you want to continue your calculation with your current answer: '{answer}'? "
"Type 'y' for yes and anything else for no. ")
# logic to continue or not, remember continue starts the iteration over
if should_continue.lower() in ['y', 'yes']:
# assign the tracked value now the user wants it.
tracked_value = answer
continue
else:
print('Thanks for using my calulator. See you next time.')
# break out of the while loop, the user opts to exit.
break
except ValueError as ex:
print(f"Enter valid inputs: {ex}")
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
def calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator.")
except ValueError:
print("Enter valid inputs.")
calculator()
should_continue = input("Do you want to continue your calculation with your current answer? Type 'y' for yes and 'n' for no. ")
if should_continue == 'y':
should_continue = True
else:
should_continue = False
print("Thank you for using the calculator.")
while should_continue:
calculator()
break
I have been working on this calculator and have been trying to modify it so that it can take in user inputs that contain decimals and if the output were to have a decimal in it, to round it to the nearest whole number but I am not sure exactly where I should input the code. I have tried using the round() function but I end up getting a syntax error when I put it towards the bottom. Here is what I have so far.
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
# while True:
cont = "y"
while cont.lower() == "y":
print("Select operation\n1.Add\n2.Subtract\n3.Multiply\n4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1' :
print(num1, "+", num2, "=", add (num1, num2))
elif choice == '2' :
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3' :
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4' :
print(num1, "/", num2, "=", divide(num1, num2))
cont = input("Continue?y/n:")
if cont == "n":
break
If you want to keep your code pretty much the way it is, but allow the user to optionally enter a floating point number that is rounded to the closest integer value then you only need to change this:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
to this:
num1 = round(float(input("Enter first number: ")))
num2 = round(float(input("Enter second number: ")))
I'm new to the stack overflow website, python, and programming as a whole. So pardon me if the title or body of this question isn't apt.
I'm trying to create a simple calculator program in python, which performs only four operations, namely, addition, subtraction (difference), multiplication and division.
Here's my code:
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
Everything runs fine, except, when I enter zero as num2, and no matter what operator I select, the output
is this:
Traceback (most recent call last):
File "test4.py.txt", line 19, in <module>
quotient = num1 / num2
ZeroDivisionError: division by zero
Help would be greatly appreciated.Thanks!
Find the quotient inside the if condition, not before checking num==0, otherwise the division by zero is already done, causing the error.:
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
quotient = num1 / num2
That's the line that is giving you the error. You should be checking if num2 is zero before calculating num1 / num2. You can do it as follows and your program would work fine.
quotient
if num2 == 0:
quotient = None
else :
quotient = num1 / num2
Else you could just declare quotient and calculate the quotient when user inputs the operator. If user enters /, then you can check if num2==0 and if it is you can give error message.
Working code -
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = None # Don't divide by num2 here or you will get error of divisionbyzero
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
Since you are new, I will explain this in more detail so you actually know what you are doing wrong
Pay attention to these lines
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
When you do this it is actually performing the calculation and assigning it to the respective value (i.e. quotient = num1 / num2 will actually do the calculation and store the result in the quotient variable). So, you are doing every calculation every time regardless of your choice of operator. It would be better to assign the values only if that operator has been chosen like below.
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
if operation == "-" :
sub1 = num1-num2
sub2 = num2 - num1
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
add = num1+num2
print(add)
elif operation == "*" :
product = num1*num2
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
This part is just a suggestion. You could also make your Difference operation easier by using the following.
if operation == "-" :
sub1 = num1-num2
print(abs(sub1))
abs gets the absolute value, basically removes the negative.
You should calculate the results only after checking the operators (thus avoiding any errors caused by trying to divide by zero), this way you will also avoid unnecessary calculations:
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
So I'm a novice coder having never coded before and am teaching myself Python on the guidance of my CS instructor. I'm walking myself through "Automating the Boring Stuff with Python" and I'm having issues with the Collatz sequence portion at the end of Chapter 3. I've got the sequence down but I'm having issues properly looping the code in order to get the result I want which is looping the sequence until the answer is == to integer 1. This is what I have and I would love some feedback and assistance.
def collatz(number): #defines the collatz sequence
if number%2 == 0:
num1 = number//2
else:
num1 = 3 * (number + 1)
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
num3 = collatz(num)
while num3 != 1: #loops collatz sequence until it equals 1
num2 = collatz(num3)
if num2 == 1:
break
else:
num3 = collatz(num2)
print("ta da!")
You need this code:
def collatz(number):
if number % 2 == 0:
num1 = number//2
else: num1 = 3 * number + 1 # Do not use brackets!!! Or you will have infinite loop
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
while num != 1:
num = collatz(num)
print(num)
if num == 1: break
print("ta da!"); input()
this is my code for a quiz with ten question.the problem is that whenever I write the answer (the answer gets printed before asking the question) it always say incorrect. please take into consideration that I am very bad at the language and don't correct what doesn't need to be fixed. Thankyou.
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(answer)
print(num1 ,symbal ,num2)
sanswer = input("= ?")
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(num1 ,symbal ,num2)
sanswer = int(input("= ?"))
print(answer)
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
2 mistake you have:
first: you shouldn't put print(answer) before input
second: you should sanswer = int(input("= ?")) use int() because what you take with input is string
and a simple suggestion try not to use global when coding.