Python Calculator Divide by Zero/Sqrting a Neg. Int. crashing program - python

Alright, I'm doing this for a project and whenever I attempt to have it divide by zero or square root a negative number that program closes out. I've attempted to find something I can insert into the code to make it display a message and then prompt for the value again, but everything that I've tried inserting causes the program to close out instantly when I start it up.
Here's the calculator without anything inserted to fix the crashes.
import math
def convertString(str):
try:
returnValue = int(str)
except ValueError:
returnValue = float(str)
return returnValue
def addition(a, B):
return convertString(a) + convertString(B)
def subtraction(a, B):
return convertString(a) - convertString(B)
def multiplication(a, B):
return convertString(a) * convertString(B)
def division(a, B):
return convertString(a) / convertString(B)
def sqrt(a):
return math.sqrt(convertString(a))
keepProgramRunning = True
print "Welcome to [Removed]'s 2011 4-H Project! This is a simple calculator coded in Python, which is a high-level programming language. Java, C, C++, and Perl are other high-level programming languages that you may have heard of."
while keepProgramRunning:
print ""
print "Please choose what you would like to do:"
print ""
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Square Root"
print "6) Quit Program"
choice = raw_input()
if choice == "1":
numberA = raw_input("Enter your first addend: ")
numberB = raw_input("Enter your second addend: ")
print "The sum of those numbers is:"
print addition(numberA, numberB)
elif choice == "2":
numberA = raw_input("Enter your first term: ")
numberB = raw_input("Enter your second term: ")
print "The difference of those numbers is:"
print subtraction(numberA, numberB)
elif choice == "3":
numberA = raw_input("Enter your first factor: ")
numberB = raw_input("Enter your second factor: ")
print "The product of those numbers is:"
print multiplication(numberA, numberB)
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
print "Your result is:"
print sqrt(numberA)
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
keepProgramRunning = False
else:
print "Please choose a valid option."
print "\n"
I'm not real sure what to insert and where to solve the crashes, but I think the problem lies with my placement.
I've been attempting to insert something like this:
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
Would that work? Where would I insert it? If it wouldn't work, what would and where would it go?
I've been attempting to put it after
numberB = raw_input("Enter your divisor: ")
So that section would read
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
But as I said, the program will close as soon as it opens when I do try that. Also, I know that if they inputted 0 again the program would crash. Is there any way to make it return to the line that it's under?
Also, for closing the program, the message it is supposed to display can't be read as the program is closing immediately after it's displayed, or the commands are being executed at the same time. Either way, the message can't be read. Is there any way to make the message appear in a separate dialog window that will cause the program to close when the window is closed? Or at least a way to make it delay before closing?
Please correct me if I got any terminology wrong. I'm still somewhat new to this.
And, as always, (constructive) feedback for any part of the program is always appreciated.

The problem is that you are trying to catch an exception before it is thrown. Instead, try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
while float(numberB) == 0:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)

Here's your answer without exception handling.
Essentially you just make this questionable input at the beginning of an infinite loop, but break out when you find that the input is all good.
For your square root:
elif choice == "5":
while True:
numberA = raw_input("Enter the number you wish to find the square root of: ")
if float(numberA) >= 0:
break
print "Cannot take the square root of a negative number."
print "Your result is:", sqrt(numberA)
and for division:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
while True:
numberB = raw_input("Enter your divisor: ")
if numberB != "0":
break
print "You cannot divide by zero. Please choose another divisor."
print "The quotient of those numbers is:", division(numberA, numberB)
And to make your program stall before it closes:
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
raw_input('')
keepProgramRunning = False
Cheers!

You should use exceptions, like you're already doing in convertString.
try:
result = division(numberA, numberB)
print "The quotient of those numbers is:"
print result
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."

Your format of the try:...except: statement is wrong. Try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
try:
print division(numberA, numberB)
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."

