So I need to make a calculator that converts strings into floats then calculate.
The problem is I need to make error messages whenever:
the user enters a string that does not contain operands and/or an operator.
the user does not enter anything (the user simply pressed the Enter key).
the user only enters an operand.
the user only enters an operator.
the user enters two operands.
the user enters an operand and an operator.
the user is trying to divide a number by 0.
the user did not put a space in between the operands and the operator.
This is how the code looks like without error messages
# Interface
print ("Equation Calculator")
print (" ")
print ("My Equation Calculator is able to")
print (" Add: +")
print (" Subtract: -")
print (" Multiply: *")
print (" Divide: /")
print (" ")
print ("The equation you enter must follow this syntax:")
print (" <openrand><speace><operator><space><operand>.")
print ("An <operand> is any float number.")
print ("An <operator> is any is any of the operators mentioned above.")
print ("A <space> is an empty space.")
# Enter the equation
equation = input ("Enter your equation: ")
# Split the equation into Operand 1,2 and Operator
operand1,operator,operand2 = equation.split(" ")
# Show the user the equation
print ("Here is the equation you have entered: " + equation)
# Addition, Converting strings (operand 1 and 2) into float
if (operator == "+"):
answer = float(operand1) + float(operand2)
# Subtraction, Converting strings (operand 1 and 2) into float
if (operator == "-"):
answer = float(operand1) - float(operand2)
# Multiplication, Converting strings (operand 1 and 2) into float
if (operator == "*"):
answer = float(operand1) * float(operand2)
# DIvision, Converting strings (operand 1 and 2) into float
if (operator == "/"):
answer = float(operand1) / float(operand2)
# Display the answer
print ("The answer is: ",answer )
So for 7 and 8th errors I did this
# Error for not having a space
if (equation.find(" ") == False):
print ("Error #1: Please check if there is a space in between the two operands and the operator.")
# Error for dividing by 0
if (operand2 == "0"):
print ("Error #7: You cannot divide by 0.")
However python just bypasses this and still crashes.
What is the problem with above code?
How can I make it so the code prints error messages in above 8 situations?
Also I cannot use the built-in functions eval( ) or exec(), break or continue or pass or sys.exit( ).
I am very new to programming in general.
Please help and thank you.
If you have some set requirements on the incoming data, it is usually a good idea to check beforehand, if the data match this requirements.
So I would test if the string given matches your requirements:
The general structure could be tested with regular expressions:
I assume only integers are used, if not you need to replace the \ds with floating pointg matching, which should be googleable.
\d+ [+\/\-*] \d+
This regex matches any digit, followed by a space,followed by one of the operator +/*- and a digit.
Please not that would cause a very generic error message - like "your input does not look like the required input", so you might be better of to test the parts separately, to give a better user experience.
Use a structure like this:
if bad_condition:
print "error"
else:
# do whatever
You can try this:
try:
assert condition, "Error Message"
except AssertionError, e:
raise Exception(e.args)
for example:
# Error for not having a space
try:
assert (equation.find(" ")), "Error #1: Please check if there is a space in between the two operands and the operator."
except AssertionError, e:
raise Exception(e.args)
Related
I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
Have your function return values, instead of simply printing. This is good practice.
Use if not a to test if your string is empty. This is a Pythonic idiom.
Convert your input string to numeric data, e.g. via int.
Catch ValueError and return an appropriate message in case the user input is invalid.
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
Receive your user inputs.
Compute the data.
Print accordingly.
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False (it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else, is if you handled your error case, then your input must be right, so you compute your data accordingly.
In your second line, it should be
if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))
pseudocode
numtodouble=int
result=int
print("")
print("Enter a number you would like to double and press Enter.")
input (numtodouble)
<class 'int'>2
'2'
while numtodouble>0:
result=numtodouble*2
print("2 X", numtodouble, "=", result)
print("")
print("Enter a number you would like to double and press Enter.")
input(numtodouble)
break
print("OK, you entered a value <=0, ending execution.")
Does anyone know where I went wrong with my code? I've been struggling with this for hours.
try:
# input is stored as num_to_double. the input is cast to an int, and the string in input is the prompt
num_to_double = int(input("Enter a number you would like to double and press Enter."))
while num_to_double>0:
result=num_to_double*2
# Format puts the arguments into the curly braces in the order given
print("2 X {} = {}\n".format(num_to_double, result))
# input is cast to int and stored in num_to_double. The text in the input command is the prompt
num_to_double =int(input("Enter a number you would like to double and press Enter."))
# This is otuside the while loop, so this runs when the while loop breaks. The previous break command was making
# the code act not as intended
print("OK, you entered a value <=0, ending execution.")
# This catches if someone inputs a value that is not able to be cast to a string. It's the second half of the Try:
# Except block.
except ValueError as _:
print("A not-a-number was supplied")
This code is far simplier and does what you're trying to do. I assume you're learning python, so some of these things are not the simplest way to do things, like the format function, but are super useful to learn.
num_to_double = 0
result = 0
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
while num_to_double > 0:
result = num_to_double * 2
print("2 X {} = {}".format(num_to_double, result))
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
print("OK< you entered a value <=0, ending execution.")
This code is the closest I could do to the pseudocode provided. Declaring variables before they're used here isn't necessary and is messy. It's like the pseudocode wasn't meant to become python. Same with printing blank lines, those should be wrapped into the previous or next print lines.
I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them...
I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
Since you are saying you are new to Python, I'm going to suggest you experiment with a few methods yourself. This will be a nice learning experience. I'm not going to give you answers directly here, since that would defeat the purpose. I'm instead going to offer suggestions on where to get started.
Side note: it's great that you are using Python3. Python3.6 supports f-strings. This means you can replace the line with your print function as follows.
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
Okay, you should look into the following in order:
for loops
List comprehension
Named Tuples
functions
ZeroDivisionError
Are you looking for something like this :
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
output:
1 2
0.5
By using a function that does the input for you inside a list comprehension that constructs your 2 numbers:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
The rest is from your code, changed is the list comp to handle the message and input-creation:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
Output:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
Links:
try: ... except:
Lists & comprehensions
Python isn't recognizing any number apart from 1 as an integer. When i enter a number to be multiplied the program will run the except ValueError even though i have entered an integer. This is the code i have.
Total = 0
Tsl = 100
receipt = open("Receipt.txt", "w")
while True:
try:
Prod_Code = input("Enter a code or Done to get your final receipt: ")
if len(Prod_Code) == 8:
int(Prod_Code)
with open("Data Base.txt", "r") as searchfile:
for line in searchfile:
if Prod_Code in line:
print(line)
Quantity = input("What quantity of this product do you want? ")
Total += float(line.split(",")[2] * int(Quantity))
print(Quantity)
print(Total)
receipt.write(line)
elif Prod_Code == "Done":
print("Bye Bye")
print(receipt)
receipt.close
exit()
else:
print("Incorrect length, try again")
except ValueError:
print("You must enter an integer")
The error occurs when i enter any other number than 1 when i enter the quantity. If anyone can see the problem any input will be appreciated
The problem is that
Total += float(line.split(",")[2] * int(Quantity))
multiplies the string line.split(",")[2] by the Quantity converted to integer. And then attempts to convert the resulting string to a float.
Eg, if line.split(",")[2] is '1.2' and Quantity is '3' then
line.split(",")[2] * int(Quantity)
results in '1.21.21.2', which can't be converted to float. :)
Instead do
Total += float(line.split(",")[2]) * int(Quantity)
BTW, you aren't actually closing the receipt file. You're just emitting the method name and discarding it. So change
receipt.close
to
receipt.close()
Even better: use with blocks to open all your files so they get closed automatically.
I should also mention that the plain exit() function is primarily intended for use in the interactive interpreter, and it's not guaranteed to exist in all environments. To ensure portability use sys.exit() instead. OTOH, it's not really needed here, you can just break out of that while loop.
One reason can be in inputing the Promo_Code , you are using input so if your promo code is abcdefgh then you must input it as 'abcdefgh' or "abcdefgh" because input in python 2 cannot take automatic decisions . For sake of simplicity always use raw_input() for inputting strings,
Also in your elif convert reciept.close to reciept.close().
I am completely new to any coding at all.
As one of my first little tasks I tried to design a program comparing numbers. I wanted to add a function that distinguishes "pi" and "e" entries and converts them into respective floats. This function, however, doesnt work fine.
# the user is prompted to insert a value. This will be stored `enter code here`as "input1"
input1=input("insert a number:")
# decide whether the input is a number or a word. Convert words `enter code here`into numbers:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", (number))
elif pismeno == "e":
number= float(2.71)
print ("word e converted to number:", (number))
else:
number = float(pismeno)
print (number, "is already a number. No need to convert.")
# call the convert function onto the input:
convert(input1)
print ("The number you chose is:",input1)*
I guess that it has something to do with the output being stored inside the function and not "leaking" outside to the general code. Please keep in mind that I have literally NO experience so stick to a child language rather than the usual professional speech.
If you are writing a function, you need a return statement. A simplified example of your code:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", number)
return number
else:
....
....
input1=input("insert a number:")
print(convert(input1))
I really suggest you to study basic concepts of programming. You may start here: https://www.learnpython.org/. More about functions: https://www.learnpython.org/en/Functions
The number you chose is: pi" instead of "The number you chose is: 3.14"
Your current final print just prints the input you originally gave it (input1)
You need to provide a way to return a value from the function and then set that to a variable where you call it
def convert(pismeno):
... Code ...
return number
# call the convert function onto the input:
output_num = convert(input1)
print ("The number you chose is:",output_num )