I am Trying to execute a script in which if non integer value is enter is should catch with except but it doesn't seem to work ..in my case print(message) in except block is showing in output while executing but errors also come
print('Answer is :', add(num1, num2))
NameError: name 'num1' is not defined
I'm using python 3.8... kindly assist :
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def into(num1, num2):
return num1 * num2
def by(num1, num2):
return num1 / num2
print("Select operation :")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice in ["1", "2", "3", "4"]:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except NameError:
print('Only Integers Allowed')
except ValueError:
print('Only Integers Allowed ')
else:
print("Invalid Input")
exit()
def calci():
if choice == "1":
print('Answer is :', add(num1, num2))
elif choice == "2":
print('Answer is :', subtract(num1, num2))
elif choice == "3":
print('Answer is :', into(num1, num2))
elif choice == "4":
print('Answer is :', by(num1, num2))
calci()
You have to exit() the if statement block so that the program doesn't call the calc() function. If you don't exit the if statement block the program calls the calc() function which is responsible for the error message.
Also, you have to pass the parameters choice, num1 and num2 to the calc() function.
I have edited the code a little bit, which might be useful. You can iterate the input() statement so that the user can give it another try after entering an invalid input.
print("Select operation :")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice in ["1", "2", "3", "4"] :
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except(TypeError, NameError, ValueError):
print('Only Numbers Allowed !!!')
exit()
else:
print("Invalid Input")
exit()
def add(a, b):
return a+b
def subtract(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
try:
return a/b
except ZeroDivisionError:
print("Undefined (Can't be divided by zero)")
def calc(choice, num1, num2):
if choice == "1":
print('Answer is :', add(num1, num2))
elif choice == "2":
print('Answer is :', subtract(num1, num2))
elif choice == "3":
print('Answer is :', multiply(num1, num2))
else:
print('Answer is :', divide(num1, num2))
calc(choice, num1, num2)
Related
Answers.py
import Multiplications
import Start
def finish(choice, num1, num2):
if choice == "1":
print(num1, "+", num2, "=", Multiplications.Add(num1, num2))
elif choice == "2":
print(num1, "-", num2, "=", Multiplications.Subtract(num1, num2))
elif choice == "3":
print(num1, "*", num2, "=", Multiplications.Multiply(num1, num2))
elif choice == "4":
print(num1, "/", num2, "=", Multiplications.Divide(num1, num2))
Main.py
import nd
import Answers
import Multiplications
import Start
Start.operations()
nd.operation()
Multiplications.py
#This function adds two numbers
def Add(x, y):
return x + y
#This function subtracts two numbers
def Subtract(x, y):
return x - y
#This function multiplies two numbers
def Multiply(x, y):
return x * y
#This function divides two numbers
def Divide(x, y):
return x / y
nd.py
import Answers
def operation():
choice = input("Choose 1, 2, 3, or 4: ")
#Check if the input is one of the four options
if choice in ("1", "2", "3", "4"):
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
Answers.finish(choice, num1, num2)
Start.py
def operations():
import time
print("Select Operation: ")
#time.sleep(1)
print("1) Add")
#time.sleep(1)
print("2) Subtract")
#time.sleep(1)
print("3) Multiply")
#time.sleep(1)
print("4) Divide")
I want to add a command where after the answer is given from the given num1 and num2 i want a insert line to appear asking Would you like to do our next multiplication (Yes/No):
I think i should make another def but it didnt work, can somebody help. Thanks!
You can use a while True loop to play infinitly, then
add another input to continue or not
def operation():
while True:
choice = input("Choose 1, 2, 3 or 4: ")
if choice in "1234":
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
Answers.finish(choice, num1, num2)
stop = input("Do you want to stop (yes)/no ?")
if stop == "no":
break
use a fifth option that stop the game
def operation():
while True:
choice = input("Choose 1, 2, 3, 4 or 5: ")
if choice in "1234":
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
Answers.finish(choice, num1, num2)
elif choice == '5':
break
For the program to run in repeat, the simplest way to do so is to use a While True loop
import Answers
def operation():
while True:
choice = input("Choose 1, 2, 3, or 4, or stop ")
#Check if the input is one of the four options
if choice in ("1", "2", "3", "4"):
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
Answers.finish(choice, num1, num2)
if choice == "stop":
sure_to_stop = input("are you sure you want to stop? Y/N)
if sure_to_stop.lower() == "y':
break
I can't quite figure out why my code won't work.
Whenever I click run, it doesn't follow back with a traceback error, it just says process finished with exit code 0.
I thought it might be the casefold but then when I applied it to "Y". casefold it wouldn't work full stop.
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
Just add calculate() at the very end to call the function.
Put function calling calculate() at the end without any indent. Your function isn't even getting called, thus giving no error.
You need to call this calculate() function first (at least it's not being executed in your code sample).
def calculate()
# func code here
#Exec this function
calculate()
I guess it should be like this:
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
calculate()
I have an error with my code when I try to run it.
CODE
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = input()
num1 = input("Enter your first number: ")
num2 = input("Enter your second number: ")
def addition(num1, num2):
num1
num2
ans = num1 + num2
print('Your answer is %s') %(ans)
def subtraction(num1, num2):
num1
num2
ans = num1 - num2
print('Your answer is %s') %(ans)
def multiply(num1, num2):
num1
num2
ans = num1 * num2
print('Your answer is %s') %(ans)
def division(num1, num2):
num1
num2
ans = num1 / num2
print('Your answer is %s') %(ans)
if choice == "1":
addition
elif choice == "2":
subtraction
elif choice == "3":
multiply
elif choice == "4":
division
else:
print("Invalid Input")
Everything works until python is called to print the answer.
I am aware of the possible duplicates but none of the code provided there works.
The issue is in the lines -
if choice == 1():
addition
elif choice == 2():
subtraction
elif choice == 3():
multiply
elif choice == 4():
division
I have no idea what you want 1() to do, seems like a typo. Also you should be calling the functions addition , etc , like - addition(num1, num2) .
And choice is string not int . And you should convert num1 and num2 to int.
More issues in your code -
Why are you doing - num1 and num2 in your functions , it does not do anything, you can remove the first two lines of each function.
Your print function in wrong, in Python 3.x , the %(ans) should be inside the function, not outside it.
Code -
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
ans = num1 + num2
print('Your answer is %s' %(ans))
def subtraction(num1, num2):
ans = num1 - num2
print('Your answer is %s' %(ans))
def multiply(num1, num2):
ans = num1 * num2
print('Your answer is %s' %(ans))
def division(num1, num2):
ans = num1 / num2
print('Your answer is %s' %(ans))
if choice == '1':
addition(num1, num2)
elif choice == '2':
subtraction(num1, num2)
elif choice == '3':
multiply(num1, num2)
elif choice == '4':
division(num1, num2)
The problem is due to this
if choice == 1():
Where as it should be
if choice == 1:
And you have to convert num1 and num2 to integer types
And you should call the function just not declare them that is
if choice == 1:
addition(num1, num2)
And you have to do this for other things
And after doing all the changes your program would look like this
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = int(input())
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
ans = num1 + num2
print('Your answer is %s') %(ans)
def subtraction(num1, num2):
ans = num1 - num2
print('Your answer is %s') %(ans)
def multiply(num1, num2):
ans = num1 * num2
print('Your answer is %s') %(ans)
def division(num1, num2):
ans = num1 / num2
print('Your answer is %s') %(ans)
if choice == 1:
addition(num1,num2)
elif choice == 2:
subtraction(num1,num2)
elif choice == 3:
multiply(num1,num2)
elif choice == 4:
division(num1,num2)
else:
print("Invalid Input")
My changes would be:
choice = int(input("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division\n^ Operation 'ID' please enter the id of your choice\n"))
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans=None
if choice == 1:
ans = num1 + num2
elif choice == 2:
ans = num1 - num2
elif choice == 3:
ans = num1 * num2
elif choice == 4:
ans = float(num1) / num2
if ans:
print('Your answer is %s') %(ans)
else:
print("Invalid Input")
The error with your current code is just with the brackets in your print statements. if instead of having %ans outside of the print statement, the code works when it is like this
print('Your answer is %s' %ans)
A neater version of the same code you just wrote looks like this
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = int(input())
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
return num1+num2
def subtraction(num1, num2):
return num1-num2
def multiply(num1, num2):
return num1*num2
def division(num1, num2):
return num1/num2
if choice == 1:
ans = addition(num1,num2)
elif choice == 2:
ans = subtraction(num1,num2)
elif choice == 3:
ans = multiply(num1,num2)
elif choice == 4:
ans = division(num1,num2)
else:
print("Invalid Input")
if choice in range(4):
print('Your answer is %s' %ans)
Ironically, this has ended up with me writing an answer to my own question with admittedly some help from # Vignesh Kalai, although hid code was a little off. So before anything else I will address the changes to my code.
Firstly, instead of defining every operation I have linked than with the choice of their "ID"'s.
Secondly, I am using "" + str(x) to print the answers out instead of the admittedly bad idea of using %s.
REVISED CODE
choice = int(input("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division\n^ Operation 'ID' please enter the id of your choice\n"))
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
if choice == 1: #Addition
num1
num2
ans = num1 + num2
print("Your answer is " + str(ans))
elif choice == 2: #Subtraction
num1
num2
ans = num1 - num2
print("Your answer is " + str(ans))
elif choice == 3: #Miltiplication
num1
num2
ans = num1 * num2
print("Your answer is " + str(ans))
elif choice == 4: #Division
num1
num2
ans = float(num1) / float(num2)
print("Your answer is " + str(ans))
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def multi(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print("\t\t\tCalculator App")
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
#invalid operation
print("You have entered an invalid key")
else:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
if(operation == "+"):
print("Answer is: ", add(var1, var2))
elif(operation == "-"):
print("Answer is: ", sub(var1, var2))
elif(operation == "*"):
print("Answer is: ", multi(var1, var2))
else:
print("Answer is: ", div(var1,var2))
main()
rerun = input("ReRun? (y/n)")
while(rerun == "y"):
main()
rerun = input("ReRun? (y/n) ")
else:
exit()
Reading books, watching videos, and self study has been challenging.
Please let me know if this is the correct way to loop this program, i'm sure there are alternatives.
If you mean the rerun loop down at the bottom, the following is probably cleaner:
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
It should be noted that it defaults to rerunning if the user enters something not expected.
I would have done something like
operators = dict()
operators['+'] = lambda x,y: x+y
operators['-'] = lambda x,y: x-y
operators['*'] = lambda x,y: x*y
operators['/'] = lambda x,y: x/y
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if operation in operators:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
print("Answer is: ", operators[operation](var1, var2))
else:
print("You have entered an invalid key")
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
Which I believe is more readeable and easier to expand (add new operators)
I'm trying to get convert this from python 3 to 2.7 and I think I may have messed up with the indentation. The shell provides an error message of:
line 20, if(operation == '+'), IndentationError: unexpected indent
I'd like to keep the code as intact as possible but I cannot see the bug! Ugh!
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else(operation == '/'):
print div(var1, var2)
main()
PEP8 recommends using 4 space indentation, here is the code of your calculator reformatted to 4 spaces:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and
operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else:
print div(var1, var2)
main()
The IndentationError exception on compilation, happened because you had the 20th line and those appearing after it overindented.
After that I found the else (else(operation == '/'):) which is invalid, because it does not need a condition, I replaced it by and else, because at this stage we are really sure the operation is '/'.
Side note:
As #Jkdc proposes we can also check operator strings using this approach, which is more readable, in my opinion:
if(operation not in ['+', '-', '*', '/']):
print "you must enter a valid operation"
else:
#Rest of the code
Basically, it checks if the operation string is not found in the list of operators, instead of comparing them separately on 4 conditions.