This does not answer your coding question, but I think it is worth to comment.
sqrt: The square root of a negative number is an imaginary number. Python supports complex numbers with complex(real_part, imaginary_part).
so your sqrt calculation could be written as:
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
numberA = float(numberA)
if numberA < 0:
sqrt_numberA = complex(0, sqrt(abs(numberA)))
else:
sqrt_numberA = sqrt(numberA)
print "Your result is:", sqrt_numberA
division: A division by 0 is infinite. Python indicates infinite with 'inf'. In fact, it returns 'inf' with numbers higher than 1E309:
>>> 1E309
inf
and the division of two of these numbers produces 'nan'
>>> 1E309/1E309
nan
so that you could write:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
try:
div = division(numberA, numberB)
except ZeroDivisionError:
div = 'inf'
print "The quotient of those numbers is:", div
this code should be additionally extended to return -inf, when numberA is negative, and to take into account situations such as 0/0

Related

Python program for soccer odds

match = input('Enter match? ')
odd1 = input("Enter tip for home: ")
if(not odd1.replace(".","").isnumeric()):
print("Sorry home tip is not numeric")
exit(0)
if(float(odd1)<=1):
print("Odd cannot be less than one")
exit(0)
odd2 = input("Enter tip for draw: ")
if(not odd2.replace(".","").isnumeric()):
print("Sorry draw tip is not numeric")
exit(0)
if(float(odd2)<=1):
print("Odd cannot be less than one")
exit(0)
odd3 = input("Enter tip for away: ")
#isnumberic() is it number
if(not odd3.replace(".","").isnumeric()):
print("Sorry your tip is not numeric")
exit(0)
if(float(odd3)<=1):
print("Odd cannot be less than one")
exit(0)
print("Thank you, your odd is: ")
print("Match: ", match)
print("Home: ", odd1)
print("Draw: ", odd2)
print("Away: ", odd3)
Generally replace(val1, val2) method changes old value with a new one which is second argument. Why in this code checks if number is float. If I type float number in odd1 without replace, I am getting the message Sorry home tip is not numeric?
odd1.replace(".","") means that change every dot in the string odd1 into to nothing (means delete it) generally .replace() is used to search about a char in a string and replace it with another
for example
s = "Hello. world"
r = s.replace(".", ",")
print(r)
this code replace every dot in the string s with a comma
and then .isnumeric() tests if the value of odd1 after replacing is a number or not

How do I correctly use isinstance() in my random number guessing game or is another function needed?

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break

Comparing numbers with while loop. Python 3.8.3

I am currently new to Python and trying to construct a program that takes two integers and outputs whether they are larger, smaller than each other or both equal. I also want to add a while loop which asks for 2 more sets of integers each time, otherwise if the user types "quit" the program ends. Only issue is, I think my casting is off as when I type quit, it actually compares that. So if I typed quit twice it would state they're equal which is true rather than stop the program.
onenumber = int(input("Please enter your first number to compare:"))
twonumber = int(input("Please enter your second number to compare:"))
if onenumber > twonumber:
print (onenumber, "is the biggest!")
elif twonumber > onenumber:
print (twonumber, "is the biggest!")
else:
print ("Both are equal!")
while onenumber != "quit":
onenumber = input("Please enter your first number to compare, or type quit:")
twonumber = input("Please enter your second number to compare:")
if onenumber > twonumber:
print (onenumber, "is the biggest!")
elif twonumber > onenumber:
print (twonumber, "is the biggest!")
else:
print ("Both are equal!")
I changed your code slightly to begin in the while loop. Ideally, you want as few lines of code as you can and as you had two repeated lines I removed them.
Now that both number variables are not cast as int we can use the in-built string function .isdigit() which returns a True or False if the variable is a digit. This helps us out by ensuring there won't be an error when comparing them.
Happy to answer any questions you have!
while True:
number_one = input("Please enter your first number to compare or type 'quit':")
number_two = input("Please enter your second number to compare:")
if number_one.isdigit() and number_two.isdigit():
number_one = int(number_one)
number_two = int(number_two)
if number_one > number_two:
print(number_one, "is the biggest!")
elif number_two > number_one:
print(number_two, "is the biggest!")
else:
print("Both are equal!")
elif number_one == "quit":
print("Thanks for playing!")
exit()
else:
print("Please enter a number or type 'quit'!")
Actually your program does exactly what it should do. But think about it, your condition is stating: As long as onenumber is not "quit" execute all commands inside the while loop. So if your onenumber variable is "quit" it will still perform the comparison ONE TIME more before it ends the program. But after that your program will stop. But obviously this won't happen because an exception will occur. You can verify it with below code:
number1 = "proceed"
while number1 != 'quit':
number1 = str(input("declare number1"))
number2 = str(input("declare number2"))
try:
if int(number1) > int(number2):
print("number1 is is bigger than number2")
elif int(number1) < int(number2):
print("number2 is bigger than number1")
else:
print("both numbers are equal")
except:
pass
One solution for example without Exception handling would be the following:
number1 = "proceed"
while number1 != 'quit':
number1 = str(input("declare number1"))
number2 = str(input("declare number2"))
if number1 != 'quit':
if int(number1) > int(number2):
print("number1 is is bigger than number2")
elif int(number1) < int(number2):
print("number2 is bigger than number1")
else:
print("both numbers are equal")
Its easier to ask for forgiveness than permission.
https://docs.python.org/3.4/glossary.html
number_1 = input("Please enter your first number to compare or type 'quit':")
number_2 = input("Please enter your second number to compare:")
try:
smaller = int(number_1) < int(number_2)
same = int(number_1) is int(number_2)
if smaller:
print(number_1, "is the smaller")
else:
print(number_2, "is the biggest")
if same:
print("Both are equal")
except ValueError:
if number_1 == "quit"
print("Thanks for playing!")

