ValueError in calculator [duplicate] - python

This question already has answers here:
Python: Test if value can be converted to an int in a list comprehension
(3 answers)
Closed 1 year ago.
I wonder, if it's possible to show a message "Invalid...", whenever a user tries to input string in x or y instead of integers?
Here's the code :
print("Enter a operator first ('+-*/') or 'q' to Exit! ")
while True:
choice = input("Enter choice (one of these): '+', '-', '/', 'x': ")
if choice in ('x+-/'):
x = int(input("First number: "))
y = int(input("Second number: "))
if choice == "+":
print(x, "+", y, "=", x + y)
elif choice == "-":
print(x, "-", y, "=", x - y)
elif choice == "/":
print(x, "/", y, "=", x / y)
elif choice == "x":
print(x, "x", y, "=", x * y)
elif choice == 'q':
break
else:
print("Invalid choice. Try again.")
I tried these code to solve my problem but didn't succeed
if x != int:
print("invalid...")
# And Also
if x == str:
print ("invalid...")
Using these also, doesn't solves my problem:
Here's the error I get:
x = int(input("First number: "))
ValueError: invalid literal for int() with base 10: 'as'
I guessed it's because I indicated in the beginning that x =input must be in integer, but if i take away this "int" the whole project won't work and I'll get this error:
TypeError: can't multiply sequence by non-int of type 'str'

Yes, it is possible. Use a try/except block as follows:
try:
x = int(input("First number:"))
y = int(input("Second number: "))
except ValueError:
print('Invalid...')

You can do it this way:
while True:
choice = input("Enter choice (one of these): '+', '-', '/', 'x': ")
if choice in ('x+-/'):
x = input("First number: ")
y = input("Second number: ")
if x.isalpha() or y.isalpha():
print("invalid...")
else:
x=int(x)
y=int(y)
if choice == "+":
print(x, "+", y, "=", x + y)
elif choice == "-":
print(x, "-", y, "=", x - y)
elif choice == "/":
print(x, "/", y, "=", x / y)
elif choice == "x":
print(x, "x", y, "=", x * y)
elif choice == 'q':
break
else:
print("Invalid choice. Try again.")

Related

Return to main menu function for python calculator program

