Python Calculator and understanding input errors: - python

I've created a small calculator in python which picks up input errors, although it only runs once.
I was wondering is there a better way of doing this using While loop or If-else statements rather than using try-catch all the time. As try-except should only be used in exceptional circumstances -
What I want is when user inputs an incorrect number, i.e. a string. It errors out and asks again,
the user inputs again the correct number and it works. But using a while loop or If-statement instead of try-except
The below program works fine although it only runs once, can you make it continously loop after it finishes. I can add the other operators in later...
Thanks,
answer = True
while answer:
try:
num1 = int(input ("Enter first number: "))
break
except:
pass
print ("Please try again: ")
operator = input ("")
num2 = int (input ("Enter second number: "))
if (operator == '+'):
print (num1 + num2)
answer = False

1. Using try/except is correct. Invalid user input is an "exceptional circumstance".
Your code already asks the user over and over for input until they provide a valid input (for the first number). This is correct. You don't need the answer variable, since it's not being used anyway. You can just use while True:
while True:
try:
num1 = int(input ("Enter first number: "))
break
except:
print ("Please try again: ") # You don't need 'pass'
You can do this for each input. Also, you can place that code inside a function (e.g. read_number()) and call it for both numeric inputs.
2. To make the program restart after it is over, place the whole thing inside a while True loop:
while True:
# Your program here
To make things more organized, you can put your calculator code inside a function, and call that function inside the while True loop:
def calculator():
while True:
try:
num1 = int(input ("Enter first number: "))
break
except:
print ("Please try again: ")
operator = input ("")
while True:
try:
num2 = int(input ("Enter second number: "))
break
except:
print ("Please try again: ")
if (operator == '+'):
print (num1 + num2)
# main program
while True:
calculator()

Related

How to break while loop when two conditions are true - Calculator

I'm building my first calculator. Trying to implement While loop to get a number through user input. I want the While to break once user put a number.
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
Try this:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
Another method you can try is to have num1 and do the following in the while loop:
if type(num1) is int:
break
What this does is check the type of the variable num1. If it is an integer, int, then it breaks out of the while loop.
I want the While to break once user put a number.
You already are doing that in the condition for your while loop by having type(num) != int so your while loop should stop after the user enters an integer.
You have several errors here:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
The break statement shoud be inside the loop, but the indentation is wrong. As you write, it is after the loop (hence useless). Also, when you read from standard input, you always get a string even if it is a number. So when you check type(num1) != int this is always false. You must convert num1 with int() each time you read from standard input, not only the first time:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
Here I try to convert to an integer the string read from stdin. If it works, I break the loop immediately. If it does not work (the except clause) I check how many attempts have been done, and break the loop if the attempts are equal to 5.

Multiple try statements; returning to the corresponding try statement instead of the first input

I am trying to get the program to loop back to the second try statement when the user correctly inputs a number for the first input but does not for the second input.
The code:
print ("We're gonna be doing some division")
while True:
try:
a=float(input("input the first number: "))
except:
print ("try again")
else:
break
pass
while True:
try:
b=float(input("input the second number: "))
except:
print ("try again")
else:
break
print ("Your final answer is: ", a/b)
EDIT: sorry this is my very first question. I am not sure how to correctly format the code portion of the question. I have tried for about 20 minutes of which lead to failure and a good amount of frustration.
EDIT2: thank you for the comments. Finally figured out how to format the question, but still needs an answer.
Here is a quick refactoring of this code that shows how you can (A) not repeat yourself, and (B) use slightly more descriptive variable names:
def get_input(prompt):
# Get a number from the user.
while True:
try:
answer = float(input(prompt))
return answer
except ValueError:
print ("try again")
def main():
print ("We're gonna be doing some division")
numerator = get_input("Input the first number: ")
denominator = get_input("Input the second number: ")
print ("Your final answer is: ", numerator/denominator)
main()
Based on what I can tell, the logic is correct in your program except for this: You don't need the pass keyword. Instead, break from the while loop when the input is correct. Also, try making sure that all of the white space is as intended. If I understand correctly, you want something like this:
a = 0.0
b = 0.0
print("We're going to do some division")
while True:
try:
a = float(input("Enter first number: "))
break
except:
print("try again")
while True:
try:
b = float(input("Enter second number: "))
break
except:
print("try again")
print("The answer is: " + str(a / b))