python dice roll simulator, issues with quit and roll again

I'm pretty new to programming and trying to make a dice roll simulator in Python. My code is sort of a combination of two other dice programs I saw. I'm having trouble trying to get quit and re-roll working. I'm using Python 2.7.9 Any tips?
import random
def rollDice():
return random.randint(1,6)
closeProgram = 0
print "Welcome to dice simulator."
print " "
while closeProgram != "q":
numTimes = input("Enter number of dice rolls: ")
for i in range(numTimes):
print rollDice()
print "Press 'q' to quit or 'enter' to roll again."
closeProgram = input()
You need to use raw_input:
closeProgram = raw_input()
input in python 2 is basically eval(raw_input()) which apart from the fact it is not going to work is also a security risk.
You can cast the input to an int instead of using input:
while closeProgram != "q":
numTimes = int(raw_input("Enter number of dice rolls: "))
for i in range(numTimes):
print rollDice()
closeProgram = raw_input("Press 'q' to quit or 'enter' to roll again.")
You should also use a try/except to catch user input that cannot be cast:
while closeProgram != "q":
try:
numTimes = int(raw_input("Enter number of dice rolls: "))
except ValueError:
print("Integer values only allowed")
continue
for i in range(numTimes):
print rollDice()
closeProgram = raw_input("Press 'q' to quit or 'enter' to roll again.")

How to properly use the "not" operator?

I'm writing this program that is basically a limited calculator. I'm trying to make it so that if the user enters let's say "Power" instead of the number 1 for the desired mode, it prints out "Invalid selection". The same goes if they attempt to write "Quadratics" instead of 2 and so on for the rest.
#CALCULATOR
print("MY CALCULATOR")
print("1. Powers")
print("2. Quadratics")
print("3. Percents")
print("4. Basic Ops")
choice = int(input("Please enter your desired mode: "))
if choice == 1:
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
power = base**exponent
if choice == 2:
print("Please enter the values for A/B/C: ")
a = int(input("A: "))
b = int(input("B: "))
c = int(input("C: "))
I tried doing:
if choice not == 1:
print("Invalid Selection")
and
if choice not 1:
print("Invalid Selection")
but they don't seem to work. If you could please tell me what I am doing wrong. Thank you.
not is not a function. It is an operator.
The correct usage is to put it before an expression:
if not (choice == 1):
However in this case, it's much better to use != (not equal) instead:
if choice != 1:

Categories