I was asked to write a calculator in Python, and I completed it, but there is only one issue that needs to be fixed.
What is the prerequisite? "Once the user inputs/selects an arithmetic operation, the program should ask the user to enter the two operands one by one, separated by Enter key. If the user made a mistake while entering the parameters, he can return to main menu by pressing ‘$’ key at the end of the input string, followed by the Enter key.
I'll give you the code I wrote here, and I'd appreciate it if you could make this to get the return function.
def Add(a, b):
return a + b
# Function to subtract two numbers
def Subtract(a, b):
return a - b
# Function to multiply two numbers
def Multiply(a, b):
return a * b
# Function to divide two numbers
def Divide(a, b):
return a / b
# Function to power two numbers
def Power(a, b):
return a ** b
# Function to remaind two numbers
def Remainder(a, b):
return a % b
def Reset(a,b):
return print(choice)
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if choice in ('+', '-', '*', '/', '^', '%', '#', '$'):
if choice == '#':
print("Done. Terminating")
break
a = input('Enter first number: ')
print(str(a))
b = input('Enter second number: ')
print(str(b))
if choice == '+':
print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))
elif choice == '-':
print(float(a), "-",float(b), "=", Subtract(float(a), float(b)))
elif choice == '*':
print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))
elif choice == '/':
if int(b) != 0:
print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
break
else:
print("float division by zero")
print(float(a), "/", float(b), "=", "None")
elif choice == '^':
print(float(a), "**",float(b), "=", Power(float(a), float(b)))
elif choice == '%':
print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))
break
else:
print('Not a valid number,please enter again.')
```
This kind of task is best (IMHO) handled in a so-called "table driven" manner. In other words, you create a table (in this case a dictionary) that has all the options built into it. Your core code then becomes much easier and the functionality is more extensible because all you need to do is add to or take away from the dictionary.
This structure also demonstrates how the user can be prompted for more input if/when something goes wrong.
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):
return a / b
def Power(a, b):
return a ** b
def Remainder(a, b):
return a % b
options = {'+': ('Add', Add, '+'),
'-': ('Subtract', Subtract, '-'),
'*': ('Multiply', Multiply, '*'),
'/': ('Divide', Divide, '/'),
'^': ('Power', Power, '**'),
'%': ('Remainder', Remainder, '%'),
'#': ('Terminate', None)}
while True:
print('Select operation: ')
for i, (k, v) in enumerate(options.items(), 1):
print(f'{i}. {v[0]:<10}: {k} : ')
option = input(f'Enter choice ({",".join(options.keys())}) : ')
if control := options.get(option):
_, func, *disp = control
if not func:
break
a = input('Enter first number: ')
b = input('Enter second number: ')
try:
a = float(a)
b = float(b)
print(f'{a} {disp} {b} = {func(a, b)}')
except (ValueError, ZeroDivisionError) as e:
print(e)
else:
print('Invalid option!')
Thank you so much for all your responses. With your help I was able to come to a decisive conclusion very quickly.
This is the end result I got after the changes I made:
def Add(a, b):
return a + b
# Function to subtract two numbers
def Subtract(a, b):
return a - b
# Function to multiply two numbers
def Multiply(a, b):
return a * b
# Function to divide two numbers
def Divide(a, b):
return a / b
# Function to power two numbers
def Power(a, b):
return a ** b
# Function to remaind two numbers
def Remainder(a, b):
return a % b
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if choice in ('+', '-', '*', '/', '^', '%', '#', '$'):
if choice == '#':
print("Done. Terminating")
break
a = input('Enter first number: ')
print(str(a))
if a.endswith('$'): continue
b = input('Enter second number: ')
print(str(b))
if b.endswith('#'):
print("Done. Terminating")
break
if b.endswith('$'): continue
if choice == '+':
print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))
elif choice == '-':
print(a, "-", b, "=", Subtract(a, b))
elif choice == '*':
print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))
elif choice == '/':
if int(b) != 0:
print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
break
else:
print("float division by zero")
print(float(a), "/", float(b), "=", "None")
elif choice == '^':
print(float(a), "**",float(b), "=", Power(float(a), float(b)))
elif choice == '%':
print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))
break
else:
print('Not a valid number,please enter again.')
```
I think I found a way to do this.
You want to loop back to the menu where you ask to choose among math symbols.
You can add a while based on a variable (bool) set to True.
You then get two while loops.
reset = True
while reset:
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
Therefor if you spot any "$"in either a, b or your choice you can just break. You will come out of the second while loop and go back to the first one, printing the menu again.
But then you have to modify the behaviour when you encounter "#" because breaking now brings you back to the top and doesn't exit the program. You first have to set reset to reset = False then you can break, therefore exiting both loops.
if choice == '#':
print("Done. Terminating")
reset = False
break
if '$' in a or '$' in b or '$' in choice :
print("Resetting.")
break
You can learn more about nested while loops here :
https://code4coding.com/nested-while-loop-in-python/
To add clarity to you code you might want to get rid of all your functions since python have already builtin functions done with the corresponding math symbol ^^
EDIT : FULL SNIPPET
reset = True
while reset:
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if choice in ('+', '-', '*', '/', '^', '%', '#', '$'):
if '$' == choice :
print("Resetting.")
break
if choice == '#':
print("Done. Terminating")
reset = False
break
a = input('Enter first number: ')
print(str(a))
if '$' in a :
print("Resetting.")
break
b = input('Enter second number: ')
print(str(b))
if '$' in a or '$' in b :
print("Resetting.")
break
if choice == '+':
print(float(a), "+", float(b), "=", Add(float(a), float(b)))
elif choice == '-':
print(float(a), "-", float(b), "=", Subtract(float(a), float(b)))
elif choice == '*':
print(float(a), "*", float(b), "=", Multiply(float(a), float(b)))
elif choice == '/':
if int(b) != 0:
print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
break
else:
print("float division by zero")
print(float(a), "/", float(b), "=", "None")
elif choice == '^':
print(float(a), "**", float(b), "=", Power(float(a), float(b)))
elif choice == '%':
print(float(a), "%", float(b), "=", Remainder(float(a), float(b)))
break
else:
print('Not a valid number,please enter again.')

"break outside loop" but i've tried everything and still got the same error message

# Program make a simple calculator
# 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
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
the error:
File "main.py", line 38
break
^
SyntaxError: 'break' outside loop
** Process exited - Return Code: 1 **
Press Enter to exit terminal
I'm trying to make an interactive calculator, and the only issue is that I don't know how to break the loop. i tried indenting it, and it gave this. deleting the indentation made python tell me that I need to add an indent; yet adding an indent gives this error message. I don't know what else to do; I'm new to this.
Try it with indentation like this:
# Program make a simple calculator
# 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
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Another option would be to add a state variable like this. And move it to false when you want to exit the loop.
# Program make a simple calculator
# 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
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
state = True
while state:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
state = False
else:
print("Invalid Input")

Trying to make a loop that stops on user input

I'm trying to make a calculator that will either restart the script or stop it using "continue" and "break". Yet when I try to run it, it says continue is not in loop, can someone help please?
Here's the code:
import os
import sys
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
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 > "4": # (REFER TO TAG 1) : Seeing if this would work ( something to compare to )
while True:
print ("Invalid Input")
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
if answer == "y":
continue
if answer == "n":
break
num1 = (input("Enter first number: ")) # Got rid of float() before input
num2 = (input("Enter second number: ")) # Got rid of float() before input
if choice == "1": # Changed single speech mark to double.
print(num1,"+",num2,"=", add(num1,num2))
elif choice == "2": # Changed single speech mark to double.
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == "3": # Changed single speech mark to double.
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == "4": # Changed single speech mark to double.
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid Input")
Below works for me, #busybear is right, the indentation was off.
import os
import sys
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
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 > "4": # (REFER TO TAG 1) : Seeing if this would work ( something to compare to )
while True:
print("Invalid Input")
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
if answer == "y":
continue
if answer == "n":
break
num1 = (input("Enter first number: ")) # Got rid of float() before input
num2 = (input("Enter second number: ")) # Got rid of float() before input
if choice == "1": # Changed single speech mark to double.
print(num1,"+",num2,"=", add(num1,num2))
elif choice == "2": # Changed single speech mark to double.
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == "3": # Changed single speech mark to double.
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == "4": # Changed single speech mark to double.
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid Input")

How to protect my python code when a user inputs a string instead of an integer?

I would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.
I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.
I would also like to know if there is a way to let a user do another operation instead of having to restart the application.
If any importing is required (if you can) please list if it is compatible with cx_Freeze.
Source code:
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)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.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))
else:
print("Invalid input")
you can use something like this for input
while True:
try:
num1 = int(input("Enter first number: "))
except ValueError:
continue
else:
break
Take a look at the changes I have made to your code as follows:
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)
def input_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That was not a number")
# Keep going around the loop until the user chooses 5 to quit
while True:
print
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Quit")
choice = input("Enter choice(1/2/3/4/5):")
# Do they want to quit?
if choice == 5:
break
num1 = input_number("Enter first number: ")
num2 = input_number("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))
else:
print("%s - Invalid input" % choice)
In order to ask for more input, you needed to wrap your prompts in a loop. You would then need to add an option to the user to allow them to quit.
Also, you can move the prompting for numbers to a function. This would keep asking for number if the user typed in a character.
This code snippet should help :-
def is_string(test_data):
if type(test_data) is str:
return True
else:
return False

Ending a Python Script

In Python 3.2, I'm writing up a basic menu program, and when the option to quit is entered, the function is not ending.
When quit is chosen, it ends the loop the rest of the script is in, and should terminate the script, but it isn't, for whatever reason?
Am I missing an 'end' function that kills the script, or is the new Python Shell just buggy?
Pretty sure this wasn't necessary in Python 2.7.
import random
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
while choice != "q" or choice != "Q":
while choice != "i" and choice != "I" and choice != "c" and choice != "C" and choice != "q" and choice != "Q":
print("Invalid menu choice.")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
if choice == "i" or choice == "I":
print("blahblah.")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
if choice == "c" or choice == "C":
x = int(input("Please enter the number of x: "))
while x < 0:
x = int(input("Please enter the number of x: "))
y = int(input("Please enter the number of y: "))
while y < 0:
y = int(input("Please enter the number of y: "))
z = str(input("blah (B) or (P) z?: "))
while z != "b" and z != "p" and z != "B" and z != "P":
z = str(input("blah (B) or (P) z?: "))
if z == "b" or z == "B":
total = x*10 + y*6 + 0
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
#function that outputs the cost of premium z
if z == "p" or z == "P":
luck = random.randrange(1, 11, 1)
if luck == 10:
total = x*10 + y*6
print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
#below is the normal function, for when the customer is not a lucky winner
if luck != 10:
total = x*12.50 + y*7.50
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate\n(Q)uit\n>>>"))
Your condition is wrong:
while choice != "q" or choice != "Q": # this should be "and"!
always returns True, creating an infinite loop.
Also, you've got quite a convoluted bit of logic here. This can be simplified a lot:
import random
while True:
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>")).lower()
if choice == "i":
print("blahblah.")
continue
elif choice == "q":
break
elif choice == "c":
while True:
x = int(input("Please enter the number of x: "))
if x >= 0: break
while True:
y = int(input("Please enter the number of y: "))
if y >= 0: break
while True:
z = str(input("blah (B) or (P) z?: ")).lower()
if z in "bp": break
if z == "b":
total = x*10 + y*6 + 0
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
#function that outputs the cost of premium z
else: # z must be "p"
luck = random.randrange(1, 11, 1)
if luck == 10:
total = x*10 + y*6
print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
#below is the normal function, for when the customer is not a lucky winner
if luck != 10:
total = x*12.50 + y*7.50
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
else:
print("Invalid menu choice.")
continue
One way to perform quit operations in Python is to throw a custom exception and catch that exception explicitly. Please correct me if I am wrong, AFAIK this doesn't put a big over-head on your python program. It could done as simple as the what I show below:
...
class QuitException(Exception);
...
def MyMenuProgram():
...
...
...
if __name__ == '__main__':
try:
MyMenuProgram()
catch QuitException:
pass
catch Exception, e:
raise
As #Tim answered, your loop condition is wrong.
while choice != "q" or choice != "Q":
Let's take a look at this, logically:
if choice == "q", choice != "Q", loop condition evaluates to false or true, which is true
if choice == "Q", choice != "q", loop condition evaluates to true or false, which is true
if choice != "q" or "Q", loop condition evaluates to true or true, which is true
You need to change this loop condition to:
while choice != "q" and choice != "Q":
or
while choice.lower() != "q":
Edit: Redacted - input() is indeed the way to get user input in Py3k. Another of the glorious differences between Python 2.7 and Python 3.2.

Categories

Resources