"Try and Except" to differentiate between strings and integers? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number)
def validation(i):
try:
result = int(i)
return(result)
except ValueError:
print("Please enter a number")
def start():
x = input("Enter Number: ")
z = validation(x)
if z != None:
#Rest of function code
print("Success")
else:
start()
start()
When the above code is executed, and an integer number is entered, you get this:
Enter Number: 1
Success
If and invalid value however, such as a letter or floating point number is entered, you get this:
Enter Number: Hello
Please enter a number
Enter Number: 4.6
Please enter a number
Enter Number:
As you can see it will keep looping until a valid NUMBER value is entered. So is it possible to use the "try and except" function to keep looping until a letter is entered? To make it clearer, I'll explain in vague structured English, not pseudo code, but just to help make it clearer:
print ("Hello this will calculate your lucky number")
# Note this isn't the whole program, its just the validation section.
input (lucky number)
# English on what I want the code to do:
x = input (luckynumber)
So what I want is that if the variable "x" IS NOT a letter, or multiple letters, it should repeat this input (x) until the user enters a valid letter or multiple letters. In other words, if a letter(s) isn't entered, the program will not continue until the input is a letter(s). I hope this makes it clearer.
You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit:
def validate_integer():
x = input('Please enter a number: ')
try:
int(x)
except ValueError:
print('Sorry, {} is not a valid number'.format(x))
return validate_integer()
return x
def start():
x = validate_integer()
if x:
print('Success!')
Don't use recursion in Python when simple iteration will do.
def validate(i):
try:
result = int(i)
return result
except ValueError:
pass
def start():
z = None
while z is None:
x = input("Please enter a number: ")
z = validate(x)
print("Success")
start()

Python does not accept my input as a real number

# Math Quizzes
import random
import math
import operator
def questions():
# Gets the name of the user
name= ("Alz")## input("What is your name")
for i in range(10):
#Generates the questions
number1 = random.randint(0,100)
number2 = random.randint(1,10)
#Creates a Dictionary containg the Opernads
Operands ={'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
#Creast a list containing a dictionary with the Operands
Ops= random.choice(list(Operands.keys()))
# Makes the Answer variable avialabe to the whole program
global answer
# Gets the answer
answer= Operands.get(Ops)(number1,number2)
# Makes the Sum variable avialbe to the whole program
global Sum
# Ask the user the question
Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
print (Sum)
global UserAnswer
UserAnswer= input()
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
def score(Sum,answer):
score = 0
for i in range(10):
correct= answer
if UserAnswer == correct:
score +=1
print("You got it right")
else:
return("You got it wrong")
print ("You got",score,"out of 10")
questions()
score(Sum,answer)
When I enter a float number into the console the console prints out this:
What is 95 * 10 Alz?
950
Please enter a correct input
I'm just curious on how I would make the console not print out the message and the proper number.
this is a way to make sure you get something that can be interpreted as a float from the user:
while True:
try:
user_input = float(input('number? '))
break
except ValueError:
print('that was not a float; try again...')
print(user_input)
the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. if it checks out, break from the (infinite) loop.
You could structure the conditional if statement such that it cause number types more than just float
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
Trace through your code to understand why it doesn't work:
UserAnswer= input()
This line offers no prompt to the user. Then it will read characters from standard input until it reaches the end of a line. The characters read are assigned to the variable UserAnswer (as type str).
if UserAnswer == input():
Again offer no prompt to the user before reading input. The new input is compared to the value in UserAnswer (which was just entered on the previous line). If this new input is equal to the previous input then execute the next block.
UserAnswer= float(input())
For a third time in a row, read input without presenting a prompt. Try to parse this third input as a floating point number. An exception will be raised if this new input can not be parsed. If it is parsed it is assigned to UserAnswer.
elif UserAnswer != float() :
This expression is evaluated only when the second input does not equal the first. If this is confusing, then that is because the code is equally confusing (and probably not what you want). The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function.
Since a string is never equal to a float this not-equals test will always be true.
print("Please enter a correct input")
and thus this message is printed.
Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior):
while True:
try:
raw_UserAnswer = input("Please enter an answer:")
UserAnswer = float(raw_UserAnswer)
break
except ValueError:
print("Please enter a correct input")

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories