loop fails to terminate once conditions are met - python

I am trying to get my function to end the loop once it hit the return clause but it fails to do so.
Explanations rather than direct code editing would be appreciated.
def Menu():
UserMenu = True
print ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
while UserMenu not in ("U", "E", "Q"):
print("\n Error: Choice must be U, E or Q")
return UserMenu
# Function designed to retrieve first name only from fullname entry.
def get_first_name(name):
first=[""]
i = 0
while i < len(name) and name[i] !=" ":
first += name[i]
i += 1
return name[:i]
# Function designed to retrieve first initial of last name or first initial of first name if only one name input.
def get_last_initial(name):
j = len(name) - 1
while j >= 0 and name[j] !=" ":
j-=1
return name[j+1]
# Function that generates username based upon user input.
def get_username():
name = raw_input("Please enter your Full Name: ")
username = get_first_name(name) + get_last_initial(name)
return username.lower()
# Function to generate exponential numbers based upon usser input.
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*",
power = power -1
return "=%d" % exponential
print Menu()
while UserMenu != "Q":
if UserMenu is "U":
UserMenu = raw_input("Please enter your Full Name: ")
print "your username is %s" % get_username()
else:
print print_exponential()
print Menu()
This is the whole program, hope it helps!

You need to update the value of UserMenu inside the loop, or else entering the loop will inherently be an infinite loop:
def Menu():
UserMenu = raw_input("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
while UserMenu not in ("U", "E", "Q"):
UserMenu = raw_input("\n Error: Please input only U, E or Q:")
return UserMenu
...
all your other functions
...
user_choice = Menu()
while user_choice != "Q":
if user_choice == "U":
print "your username is %s" % get_username()
else:
print_exponential()
user_choice = Menu()
By getting new input in the loop, it will be able to meet the criteria that controls the loop. The loop you wrote will just print then check UserMenu again without changing it, so the loop will never exit.

Managed to sort out my problem using the following code.
def Menu():
result = raw_input ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""").upper()
while result not in ("U", "E", "Q"):
print("\n Error: Please input only U, E or Q:")
result = raw_input ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""").upper()
return result
# Function designed to retrieve first name only from fullname entry.
def get_first_name(full_name):
i = 0
while i < len(full_name) and full_name[i] !=" ":
i += 1
return full_name[:i]
# Function designed to retrieve first initial of last name or first initial of first name if only one name input.
def get_last_initial(full_name):
j = len(full_name) - 1
while j >= 0 and full_name[j] !=" ":
j-=1
return full_name[j+1]
# Function that generates username based upon user input.
def get_username():
username = get_first_name(full_name) + get_last_initial(full_name)
return username.lower()
# Function to generate exponential numbers based upon user input.
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*",
power = power -1
return "=%d" % exponential
choice = Menu()
while choice != "Q":
if choice == "U":
full_name = raw_input("Please enter your Full Name:")
print "your username is %s" % get_username()
else:
print print_exponential()
choice = Menu()

Related

How do I reset my calculator, when I enter "$" to input , instead of a number , python

I need to reset this calculator when user enter "$" instead first or second input number or user enter "$" end of the input number (ex: 5$,20$).
the (a,b) is input number1 and number2. it was assigned as global varibles.
select_op(choice) is function, running the operation that user need. input_function() is function for input two numbers.
# Functions for arithmetic operations.
def add(a,b):
return (a+b) # 'a' and 'b' will add.
def subtract(a,b):
return (a-b) # 'b' substract from 'a'.
def multiply(a,b):
return (a*b) #'a' multiply by 'b'.
def divide(a,b):
if b == 0 : .
return None
else:
return (a/b) # 'a' divided by 'b'.
def power(a,b):
return (a**b) # 'a' power of 'b'.
def remainder(a,b):
if b == 0:
return None
else:
return (a%b) # reminder of 'a' divided by 'b'.
#this function for out put of operation
def select_op(choice): #this function will select operation
if choice == "+":
input_function()
print(a,' + ',b,' = ',add(a,b))
elif choice == "-":
input_function()
print(a,' - ',b,' = ',subtract(a,b))
elif choice == "*":
input_function()
print(a,' * ',b,' = ',multiply(a,b))
elif choice == "/":
input_function()
if b==0:
print("float division by zero")
print(a,' / ',b,' = ',divide(a,b))
elif choice == "^":
input_function()
print(a,' ^ ',b,' = ',power(a,b))
elif choice == "%":
input_function()
if b==0:
print("float division by zero")
print(a,' % ',b,' = ',remainder(a,b))
elif choice == "#": #if choice is '#' program will terminate.
return -1
elif choice == "$": #if choice is '$' program reset.
return None
else:
print("Unrecognized operation")
#this function for input two operands.
def input_function():
number1=float(input("Enter first number: "))
number2=float(input("Enter second number: "))
global a,b
a=number1
b=number2
return a,b
#loop repeat until user need to terminate.
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(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
Be sure to check whether the string returned from input() ends with a "$" before converting it to a float.
To reset when a user types something that ends with "$", you could throw an exception to break out of your calculator logic and start over. We'll surround the stuff inside your while loop with a try/catch, so that the exception doesn't stop your program, but merely starts a new iteration in the while loop.
# I omitted all your other functions at the start of the file
# but of course those should be included as well
class ResetException(Exception):
pass
#this function for input two operands.
def input_function():
s = input("Enter first number: ")
if s.endswith("$"):
raise ResetException()
number1=float(s)
s = input("Enter second number: ")
if s.endswith("$"):
raise ResetException()
number2=float(s)
global a,b
a=number1
b=number2
return a,b
#loop repeat until user need to terminate.
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
try:
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
except ResetException:
pass

How to make it my code go back to a specific while loop in python?

I'm new to Python and I am trying to create a simple calculator. Sorry if my code is really messy and unreadable. I tried to get the calculator to do another calculation after the first calculation by trying to make the code jump back to while vi == true loop. I'm hoping it would then ask for the "Enter selection" again and then continue on with the next while loop. How do I do that or is there another way?
vi = True
ag = True
while vi == True: #I want it to loop back to here
op = input("Input selection: ")
if op in ("1", "2", "3", "4"):
vi = False
while vi == False:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
break
#Here would be an If elif statement to carry out the calculation
while ag == True:
again = input("Another calculation? ")
if again in ("yes", "no"):
ag = False
else:
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
exit()
elif again == "yes":
print("okay!")
vi = True #I want this part to loop back
Nice start. To answer your question about whether there's another way to do what you're looking for; yes, there is generally more than one way to skin a cat.
Generally, I don't use while vi==True: in one section, then follow that up with while vi==False: in another since, if I'm not in True then False is implied. If I understand your question, then basically a solution is to nest your loops, or call one loop from within the other. Also, it seems to me like you're on the brink of discovering the not keyword as well as functions.
Code
vi = True
while vi:
print("MENU")
print("1-Division")
print("2-Multiplication")
print("3-Subtraction")
print("4-Addition")
print("Any-Exit")
op = input("Input Selection:")
if op != "1":
vi = False
else:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
print("Placeholder operation")
ag = True
while ag:
again = input("Another calculation? ")
if again not in ("yes", "no"):
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
ag = False
vi = False
elif again == "yes":
print("okay!")
ag = False
Of course, that's a lot of code to read/follow in one chunk. Here's another version that introduces functions to abstract some of the details into smaller chunks.
def calculator():
vi = True
while vi:
op = mainMenu()
if op == "\n" or op == " ":
return None
x, y = getInputs()
print(x + op + y + " = " + str(eval(x + op + y)))
vi = toContinue()
return None
def mainMenu():
toSelect=True
while toSelect:
print()
print("\tMENU")
print("\t/ = Division; * = Multiplication;")
print("\t- = Subtract; + = Addition;")
print("\t**= Power")
print("\tSpace or Enter to Exit")
print()
option = input("Select from MENU: ")
if option in "/+-%** \n":
toSelect = False
return option
def getInputs():
inpt = True
while inpt:
x = input("insert first number: ")
y = input("insert second number: ")
try:
tmp1 = float(x)
tmp2 = float(y)
if type(tmp1) == float and type(tmp2) == float:
inpt = False
except:
print("Both inputs need to be numbers. Try again.")
return x, y
def toContinue():
ag = True
while ag:
again = input("Another calculation?: ").lower()
if again not in ("yes","no"):
print("Please input a 'yes' or a 'no'.")
if again == "yes":
print("Okay!")
return True
elif again == "no":
print("Done, Thank you for using Calculator!")
return False

Encryption / Decryption String Indices Must Be Integers

I have spent a lot of time creating this encryption program that is specific to an assignment. The encryption works perfectly, i thought i would be able to copy the code and do the opposite to decrypt the message, however i receive the error:
letter = encryptionCharacters[temp_k]
"TypeError: String indices must be integers"
Not sure if anyone can fix this issue to be able to decrypt a message, but hopefully someone can give me some help.
Steps to use the program:
Select option 1 by entering that number from the menu.
Enter 854417 as the number
Then press 2 and choose a message to encrypt / decrypt.
from itertools import cycle
listOfDigits = []
listOfIllegalCharacters = []
encryptionCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz .'
encryptedMessageLettersPosition = []
decryptedMessageLettersPosition =[]
encryptedMessageList = []
def main(): #This Function is the base of the main menu
print()
print("********* Welcome to the Encryption Program *********")
print()
while True: #Start of while loop to get the users choice.
try: #Start of try method.
choice = int(input("""
1: Set Person Number
2. Encrypt a Message
3. Decrypt a Message
4. Quit
Please Choose an Option (1 - 4): """)) #Interactive menu itself taking in the users option as an integer.
except ValueError: #End of try method, in order to catch the possible value error of entering a string instead of an integer.
print("!!!!!!ERROR!!!!!!")
print()
print("ERROR: Choice was not valid!")
print("Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main() #Call to menu method (a.k.a restart).
if choice == 1:
personNumberInput() #Call to personNumberInput method, which allows the user to enter their personal ID number for the encryption.
elif choice == 2:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageEncrypt()
elif choice == 3:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageDecrypt()
elif choice == 4:
menuQuit()
else:
print()
print("!!!!!!ERROR!!!!!!") #If none of the options are chosen, restart and provide a suitable error message.
print()
print("You must only select 1, 2, 3 or 4.")
print("Please Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main()
def menuQuit(): #This function is the 4th option on the menu.
print()
userOption = input("Are you sure you want to Quit / Exit the Program? (Y/N): ") #Taking the users input to get their decision.
if userOption == "y":
exit()
elif userOption == "Y":
exit() #Exit the program if the user confirms their choice with "y" or "Y".
else:
print()
print("You have been returned to the Main Menu")
main() #Returning the user to the menu for any other option including "n" or "N".
def personNumberInput():
while True:
try:
print()
personNumber = int(input("Please enter your Person Number: ")) #Checking the input from the user.
except ValueError: #Catching the value error of unexpected value (non integer).
print()
print("ERROR: Person Number contained a non integer, Try Again")
continue
else:
personNumberInt = len(str(abs(personNumber))) #Getting the length of the string as well as the absolute value of each digit entered.
break
while True:
if (personNumberInt) != 6: #If the length of the number entered is not 6, try again.
print()
print("ERROR: Person Number length not equal to 6, Try Again")
return personNumberInput()
else:
print()
print ("The Person Number you have entered is:", personNumber)
print ("Ready to Encrypt / Decrypt a Message")
personNumberDigits = [int(x) for x in str(personNumber)]
listOfDigits.extend(personNumberDigits)
break
def messageEncrypt():
print()
message = input("Please Enter a Message to Encrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit - value*3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
print()
print ("Your message has been Encrypted!")
print ("Encrypted Message Output:",(''.join(encryptedMessageList)))
encryptedMessageLettersPosition.clear()
encryptedMessageList.clear()
def messageDecrypt():
print()
message = input("Please Enter a Message to Decrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit + value/3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
main()
Try making temp_k an integer using int()
temp_k = int( k % len(encryptionCharacters) )
letter = encryptionCharacters[temp_k]
Some of the values in encryptedMessageLettersPosition are floats, not integers.
Therefore temp_k = k % len(encryptionCharacters) sometimes returns a float value, and you cannot use a float as a string index.

possible global variable issue?

I am working on this homework assignment and I am stuck on what I know to be a very simple problem. The premise of the code is a petty cash system in which the user can make deposits, withdraws, and get their current balance.
My problem is that the withdraws and deposits don't seem to be going through my Account class. Is it a global variable issue? I'll be adding timestamps later. Thank you in advance.
import datetime
import time
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
def yesno(prompt):
ans = raw_input(prompt)
return (ans[0]=='y' or ans[0]=='Y')
def run():
done = 0
while not done:
user_options()
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
u = raw_input("Please select a letter option: ").lower()
user_input(u)
def user_input(choice):
account = Account(0.00)
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
#now = datetime.datetime.now()
Python Version: 2.7.2
The problem is:
account = Account(0.00)
Every time user_input is called, you create a new, empty account. Since user_input is called from user_options which is called inside the while loop in run, this happens before every transaction.
You need to move that line out of the loop, for example:
def run():
done = 0
global account # just showing you one way, not recommending this
account = Account(0.00)
while not done:
user_options()
print
done = not yesno("Do another? ")
print
You don't need global variables, just restructure the code slightly like this
def run():
account = Account(0.00)
done = 0
while not done:
user_option = user_options()
user_input(user_option, account)
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
return raw_input("Please select a letter option: ").lower()
def user_input(choice, account):
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
You can still do more to make the code nicer, this is just enough to get the account part working

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

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

Categories